0

Considering the following label:

foo:
    dw 0
    dd 0

Now how can one access the double word or dd(word?) under the foo label from another label?

bar: ;Subroutine
    mov eax, [foo] ;Now how can I move the value stored in foo's dw into eax for example?
                   ;I assume this isn't the correct way?
    add eax, 01h   ;Do something with the value
    mov [foo], eax ;Store it back into foo's dw
    ret

I am aware that there may be answers to this in documentations etc. but I'm lacking the proper terminology to find any good results using Google.

Cœur
  • 37,241
  • 25
  • 195
  • 267
The amateur programmer
  • 1,238
  • 3
  • 18
  • 38

2 Answers2

3

dw declares a word, which on x86 platforms is 16 bits. The size of eax is 32 bits (a doubleword). Hence, using mov eax,[foo] would usually be a bad idea.

Imagine that you have the following:

foo: dw 0x1122
     dd 0x33445566

What you'd get in eax if you did mov eax,[foo] is 0x55661122. The CPU just reads whatever it finds at the given address as if it was a doubleword (so long as you don't try to access data not allocated to your program), without caring about what that data might be.

If you want to get just 0x1122 you could read it into ax (the low word of eax): mov ax,[foo]. Note that the upper word of eax will remain unchanged.

If you want to get 0x1122 into eax you should use the zero-extending variant of mov: movzx eax,word [foo]. This will read just the first word located at foo, zero-extend it into a doubleword, and place the result in eax.

If you wanted to read the doubleword you've declared (0x33445566 in my example), you would use mov eax,[foo+2].

Michael
  • 57,169
  • 9
  • 80
  • 125
  • Thank you for good answer. Btw what does the `d` stand for then if it's not for word? – The amateur programmer Aug 06 '14 at 13:05
  • 1
    Depends on which `d` you're talking about. If you mean the first `d` in `db`/`dw`/`dd`/etc, then it probably stands for something like _declare_. The second `d` in `dd` stands for `dword` or `doubleword` (which on the x86 is 32 bits). – Michael Aug 06 '14 at 13:34
  • 1
    @Theamateurprogrammer: I think `db/dw/dd` stands for `data byte/word/dword`, or maybe `define byte/word/dword`. I don't think "declare" makes sense, because declare is something you do with labels, not data. `foo:` delcares the label. You can have either one without the other. – Peter Cordes Dec 30 '18 at 05:01
1

data segment:

foo dw 0
    dd 0
    db 0,0

code segment:

bar:
xor eax, eax  ; set eax to zero
mov ax, [foo] ; get a word from DS:foo into ax (low word of EAX)

add eax, 01h
mov [foo], ax ; Store it back into foo's dw
ret

Some more access variations.

accessing a dword:

mov eax, [foo+2] ; get a dword word from DS:foo+2 into eax
mov [foo+2], eax ; Store it back

accessing a byte:

mov al, [foo+6] ; get a byte from DS:foo+6 into al (low byte of ax)