Skip to content

Commit 2bb42ba

Browse files
committed
Do not emit bad dynamic relocations when sections are shrunk
1 parent 48077dd commit 2bb42ba

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

src/output-chunks.cc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -923,6 +923,12 @@ void OutputSection<E>::copy_buf(Context<E> &ctx) {
923923
u64 addr = this->shdr.sh_addr + r.isec->offset + r.offset;
924924
Symbol<E> &sym = *r.sym;
925925

926+
if constexpr (is_riscv<E> || is_loongarch<E>) {
927+
i64 delta = get_r_delta(*r.isec, r.offset);
928+
loc = (Word<E> *)(buf + r.isec->offset + r.offset - delta);
929+
addr -= delta;
930+
}
931+
926932
switch (r.kind) {
927933
case ABS_REL_NONE:
928934
case ABS_REL_RELR:
@@ -1103,6 +1109,7 @@ void OutputSection<E>::scan_abs_relocations(Context<E> &ctx) {
11031109
if (ctx.arg.pack_dyn_relocs_relr)
11041110
for (AbsRel<E> &r : abs_rels)
11051111
if (r.kind == ABS_REL_BASEREL &&
1112+
!(r.isec->shdr().sh_flags & SHF_EXECINSTR) &&
11061113
r.isec->shdr().sh_addralign % sizeof(Word<E>) == 0 &&
11071114
r.offset % sizeof(Word<E>) == 0)
11081115
r.kind = ABS_REL_RELR;

test/textrel.sh

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/bin/bash
2+
. $(dirname $0)/common.inc
3+
4+
cat <<EOF | $CC -o $t/a.o -c -xc - -fno-PIE
5+
void hello();
6+
int main() { hello(); }
7+
EOF
8+
9+
cat <<EOF | $CC -o $t/b.o -c -xc - -fno-PIE
10+
#include <stdio.h>
11+
12+
__attribute__((section(".text")))
13+
int (*fn)(const char *s) = puts;
14+
15+
void hello() {
16+
puts("Hello world");
17+
}
18+
EOF
19+
20+
$CC -B. -o $t/exe $t/a.o $t/b.o -no-pie
21+
$QEMU $t/exe | grep -q 'Hello world'

test/textrel2.sh

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/bin/bash
2+
. $(dirname $0)/common.inc
3+
4+
cat <<EOF | $CC -o $t/a.o -c -xc - -fPIE
5+
#include <stdio.h>
6+
7+
void hello() {
8+
puts("Hello world");
9+
}
10+
11+
__attribute__((section(".text")))
12+
void (*p)() = hello;
13+
14+
int main() {
15+
p();
16+
}
17+
EOF
18+
19+
$CC -B. -o $t/exe1 $t/a.o -pie
20+
$QEMU $t/exe1 | grep -q 'Hello world'
21+
22+
$CC -B. -o $t/exe2 $t/a.o -pie -Wl,-z,pack-relative-relocs
23+
$QEMU $t/exe2 | grep -q 'Hello world'

0 commit comments

Comments
 (0)