2

I'm trying to write a 32 bits kernel in gcc and i'm cross-compiling it with x86_64-elf-gcc by using the -m32 flag.

It builds and runs ok, but the binary file is 129 MB!!!. I'm very sure the actual code is not that big, and the result binary is full of zeroes, using hexdump, everything in between of 0x2080 and 0x8047000 are zeroes, random hex code and GNU labels.

This is my Makefile:

C_SOURCES = $(wildcard kernel/*.c cpu/*.c lain/*.c)
HEADERS = $(wildcard kernel/*.h cpu/*.h lain/*.h)
OBJ_FILES = ${C_SOURCES:.c=.o cpu/interrupt.o}

all: run

kernel.bin: boot/kernel-entry.o ${OBJ_FILES} 
    x86_64-elf-ld -m elf_i386 -o $@ -Ttext 0x1000 $^ --oformat binary

os-image.bin: boot/mbr.bin kernel.bin
    cat $^ > $@

run: os-image.bin
    qemu-system-i386 -fda $<

%.o: %.c ${HEADERS}
    x86_64-elf-gcc -g -m32 -ffreestanding -fno-builtin -nostdlib -c $< -o $@

%.o: %.asm
    nasm $< -f elf -o $@

%.bin: %.asm
    nasm $< -f bin -o $@

clean:
    $(RM) */*.bin */*.o */*.dis
  • Interesting. I don't know the answer but one suggestion - dump the elf info with `readelf` to see if that gives you any clues on what section is contributing to that large size. – kaylum Jul 17 '22 at 22:43
  • 2
    A linker's parameter `--oformat binary` means to produce a **binary** which covers **all addresses** from 0 till the **maximum one** used by the linker, according to the linker script. You probably want to write the linker script by yourself for control addresses of the sections emitted by the linker. See also [this question](https://stackoverflow.com/questions/63106614/why-did-ld-turn-my-5-lines-of-library-less-c-into-a-100mb-binary) and [that one](https://stackoverflow.com/questions/10490658/why-does-the-oformat-binary-option-of-the-gnu-linker-place-the-data-segme). – Tsyvarev Jul 17 '22 at 23:20

1 Answers1

1

Solved using Tsyvarev solution, wrote a linker script (aka copied) similar to the one used in The little book about OS development.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 20 '22 at 12:34