Search code examples
assemblynasmx86-16qemureal-mode

NASM. Square brackets return relative location. How to find absolute?


I'm trying to print the symbol with teletype. Here's the piece of code:

mov al, [smb]
int 0x10

smb: db "X"

But it turns out that this shows any arbitrary symbol from memory rather than from this location. Seems like [] returns the relative address of the symbol. It may be expected, but the question is: how can I find the absolute address? I'm using QEMU-i386, assembling with standard NASM.

P.S. After reviewing other questions related to NASM: please, don't tell me to go check docs of NASM as a lot more people ask here a lot of simple questions about C#, but they're not sent to Richter.


Solution

  • For 64-bit code; the default is absolute addressing, and to get RIP relative addressing you'd use something like mov al, [rel smb]. However; the default can be changed with a DEFAULT REL directive; and in that case if you want absolute addressing you'd use something like mov al, [abs smb].

    For 16-bit and 32-bit code; absolute addressing is the only option (ignoring the hopefully unnecessary confusion of "absolute address encoded as relative displacement" which occurs for some jumps and calls, which can't matter for mov al, [smb]).

    For both cases (16-bit and 32-bit code, and 64-bit code); "absolute addressing" is actually an absolute offset from the segment base. For example, mov al, [smb] will implicitly use the DS segment, so if the base address of the DS segment is not zero (which is only possible for 32-bit and 16-bit code - for 64-bit code only FS and GS can have a segment base) the actual absolute address will be "segment base + absolute offset". If the segment base is zero this can be ignored ("segment base + absolute offset" = "0 + absolute offset" = "absolute offset").

    Of course how the absolute offset is determined depends on which section it is in and where the section begins; which (depending on output file format - flat binary vs. object file) depends on an org directive, or section definitions, or a linker.