3

My teacher asked me to write code into MBR of a virtual machine on a virtual box, I firstly use nasm to create a binary file, for instance, like this:

nasm my_file.asm -o my_file.bin

And I directly use dd command to write into the vhd:

dd if=my_file.bin of=machine.vhd bs=512 const=1 conv=notrunc

After I boot the virtual machine it did as my expectation.

But what confused me is that we seemingly lose the link process. When we want to get an executable file on computers, we do need a linker to help us do some critical works(like dd something..). But this time we directly use the bin file. So why we can use it in that way?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
PoLomy
  • 31
  • 2
  • 7
    Because you are using NASM's BIN file generation which makes NASM skip the linking process and generate all the code and addresses at assembly time itself. You can use NASM to generate ELF objects that can be linked with a linker by using something like `-f elf32` (the default is `-f bin`). `-f elf32` would generate ELF objects that can be linked with a linker like LD – Michael Petch Mar 24 '21 at 13:15
  • 1
    https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html shows how to use NASM's flat-binary output to manually generate ELF headers to make a tiny Linux ELF executable. An assembler like NASM can assemble any arbitrary bytes into its output file. – Peter Cordes Mar 24 '21 at 13:35
  • 3
    Technically, the `-f bin` output format of NASM is considered an internal linker that is built into NASM's output format. – ecm Mar 24 '21 at 13:48
  • 3
    In the good old days just after we stopped punching holes in cards by hand, the assemblers would generate binary files directly. Thus directives like ORG, so you didnt need a linker. Some of that legacy is still visible today. – old_timer Mar 24 '21 at 14:14
  • 1
    Also note that manually assembling metadata is exactly what you're doing with `times 510-($-$$) db 0` / `dw 0xAA55` to put the boot signature at the end of the 512-byte MBR; not fundamentally different from using `-fbin` and manually outputting ELF metadata. It's just a lot simpler :P – Peter Cordes Mar 24 '21 at 15:41
  • 1
    Source for my statement on the built-in `-f bin` linker: https://bugzilla.nasm.us/show_bug.cgi?id=3392655#c2 "`org 7C00h` is a linker directive (just because in the case of bin/ihex/srec formats the linker is built into NASM doesn't change that it is still a linker.)" – ecm Mar 25 '21 at 15:23

0 Answers0