Skip to content

Commit 3cc58a3

Browse files
mykouHWHalf-spring
authored andcommitted
[lld][ELF] Fix crash when relocations proceed relocated section
Fix the error generated during the linking process when the relocation section is placed before the relocated section and the relocated section is not defined in the linker script.
1 parent 507ff08 commit 3cc58a3

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

lld/ELF/LinkerScript.cpp

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1037,10 +1037,16 @@ void LinkerScript::addOrphanSections() {
10371037
if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER))
10381038
continue;
10391039

1040-
if (auto *sec = dyn_cast<InputSection>(isec))
1041-
if (InputSectionBase *rel = sec->getRelocatedSection())
1042-
if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
1040+
if (auto *sec = dyn_cast<InputSection>(isec)) {
1041+
if (InputSectionBase *relocated = sec->getRelocatedSection()) {
1042+
// Ensure creation of OutputSection for relocated section before
1043+
// relocation section
1044+
if (auto *relIS = dyn_cast_or_null<InputSectionBase>(relocated))
10431045
add(relIS);
1046+
if (auto *relIS = dyn_cast_or_null<InputSectionBase>(relocated->parent))
1047+
add(relIS);
1048+
}
1049+
}
10441050
add(isec);
10451051
if (ctx.arg.relocatable)
10461052
for (InputSectionBase *depSec : isec->dependentSections)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# REQUIRES: x86
2+
# RUN: rm -rf %t && mkdir -p %t
3+
# RUN: split-file %s %t && cd %t
4+
5+
## Test that lld's orphan section placement can handle a relocatable link where
6+
## the relocation section is seen before the relocated section.
7+
8+
## Create a relocatable object with the relocations before the relocated section
9+
# RUN: llvm-mc -filetype=obj -triple=x86_64 foo.s -o foo.o
10+
# RUN: ld.lld -r foo.o -T script.ld -o foo_mc.o
11+
12+
## Rename the sections to make them orphans
13+
# RUN: llvm-objcopy \
14+
# RUN: --rename-section .text=.com.text \
15+
# RUN: --rename-section .rela.text=.rela.com.text \
16+
# RUN: foo_mc.o foo_mc.o
17+
18+
# RUN: ld.lld -r foo_mc.o -T script.ld -o foo_mc_after.o
19+
# RUN: llvm-readelf -S foo_mc_after.o | FileCheck %s
20+
# CHECK: .com.text PROGBITS 0000000000000000 000040 000007 00 AX 0 0 16
21+
# CHECK-NEXT: .rela.com.text RELA 0000000000000000 000048 000018 18 I 4 1 8
22+
23+
#--- foo.s
24+
.text
25+
.globl foo
26+
.p2align 4
27+
.type foo,@function
28+
foo:
29+
mov $bar, %rax
30+
31+
#--- script.ld
32+
SECTIONS
33+
{
34+
.rela.text 0 : { *(.rela.text) }
35+
.text 0 : { *(.text) }
36+
}
37+

0 commit comments

Comments
 (0)