Index: ELF/InputFiles.cpp =================================================================== --- ELF/InputFiles.cpp +++ ELF/InputFiles.cpp @@ -404,8 +404,14 @@ // from the output, so returning `nullptr` for the normal case. // However, if -emit-relocs is given, we need to leave them in the output. // (Some post link analysis tools need this information.) - if (Config->EmitRelocs) - return make>(this, &Sec, Name); + if (Config->EmitRelocs) { + if (!isa>(Target)) + fatal(toString(this) + ": --emit-relocs for relocations sections " + "pointing to .eh_frame is not supported"); + InputSection *RelocSec = make>(this, &Sec, Name); + cast>(Target)->DependentSection = RelocSec; + return RelocSec; + } return nullptr; } } Index: ELF/LinkerScript.cpp =================================================================== --- ELF/LinkerScript.cpp +++ ELF/LinkerScript.cpp @@ -272,6 +272,15 @@ for (InputSectionBase *S : V) { S->Live = false; reportDiscarded(S); + + // If we discard a section, we also should discard a dependent section. + // For example if linkerscript discards .text section, + // code below will discard .rel[a].text dependent section, which + // is impossible and useless to keep then. Used for --emit-relocs. + InputSection *IS = dyn_cast>(S); + if (!IS || !IS->DependentSection || !IS->DependentSection->Live) + continue; + discard({IS->DependentSection}); } } Index: test/ELF/linkerscript/emit-reloc-discard.s =================================================================== --- test/ELF/linkerscript/emit-reloc-discard.s +++ test/ELF/linkerscript/emit-reloc-discard.s @@ -0,0 +1,14 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t.o +# RUN: echo "SECTIONS { /DISCARD/ : { *(.bbb) } }" > %t.script +# RUN: ld.lld --emit-relocs --script %t.script %t.o -o %t1 +# RUN: llvm-readobj -r %t1 | FileCheck %s + +# CHECK: Relocations [ +# CHECK-NEXT: ] + +.section .aaa,"",@progbits +.Lfoo: + +.section .bbb,"",@progbits +.long .Lfoo