0

I put the following code into NASM:

[BITS 16]  
[ORG 0x7C00]  

TIMES 510 - ($ - $$) db 0  

and looked at it in my hex editor and found a bunch of 0s. This was sort of what I expected, but now I ask the question: What did [ORG 0x7C00] actually do to the file?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Epic8009
  • 33
  • 1
  • 8
  • 3
    In this code example the ORG directive wouldn't appear to do anything directly. It sets the offset to which all absolute addresses will be relative to. You have no absolute offsets in this do nothing code so you don't see the difference. Define some memory to hold some data and move data to that address (via a label). You should note a difference in the memory address if you change the org directive. – Michael Petch Oct 18 '17 at 13:25
  • 2
    Just add `mov ax,[$]` under `ORG` and produce the binary, it will start with bytes `a1 00 7c 00` (i.e. the `a1` instruction has hard offset `0x7C00` encoded in it, because after `ORG` the next instruction is treated as it will land to 0x7C00 offset in memory, i.e. `$ == 0x7C00`). The docs: [7.1.1 ORG: Binary File Program Origin](http://www.nasm.us/doc/nasmdoc7.html#section-7.1.1) (interestingly for *me*, the listing file shows the opcodes before "linking", i.e. `A1[0000]` ... that's sort of unfortunate). – Ped7g Oct 18 '17 at 13:43

1 Answers1

4

The ORG instruction is used to provide a "hint" to the assembler and the linker for the resulting object file. It allows you to specify the base address of the section of the file.

When creating "functions" (things that you might CALL), if those are sufficiently distant from where you are calling from, the assembler will need to use an absolute address for the call rather than an offset from the current instruction. The ORG instruction effectively locks the code in place, making it non-position independent code.

In practice, unless you are writing long code blocks, the majority of the JMP and CALL instructions will be SHORT or NEAR, allowing for simple offsets to be used.

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
  • 3
    In NASM the `ORG` directive doesn't apply when you output to an intermediate object, just the `bin` target. It's not just a hint, it is what NASM needs to determine where to start offsets from when outputting binary files directly. The absence of an ORG directive results in an origin point of 0. If you attempt to use ORG and output to something like an elf object it should error out. – Michael Petch Oct 18 '17 at 14:57
  • 2
    Are you sure NASM will emit a `far call ptr16:16` when a `call` is out of range for a near `call rel16`? That wouldn't make sense, because a far call pushes more than just a return address. (There are no absolute direct near calls, and I doubt NASM would emit `mov ax, target` / `call ax` either.) Anyway, there are lots of ways to make position-dependent code, e.g. `mov ax, label` or `mov ax, [label]`, and ORG will come into play then. – Peter Cordes Oct 18 '17 at 15:47