5

How should I produce raw binary file from two object (.o) files?

I want the plain binary format produced by nasm -f bin when compiling a .asm file, but for .o files.

By a plain binary, I mean a file which contains only the instructions, not some extra information, as many executable files contain a lot of extra helpful information.

See http://www.nasm.us/doc/nasmdoc7.html for information on that.

PS: I want to make a "plain binary" to start in QEMU.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Pratik Singhal
  • 5,913
  • 10
  • 50
  • 93

2 Answers2

5

This brings back memories. I'm sure there is a better way to do this with linker scripts, but this is how I did it when I was young and stupid:

# compile some files
gcc -c -nostdlib -nostartfiles -nodefaultlibs -fno-builtin kernel.c -o kernel.o
gcc -c -nostdlib -nostartfiles -nodefaultlibs -fno-builtin io.c -o io.o

# link files and place code at known address so we can jump there from asm
ld -Ttext 0x100000 kernel.o io.o -o kernel.out

# get a flat binary
objcopy -S -O binary kernel.out kernel.bin

The file kernel.c started with

__asm__("call _kmain");
__asm__("ret");

void kmain(void) { ... }

The fun part is writing the loader in assembler.

Christoph
  • 158,247
  • 36
  • 176
  • 234
1

ld --oformat binary is a more direct option:

ld --oformat binary -o main.img -Ttext 0x7C00 main.o

The downside of this method is that I don't think it is possible to reuse the symbols to debug, as we'd want something like:

qemu-system-i386 -hda main.img -S -s &
gdb main.elf -ex 'target remote localhost:1234'

So in that case you should stick to objcopy. See also: https://stackoverflow.com/a/32960272/895245

Also make sure that you use your own clean linker script: https://stackoverflow.com/a/32594933/895245

Repository with working examples for some common cases:

Similar question: How to generate plain binaries like nasm -f bin with the GNU GAS assembler?

Community
  • 1
  • 1