diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp --- a/lld/ELF/LinkerScript.cpp +++ b/lld/ELF/LinkerScript.cpp @@ -1148,14 +1148,16 @@ sec->alignment = std::max(sec->alignment, sec->alignExpr().getValue()); - // The input section might have been removed (if it was an empty synthetic - // section), but we at least know the flags. - if (sec->hasInputSections) + bool isEmpty = (getFirstInputSection(sec) == nullptr); + bool discardable = isEmpty && isDiscardable(*sec); + // If sec has at least one input section and not discarded, remember its + // flags to be inherited by subsequent output sections. (sec may contain + // just one empty synthetic section.) + if (sec->hasInputSections && !discardable) flags = sec->flags; // We do not want to keep any special flags for output section // in case it is empty. - bool isEmpty = (getFirstInputSection(sec) == nullptr); if (isEmpty) sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE | SHF_EXECINSTR); @@ -1172,7 +1174,7 @@ if (sec->sectionIndex != UINT32_MAX) maybePropagatePhdrs(*sec, defPhdrs); - if (isEmpty && isDiscardable(*sec)) { + if (discardable) { sec->markDead(); cmd = nullptr; } diff --git a/lld/test/ELF/linkerscript/insert-before.test b/lld/test/ELF/linkerscript/insert-before.test --- a/lld/test/ELF/linkerscript/insert-before.test +++ b/lld/test/ELF/linkerscript/insert-before.test @@ -29,7 +29,7 @@ # CHECK2-NEXT: NULL # CHECK2-NEXT: .foo.text PROGBITS 000000000020{{.*}} [[#%x,]] 000008 00 AX # CHECK2-NEXT: .text PROGBITS [[#%x,]] [[#%x,]] 000008 00 AX -# CHECK2-NEXT: .byte PROGBITS [[#%x,]] [[#%x,]] 000001 00 WA +# CHECK2-NEXT: .byte PROGBITS [[#%x,]] [[#%x,]] 000001 00 AX # CHECK2-NEXT: .foo.data PROGBITS [[#%x,]] [[#%x,]] 000008 00 WA # CHECK2-NEXT: .data PROGBITS [[#%x,]] [[#%x,]] 000008 00 WA # CHECK2: Type {{.*}} Flg Align