Index: ELF/Writer.cpp =================================================================== --- ELF/Writer.cpp +++ ELF/Writer.cpp @@ -1688,17 +1688,20 @@ // The linker is expected to define SECNAME_start and SECNAME_end // symbols for a few sections. This function defines them. template void Writer::addStartEndSymbols() { - auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) { - // These symbols resolve to the image base if the section does not exist. - // A special value -1 indicates end of the section. + // These symbols resolve to the image base or ".text" if the section + // does not exist. Set symbol value to ".text" mitigates the possibilities + // that an relocation from .text section to these symbols overflows. + // A special value -1 indicates end of the section. + OutputSection *DefaultOutSec = findSection(".text"); + if (!DefaultOutSec && Config->Pic) + DefaultOutSec = Out::ElfHeader; + auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) { if (OS) { addOptionalRegular(Start, OS, 0); addOptionalRegular(End, OS, -1); } else { - if (Config->Pic) - OS = Out::ElfHeader; - addOptionalRegular(Start, OS, 0); - addOptionalRegular(End, OS, 0); + addOptionalRegular(Start, DefaultOutSec, 0); + addOptionalRegular(End, DefaultOutSec, 0); } }; Index: test/ELF/preinit_init_finit_placement.s =================================================================== --- /dev/null +++ test/ELF/preinit_init_finit_placement.s @@ -0,0 +1,24 @@ +// RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t +// RUN: ld.lld %t -o %t2 +// RUN: llvm-objdump -d %t2 | FileCheck %s +// REQUIRES: x86 + +.globl _start +_start: + call __preinit_array_start + call __preinit_array_end + call __init_array_start + call __init_array_end + call __fini_array_start + call __fini_array_end + +// With no .init_array section the symbols resolve to ".text". + +// CHECK: Disassembly of section .text: +// CHECK-NEXT: _start: +// CHECK-NEXT: 201000: e8 fb ff ff ff callq -5 +// CHECK-NEXT: 201005: e8 f6 ff ff ff callq -10 +// CHECK-NEXT: 20100a: e8 f1 ff ff ff callq -15 +// CHECK-NEXT: 20100f: e8 ec ff ff ff callq -20 +// CHECK-NEXT: 201014: e8 e7 ff ff ff callq -25 +// CHECK-NEXT: 201019: e8 e2 ff ff ff callq -30