Binutils LD creates huge files

不问归期 提交于 2021-02-09 11:12:05

问题


I'm trying to create as small ELF as possible. I created a test file like this (NASM syntax):

SECTION .text
dd 0xdeadbeef

With this linker script:

SECTIONS {
    .text : {
        *(.text)
    }
}

Then I checked sizes of flat binary and ELFs built two ways:

nasm -f bin -o test test.asm

It's flat binary, so 4 bytes.

nasm -f elf -o test.o test.asm
i686-elf-ld -Tlinker.ld test.o -o test

I'd expect something like 500 bytes max, but the resulting file is 4396 bytes long! There is an option however, named --strip-all, that could make this file smaller.

i686-elf-ld -Tlinker.ld test.o -o test --strip-all

4244 bytes. Still huge.

Why is LD generating so big files? Is there a way to make it smaller?


回答1:


The linker is page aligning your text section to the nearest page boundary so that demand paging can be used.

$ objdump --headers -f test

test:     file format elf32-i386
architecture: i386, flags 0x00000102:
EXEC_P, D_PAGED
start address 0x00000000

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         00000004  00000000  00000000  00001000  2**4
                  CONTENTS, ALLOC, LOAD, READONLY, CODE

Notice the "Align" column of the text section is set to 4KB. Because of the alignment is set to 4Kb and demand paging is in use (D_PAGED), the .text section is located 4Kb into the file. Your text section is only 4 bytes long.

Link with -n to disable demand paging:

$ ld -Tlinker.ld test.o -o test --strip-all -n
$ objdump --headers -f test

test:     file format elf32-i386
architecture: i386, flags 0x00000002:
EXEC_P
start address 0x00000000

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         00000004  00000000  00000000  00000060  2**4
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
$ ls -l test
-rwxrwxr-x 1 mikel mikel 240 Apr 15 12:31 test


来源:https://stackoverflow.com/questions/36649501/binutils-ld-creates-huge-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!