Index: ELF/LinkerScript.cpp =================================================================== --- ELF/LinkerScript.cpp +++ ELF/LinkerScript.cpp @@ -885,7 +885,7 @@ void LinkerScript::synchronize() { for (BaseCommand *Base : Opt.Commands) { auto *Cmd = dyn_cast(Base); - if (!Cmd) + if (!Cmd || (Cmd->Sec->Flags & SHF_LINK_ORDER)) continue; ArrayRef Sections = Cmd->Sec->Sections; std::vector ScriptSections; Index: ELF/OutputSections.cpp =================================================================== --- ELF/OutputSections.cpp +++ ELF/OutputSections.cpp @@ -127,8 +127,20 @@ template void OutputSection::finalize() { if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) { + OutputSectionCommand *Cmd = Script->getCmd(this); + // Link order may be distributed across several InputSectionDescriptions + // but sort must consider them all at once. + std::vector ScriptSections; + std::vector Sections; + for (BaseCommand *Base : Cmd->Commands) + if (auto *ISD = dyn_cast(Base)) + for (InputSection *&IS : ISD->Sections) { + ScriptSections.push_back(&IS); + Sections.push_back(IS); + } std::sort(Sections.begin(), Sections.end(), compareByFilePosition); - assignOffsets(); + for (int I = 0, N = Sections.size(); I < N; ++I) + *ScriptSections[I] = Sections[I]; // We must preserve the link order dependency of sections with the // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We Index: ELF/Writer.cpp =================================================================== --- ELF/Writer.cpp +++ ELF/Writer.cpp @@ -257,12 +257,6 @@ if (ErrorCount) return; - if (!Script->Opt.HasSections) { - if (!Config->Relocatable) - fixSectionAlignments(); - Script->fabricateDefaultCommands(); - } - for (BaseCommand *Base : Script->Opt.Commands) if (auto *Cmd = dyn_cast(Base)) OutputSectionCommands.push_back(Cmd); @@ -1230,6 +1224,12 @@ Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size(); } + if (!Script->Opt.HasSections) { + if (!Config->Relocatable) + fixSectionAlignments(); + Script->fabricateDefaultCommands(); + } + // Dynamic section must be the last one in this list and dynamic // symbol table section (DynSymTab) must be the first one. applySynthetic({InX::DynSymTab, InX::Bss, InX::BssRelRo,