[ELF] --emit-relocs: fix missing STT_SECTION when the first input section is synthetic
authorFangrui Song <i@maskray.me>
Tue, 29 Mar 2022 15:56:21 +0000 (08:56 -0700)
committerFangrui Song <i@maskray.me>
Tue, 29 Mar 2022 15:56:21 +0000 (08:56 -0700)
commit7370a489b1005e424b23bd0009af2365aef4db53
treecf9187d36e2c0cd50ed7a2a888e40a0b90cd9539
parentf0799465b2cc25738d7164774926a8ba3a63b98d
[ELF] --emit-relocs: fix missing STT_SECTION when the first input section is synthetic

addSectionSymbols suppresses the STT_SECTION symbol if the first input section
is non-SHF_MERGE synthetic. This is incorrect when the first input section is synthetic
while a non-synthetic input section exists:

* `.bss : { *(COMMON) *(.bss) }`
  (abc388ed3cf0ef7e617ebe243d3b0b32d29e69a5 regressed the case because
  COMMON symbols precede .bss in the absence of a linker script)
* Place a synthetic section in another section: `.data : { *(.got) *(.data) }`

For `%t/a1` in the new test emit-relocs-synthetic.s, ld.lld produces incorrect
relocations with symbol index 0.
```
0000000000000000 <_start>:
       0: 8b 05 33 00 00 00             movl    51(%rip), %eax          # 0x39 <bss>
                0000000000000002:  R_X86_64_PC32        *ABS*+0xd
       6: 8b 05 1c 00 00 00             movl    28(%rip), %eax          # 0x28 <common>
                0000000000000008:  R_X86_64_PC32        common-0x4
       c: 8b 05 06 00 00 00             movl    6(%rip), %eax           # 0x18
                000000000000000e:  R_X86_64_GOTPCRELX   *ABS*+0x4
```

Fix the issue by checking every input section.

Reviewed By: ikudrin

Differential Revision: https://reviews.llvm.org/D122463
lld/ELF/Writer.cpp
lld/test/ELF/emit-relocs-synthetic.s [new file with mode: 0644]