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

前端 未结 2 1391
再見小時候
再見小時候 2020-11-27 05:34

I have some NASM files that generally have the structure:

        [BITS 64]
        [ORG 0x0000000000200000]

start:
        ...

        ret
2条回答
  •  春和景丽
    2020-11-27 05:59

    objcopy -O binary

    A good option is:

    as -o test.o test.S
    ld -Ttext 0x7C00 -o test.elf test.o
    objcopy -O binary kernel.elf kernel.bin
    

    The advantage over ld --oformat binary is that it is easier to use the symbols to debug via:

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

    See also: https://stackoverflow.com/a/32960272/895245

    Linker script

    -Ttext is fine for quick and dirty testing, but for serious work you should use a script instead to increase robustness.

    Otherwise, ld will use a default script (ld --verbose) intended for userland application, which does not look like your application.

    Without further information, the minimal script I can give is:

    SECTIONS
    {
        . = 2M;
        .text :
        {
            *(.*)
        }
    }
    

    And then use it with -T:

    as --64 -o test.o test.S
    ld -T linker.ld --oformat binary -o test.bin test.o
    

    But you will likely want to modify that script based on your exact application.

    See also: Is there a way to get gcc to output raw binary?

    I have a repository with working examples for some common use cases:

    • boot sectors
    • multiboot interfacing with C

提交回复
热议问题