NASM - is this the address, value?

风格不统一 提交于 2021-01-27 22:53:52

问题


TL;DR

Is [memloc] referring to the value or the address? If it's referring to either, then why does it work both as a value and an address? (see code below, lines 4 and 5)

Full question...

Sorry for the long question. I'm confused by label dereferencing in NASM. Take this example:

01| section .text
02| ; exiting the program with exit code "15"
03|
04| mov     [memloc], 15 ; move 15 into memloc
05| push    [memloc]     ; push memloc on stack
06| mov     eax, 1       ; prepare exit syscall
07| call    kernel       ; invoke syscall
08|
09| section .data
10| memloc: dd 0    ; let's say this is at address 0x1234

When I run it, it exits with code 15. It works!
...but why? Shouldn't memlock be without braces line 4, where push presumably expects a destination?

For example:
The mov instruction at line 04 moves the value 15 to the ADDRESS of memloc:

mov     [memloc], 15 ; move 15 into mem @memloc

But line 05 pushes the VALUE stored at memloc onto the stack:

push    [memloc]     ; push value @memloc on stack

So, is [memloc] the value (15) or the address (0x1234)? What happens in theory if you mov memloc, 15 instead?

Thank you in advance.


回答1:


There's more than 1 version of the mov instruction. If the compiler (NASM) sees the square brackets around memloc it generates one form of mov and if your compiler doesn't see the square brackets around memloc it generates another form of mov.

Consider the following instructions:

mov edx, memloc
mov edx, [memloc]
mov [memloc], edx

They're all mov to/from the same destination/source register EDX but the compiler (NASM) will generate completely different opcodes for these instructions.

The 1st mov is encoded with 5 bytes 0xBA, ?, ?, ?, ?
The 2nd mov is encoded with 6 bytes 0x8B, 0x15, ?, ?, ?, ?
The 3rd mov is encoded with 6 bytes 0x89, 0x15, ?, ?, ?, ?

The 4 ?'s represent the address of memloc as assigned by NASM.
Using the example address (0x1234) in your question this would become:

The 1st mov is encoded with 5 bytes 0xBA, 0x34, 0x12, 0x00, 0x00
The 2nd mov is encoded with 6 bytes 0x8B, 0x15, 0x34, 0x12, 0x00, 0x00
The 3rd mov is encoded with 6 bytes 0x89, 0x15, 0x34, 0x12, 0x00, 0x00




回答2:


What happens in theory if you mov memloc, 15 instead?

NASM would not except this because you can't move an immediate value (15) into another immendiate value (memloc).

The mov instruction at line 04 moves the value 15 to the ADDRESS of memloc:

The instruction at line 4 does not change the address of memloc.
Just like line 5 it uses the value stored at memloc.

So, is [memloc] the value (15) or the address (0x1234)?

[memloc] is the value 15
memloc is the address 0x1234 (which you can't change after it has been set by the line 10 of your code)



来源:https://stackoverflow.com/questions/32412100/nasm-is-this-the-address-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!