Index: ELF/MapFile.cpp =================================================================== --- ELF/MapFile.cpp +++ ELF/MapFile.cpp @@ -138,6 +138,8 @@ if (!ISD) continue; for (InputSection *IS : ISD->Sections) { + if (!IS->Live) + continue; writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(), IS->Alignment); OS << indent(1) << toString(IS) << '\n'; Index: ELF/OutputSections.cpp =================================================================== --- ELF/OutputSections.cpp +++ ELF/OutputSections.cpp @@ -84,7 +84,16 @@ void OutputSection::addSection(InputSection *S) { assert(S->Live); - Live = true; + + // Adding regular sections should trigger live bit, so that we enable emiting + // this output section. Synthetic sections are exception, because we do not + // know their final status here yet. So we set Live flag here only if we + // definetely know we are going to keep this synthetic section. + if (SyntheticSection *SS = dyn_cast(S)) + Live |= !SS->empty(); + else + Live = true; + S->Parent = this; this->updateAlignment(S->Alignment); Index: ELF/Writer.cpp =================================================================== --- ELF/Writer.cpp +++ ELF/Writer.cpp @@ -1168,37 +1168,16 @@ // relocation that needs a .got, we don't want to emit .got. // // To deal with the above problem, this function is called after -// scanRelocations is called to remove synthetic sections that turn -// out to be empty. -static void removeUnusedSyntheticSections() { - // All input synthetic sections that can be empty are placed after - // all regular ones. We iterate over them all and exit at first - // non-synthetic. - for (InputSectionBase *S : llvm::reverse(InputSections)) { - SyntheticSection *SS = dyn_cast(S); - if (!SS) - return; - OutputSection *OS = SS->getParent(); - if (!SS->empty() || !OS) - continue; - - std::vector::iterator Empty = OS->Commands.end(); - for (auto I = OS->Commands.begin(), E = OS->Commands.end(); I != E; ++I) { - BaseCommand *B = *I; - if (auto *ISD = dyn_cast(B)) { - llvm::erase_if(ISD->Sections, - [=](InputSection *IS) { return IS == SS; }); - if (ISD->Sections.empty()) - Empty = I; - } +// scanRelocations to disable synthetic sections that turn out to be +// empty. If we find that section should be kept, we must update output +// section live bit to ensure it is emited. +static void disableUnusedSyntheticSections() { + for (InputSectionBase *S : InputSections) { + if (SyntheticSection *SS = dyn_cast(S)) { + SS->Live = !SS->empty(); + if (OutputSection *OS = SS->getParent()) + OS->Live |= SS->Live; } - if (Empty != OS->Commands.end()) - OS->Commands.erase(Empty); - - // If there are no other sections in the output section, remove it from the - // output. - if (OS->Commands.empty()) - OS->Live = false; } } @@ -1301,7 +1280,7 @@ return; addPredefinedSections(); - removeUnusedSyntheticSections(); + disableUnusedSyntheticSections(); sortSections(); Script->removeEmptyCommands();