Bug 26622

Summary: Support --gc-sections for SHF_MERGE sections
Product: binutils Reporter: Fangrui Song <i>
Component: ldAssignee: Not yet assigned to anyone <unassigned>
Status: UNCONFIRMED ---    
Severity: normal    
Priority: P2    
Version: unspecified   
Target Milestone: ---   
Host: Target:
Build: Last reconfirmed:

Description Fangrui Song 2020-09-15 22:12:38 UTC
% cat a.c
__attribute__((noinline)) void ppp(const char *a) {}
void used1(){ ppp("foo"); }
void used2(){ ppp("bar"); }
void used3(){ ppp("bar foo"); }
void unused(){ ppp("unused"); }

% clang -c a.c -ffunction-sections -fdata-sections -fPIC && re -S a.o G rodata                  
  [12] .rodata.str1.1    PROGBITS        0000000000000000 0000c2 000017 01 AMS  0   0  1
% ld.bfd --gc-sections -e 0 a.o -o a -u used1 -u used2 -u used3 && strings a | grep unused
   2010 unused

`unused` is in the linked image because GNU ld (and gold) do not implement --gc-sections for SHF_MERGE sections.

Since May 2015, GCC -ffunction-sections -fdata-sections -fmerge-constants places string literals into separate sections https://gcc.gnu.org/bugzilla/show_bug.cgi?id=192#c16

% gcc -c a.c -ffunction-sections -fdata-sections -fPIC -fmerge-constants && re -S a.o G rodata
  [ 5] .rodata.used1.str1.1 PROGBITS        0000000000000000 00004b 000004 01 AMS  0   0  1
  [ 8] .rodata.used2.str1.1 PROGBITS        0000000000000000 000062 000004 01 AMS  0   0  1
  [11] .rodata.used3.str1.1 PROGBITS        0000000000000000 000079 000008 01 AMS  0   0  1
  [14] .rodata.unused.str1.1 PROGBITS        0000000000000000 000094 000007 01 AMS  0   0  1

This is to make --gc-sections discard unused section pieces. However, this does not look like a good idea (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=192#c14) because the cost of a section header (sizeof(Elf64_Shdr)=64) + a section name is quite large. The object file sizes are bloated even if the final linked image is optimal.
Comment 1 Fangrui Song 2020-09-15 22:13:25 UTC
Ah, I alias `re` to readelf and `G` to `| grep` :)