Index: ELF/LinkerScript.cpp =================================================================== --- ELF/LinkerScript.cpp +++ ELF/LinkerScript.cpp @@ -753,10 +753,15 @@ if (!Cmd) continue; - if (Cmd->Phdrs.empty()) - Cmd->Phdrs = DefPhdrs; - else + if (Cmd->Phdrs.empty()) { + OutputSection *Sec = Cmd->Sec; + // Only propagate program headers to sections that are allocated. + if (Sec && (Sec->Flags & SHF_ALLOC)) + Cmd->Phdrs = DefPhdrs; + } + else { DefPhdrs = Cmd->Phdrs; + } } removeEmptyCommands(); @@ -975,8 +980,6 @@ // Add output sections to program headers. for (OutputSectionCommand *Cmd : OutputSectionCommands) { OutputSection *Sec = Cmd->Sec; - if (!(Sec->Flags & SHF_ALLOC)) - break; // Assign headers specified by linker script for (size_t Id : getPhdrIndices(Sec)) { Index: test/ELF/linkerscript/non-alloc-segment.s =================================================================== --- /dev/null +++ test/ELF/linkerscript/non-alloc-segment.s @@ -0,0 +1,28 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t.o + +## Test that non-alloc section .foo can be assigned to a segment. +# RUN: echo "PHDRS {text PT_LOAD; foo 0x12345678;} \ +# RUN: SECTIONS { \ +# RUN: .text : {*(.text .text*)} :text \ +# RUN: .foo : {*(.foo)} :foo \ +# RUN: }" > %t.script +# RUN: ld.lld -o %t --script %t.script %t.o +# RUN: llvm-readobj -elf-output-style=GNU -s -l %t | FileCheck %s + +# CHECK: Program Headers: +# CHECK-NEXT: Type +# CHECK-NEXT: LOAD +# CHECK-NEXT: : 0x12345678 + +# CHECK: Section to Segment mapping: +# CHECK-NEXT: Segment Sections... +# CHECK-NEXT: 00 .text +# CHECK-NEXT: 01 .foo + +.global _start +_start: + nop + +.section .foo + .long 0