Reputation:
A label represents the address of the first byte following it, but can I read its value? For example can I do the following?
some_label:
mov eax, some_label ; this will move the address of mov into eax?
Upvotes: 1
Views: 2963
Reputation: 137408
What you show will work in e.g. nasm
, but the result may not be what you expect.
A little more information into what you're writing would help this answer be more specific. (Typical user-mode ELF application? Stand-alone binary blob? Something else?)
Because the assembler doesn't know where (in the address space) your code may be running, the instruction you've written will cause a relocation to be generated by the assembler (if your output format supports it).
If your environment does support relocations, (e.g. an ELF object file produced by nasm -f elf
) then that should be fine; eax
will match what eip
was prior to executing that instruction. This works because that instruction was fixed-up by the loader - a relocation was applied.
If your environment does not support relocations, (e.g. a raw binary file, or other non-hosted environment) then you have a problem. If that instruction is at offset 0x100 in your binary blob, then eax
will get the value 0x100
- certainly not the actual address you're executing at. To remedy this, you need to do the relocation yourself. Unfortunately, there's no easy way to do this on x86 (32-bit). You have to do something like this:
call .getbase
.getbase:
pop ebx
sub ebx, .getbase
;; Now ebx has the base address of your linked application/blob
some_label:
mov eax, some_label
add eax, ebx
;; Now eax has the (run-time) address of some_label
The x86_64 instruction set added a RIP-relative addressing scheme, which makes this much easier:
some_lable:
lea rax, [rel some_label]
Upvotes: 5