xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 8d01ac75)
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Writer.h"
10 #include "AArch64ErrataFix.h"
11 #include "ARMErrataFix.h"
12 #include "CallGraphSort.h"
13 #include "Config.h"
14 #include "InputFiles.h"
15 #include "LinkerScript.h"
16 #include "MapFile.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "lld/Common/Arrays.h"
24 #include "lld/Common/CommonLinkerContext.h"
25 #include "lld/Common/Filesystem.h"
26 #include "lld/Common/Strings.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/Support/MD5.h"
29 #include "llvm/Support/Parallel.h"
30 #include "llvm/Support/RandomNumberGenerator.h"
31 #include "llvm/Support/SHA1.h"
32 #include "llvm/Support/TimeProfiler.h"
33 #include "llvm/Support/xxhash.h"
34 #include <climits>
35 
36 #define DEBUG_TYPE "lld"
37 
38 using namespace llvm;
39 using namespace llvm::ELF;
40 using namespace llvm::object;
41 using namespace llvm::support;
42 using namespace llvm::support::endian;
43 using namespace lld;
44 using namespace lld::elf;
45 
46 namespace {
47 // The writer writes a SymbolTable result to a file.
48 template <class ELFT> class Writer {
49 public:
50   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
51 
52   Writer() : buffer(errorHandler().outputBuffer) {}
53 
54   void run();
55 
56 private:
57   void copyLocalSymbols();
58   void addSectionSymbols();
59   void sortSections();
60   void resolveShfLinkOrder();
61   void finalizeAddressDependentContent();
62   void optimizeBasicBlockJumps();
63   void sortInputSections();
64   void finalizeSections();
65   void checkExecuteOnly();
66   void setReservedSymbolSections();
67 
68   SmallVector<PhdrEntry *, 0> createPhdrs(Partition &part);
69   void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
70                          unsigned pFlags);
71   void assignFileOffsets();
72   void assignFileOffsetsBinary();
73   void setPhdrs(Partition &part);
74   void checkSections();
75   void fixSectionAlignments();
76   void openFile();
77   void writeTrapInstr();
78   void writeHeader();
79   void writeSections();
80   void writeSectionsBinary();
81   void writeBuildId();
82 
83   std::unique_ptr<FileOutputBuffer> &buffer;
84 
85   void addRelIpltSymbols();
86   void addStartEndSymbols();
87   void addStartStopSymbols(OutputSection *sec);
88 
89   uint64_t fileSize;
90   uint64_t sectionHeaderOff;
91 };
92 } // anonymous namespace
93 
94 static bool needsInterpSection() {
95   return !config->relocatable && !config->shared &&
96          !config->dynamicLinker.empty() && script->needsInterpSection();
97 }
98 
99 template <class ELFT> void elf::writeResult() {
100   Writer<ELFT>().run();
101 }
102 
103 static void removeEmptyPTLoad(SmallVector<PhdrEntry *, 0> &phdrs) {
104   auto it = std::stable_partition(
105       phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {
106         if (p->p_type != PT_LOAD)
107           return true;
108         if (!p->firstSec)
109           return false;
110         uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
111         return size != 0;
112       });
113 
114   // Clear OutputSection::ptLoad for sections contained in removed
115   // segments.
116   DenseSet<PhdrEntry *> removed(it, phdrs.end());
117   for (OutputSection *sec : outputSections)
118     if (removed.count(sec->ptLoad))
119       sec->ptLoad = nullptr;
120   phdrs.erase(it, phdrs.end());
121 }
122 
123 void elf::copySectionsIntoPartitions() {
124   SmallVector<InputSectionBase *, 0> newSections;
125   for (unsigned part = 2; part != partitions.size() + 1; ++part) {
126     for (InputSectionBase *s : inputSections) {
127       if (!(s->flags & SHF_ALLOC) || !s->isLive())
128         continue;
129       InputSectionBase *copy;
130       if (s->type == SHT_NOTE)
131         copy = make<InputSection>(cast<InputSection>(*s));
132       else if (auto *es = dyn_cast<EhInputSection>(s))
133         copy = make<EhInputSection>(*es);
134       else
135         continue;
136       copy->partition = part;
137       newSections.push_back(copy);
138     }
139   }
140 
141   inputSections.insert(inputSections.end(), newSections.begin(),
142                        newSections.end());
143 }
144 
145 void elf::combineEhSections() {
146   llvm::TimeTraceScope timeScope("Combine EH sections");
147   for (InputSectionBase *&s : inputSections) {
148     // Ignore dead sections and the partition end marker (.part.end),
149     // whose partition number is out of bounds.
150     if (!s->isLive() || s->partition == 255)
151       continue;
152 
153     Partition &part = s->getPartition();
154     if (auto *es = dyn_cast<EhInputSection>(s)) {
155       part.ehFrame->addSection(es);
156       s = nullptr;
157     } else if (s->kind() == SectionBase::Regular && part.armExidx &&
158                part.armExidx->addSection(cast<InputSection>(s))) {
159       s = nullptr;
160     }
161   }
162 
163   llvm::erase_value(inputSections, nullptr);
164 }
165 
166 static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
167                                    uint64_t val, uint8_t stOther = STV_HIDDEN) {
168   Symbol *s = symtab->find(name);
169   if (!s || s->isDefined() || s->isCommon())
170     return nullptr;
171 
172   s->resolve(Defined{nullptr, StringRef(), STB_GLOBAL, stOther, STT_NOTYPE, val,
173                      /*size=*/0, sec});
174   s->isUsedInRegularObj = true;
175   return cast<Defined>(s);
176 }
177 
178 static Defined *addAbsolute(StringRef name) {
179   Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
180                                           STT_NOTYPE, 0, 0, nullptr});
181   sym->isUsedInRegularObj = true;
182   return cast<Defined>(sym);
183 }
184 
185 // The linker is expected to define some symbols depending on
186 // the linking result. This function defines such symbols.
187 void elf::addReservedSymbols() {
188   if (config->emachine == EM_MIPS) {
189     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
190     // so that it points to an absolute address which by default is relative
191     // to GOT. Default offset is 0x7ff0.
192     // See "Global Data Symbols" in Chapter 6 in the following document:
193     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
194     ElfSym::mipsGp = addAbsolute("_gp");
195 
196     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
197     // start of function and 'gp' pointer into GOT.
198     if (symtab->find("_gp_disp"))
199       ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
200 
201     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
202     // pointer. This symbol is used in the code generated by .cpload pseudo-op
203     // in case of using -mno-shared option.
204     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
205     if (symtab->find("__gnu_local_gp"))
206       ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
207   } else if (config->emachine == EM_PPC) {
208     // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
209     // support Small Data Area, define it arbitrarily as 0.
210     addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
211   } else if (config->emachine == EM_PPC64) {
212     addPPC64SaveRestore();
213   }
214 
215   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
216   // combines the typical ELF GOT with the small data sections. It commonly
217   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
218   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
219   // represent the TOC base which is offset by 0x8000 bytes from the start of
220   // the .got section.
221   // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
222   // correctness of some relocations depends on its value.
223   StringRef gotSymName =
224       (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
225 
226   if (Symbol *s = symtab->find(gotSymName)) {
227     if (s->isDefined()) {
228       error(toString(s->file) + " cannot redefine linker defined symbol '" +
229             gotSymName + "'");
230       return;
231     }
232 
233     uint64_t gotOff = 0;
234     if (config->emachine == EM_PPC64)
235       gotOff = 0x8000;
236 
237     s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
238                        STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
239     ElfSym::globalOffsetTable = cast<Defined>(s);
240   }
241 
242   // __ehdr_start is the location of ELF file headers. Note that we define
243   // this symbol unconditionally even when using a linker script, which
244   // differs from the behavior implemented by GNU linker which only define
245   // this symbol if ELF headers are in the memory mapped segment.
246   addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
247 
248   // __executable_start is not documented, but the expectation of at
249   // least the Android libc is that it points to the ELF header.
250   addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
251 
252   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
253   // each DSO. The address of the symbol doesn't matter as long as they are
254   // different in different DSOs, so we chose the start address of the DSO.
255   addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
256 
257   // If linker script do layout we do not need to create any standard symbols.
258   if (script->hasSectionsCommand)
259     return;
260 
261   auto add = [](StringRef s, int64_t pos) {
262     return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
263   };
264 
265   ElfSym::bss = add("__bss_start", 0);
266   ElfSym::end1 = add("end", -1);
267   ElfSym::end2 = add("_end", -1);
268   ElfSym::etext1 = add("etext", -1);
269   ElfSym::etext2 = add("_etext", -1);
270   ElfSym::edata1 = add("edata", -1);
271   ElfSym::edata2 = add("_edata", -1);
272 }
273 
274 static OutputSection *findSection(StringRef name, unsigned partition = 1) {
275   for (SectionCommand *cmd : script->sectionCommands)
276     if (auto *sec = dyn_cast<OutputSection>(cmd))
277       if (sec->name == name && sec->partition == partition)
278         return sec;
279   return nullptr;
280 }
281 
282 template <class ELFT> void elf::createSyntheticSections() {
283   // Initialize all pointers with NULL. This is needed because
284   // you can call lld::elf::main more than once as a library.
285   Out::tlsPhdr = nullptr;
286   Out::preinitArray = nullptr;
287   Out::initArray = nullptr;
288   Out::finiArray = nullptr;
289 
290   // Add the .interp section first because it is not a SyntheticSection.
291   // The removeUnusedSyntheticSections() function relies on the
292   // SyntheticSections coming last.
293   if (needsInterpSection()) {
294     for (size_t i = 1; i <= partitions.size(); ++i) {
295       InputSection *sec = createInterpSection();
296       sec->partition = i;
297       inputSections.push_back(sec);
298     }
299   }
300 
301   auto add = [](SyntheticSection &sec) { inputSections.push_back(&sec); };
302 
303   in.shStrTab = std::make_unique<StringTableSection>(".shstrtab", false);
304 
305   Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
306   Out::programHeaders->alignment = config->wordsize;
307 
308   if (config->strip != StripPolicy::All) {
309     in.strTab = std::make_unique<StringTableSection>(".strtab", false);
310     in.symTab = std::make_unique<SymbolTableSection<ELFT>>(*in.strTab);
311     in.symTabShndx = std::make_unique<SymtabShndxSection>();
312   }
313 
314   in.bss = std::make_unique<BssSection>(".bss", 0, 1);
315   add(*in.bss);
316 
317   // If there is a SECTIONS command and a .data.rel.ro section name use name
318   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
319   // This makes sure our relro is contiguous.
320   bool hasDataRelRo = script->hasSectionsCommand && findSection(".data.rel.ro");
321   in.bssRelRo = std::make_unique<BssSection>(
322       hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
323   add(*in.bssRelRo);
324 
325   // Add MIPS-specific sections.
326   if (config->emachine == EM_MIPS) {
327     if (!config->shared && config->hasDynSymTab) {
328       in.mipsRldMap = std::make_unique<MipsRldMapSection>();
329       add(*in.mipsRldMap);
330     }
331     if ((in.mipsAbiFlags = MipsAbiFlagsSection<ELFT>::create()))
332       add(*in.mipsAbiFlags);
333     if ((in.mipsOptions = MipsOptionsSection<ELFT>::create()))
334       add(*in.mipsOptions);
335     if ((in.mipsReginfo = MipsReginfoSection<ELFT>::create()))
336       add(*in.mipsReginfo);
337   }
338 
339   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
340 
341   for (Partition &part : partitions) {
342     auto add = [&](SyntheticSection &sec) {
343       sec.partition = part.getNumber();
344       inputSections.push_back(&sec);
345     };
346 
347     if (!part.name.empty()) {
348       part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>();
349       part.elfHeader->name = part.name;
350       add(*part.elfHeader);
351 
352       part.programHeaders =
353           std::make_unique<PartitionProgramHeadersSection<ELFT>>();
354       add(*part.programHeaders);
355     }
356 
357     if (config->buildId != BuildIdKind::None) {
358       part.buildId = std::make_unique<BuildIdSection>();
359       add(*part.buildId);
360     }
361 
362     part.dynStrTab = std::make_unique<StringTableSection>(".dynstr", true);
363     part.dynSymTab =
364         std::make_unique<SymbolTableSection<ELFT>>(*part.dynStrTab);
365     part.dynamic = std::make_unique<DynamicSection<ELFT>>();
366     if (config->androidPackDynRelocs)
367       part.relaDyn =
368           std::make_unique<AndroidPackedRelocationSection<ELFT>>(relaDynName);
369     else
370       part.relaDyn = std::make_unique<RelocationSection<ELFT>>(
371           relaDynName, config->zCombreloc);
372 
373     if (config->hasDynSymTab) {
374       add(*part.dynSymTab);
375 
376       part.verSym = std::make_unique<VersionTableSection>();
377       add(*part.verSym);
378 
379       if (!namedVersionDefs().empty()) {
380         part.verDef = std::make_unique<VersionDefinitionSection>();
381         add(*part.verDef);
382       }
383 
384       part.verNeed = std::make_unique<VersionNeedSection<ELFT>>();
385       add(*part.verNeed);
386 
387       if (config->gnuHash) {
388         part.gnuHashTab = std::make_unique<GnuHashTableSection>();
389         add(*part.gnuHashTab);
390       }
391 
392       if (config->sysvHash) {
393         part.hashTab = std::make_unique<HashTableSection>();
394         add(*part.hashTab);
395       }
396 
397       add(*part.dynamic);
398       add(*part.dynStrTab);
399       add(*part.relaDyn);
400     }
401 
402     if (config->relrPackDynRelocs) {
403       part.relrDyn = std::make_unique<RelrSection<ELFT>>();
404       add(*part.relrDyn);
405     }
406 
407     if (!config->relocatable) {
408       if (config->ehFrameHdr) {
409         part.ehFrameHdr = std::make_unique<EhFrameHeader>();
410         add(*part.ehFrameHdr);
411       }
412       part.ehFrame = std::make_unique<EhFrameSection>();
413       add(*part.ehFrame);
414     }
415 
416     if (config->emachine == EM_ARM && !config->relocatable) {
417       // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx
418       // InputSections.
419       part.armExidx = std::make_unique<ARMExidxSyntheticSection>();
420       add(*part.armExidx);
421     }
422   }
423 
424   if (partitions.size() != 1) {
425     // Create the partition end marker. This needs to be in partition number 255
426     // so that it is sorted after all other partitions. It also has other
427     // special handling (see createPhdrs() and combineEhSections()).
428     in.partEnd =
429         std::make_unique<BssSection>(".part.end", config->maxPageSize, 1);
430     in.partEnd->partition = 255;
431     add(*in.partEnd);
432 
433     in.partIndex = std::make_unique<PartitionIndexSection>();
434     addOptionalRegular("__part_index_begin", in.partIndex.get(), 0);
435     addOptionalRegular("__part_index_end", in.partIndex.get(),
436                        in.partIndex->getSize());
437     add(*in.partIndex);
438   }
439 
440   // Add .got. MIPS' .got is so different from the other archs,
441   // it has its own class.
442   if (config->emachine == EM_MIPS) {
443     in.mipsGot = std::make_unique<MipsGotSection>();
444     add(*in.mipsGot);
445   } else {
446     in.got = std::make_unique<GotSection>();
447     add(*in.got);
448   }
449 
450   if (config->emachine == EM_PPC) {
451     in.ppc32Got2 = std::make_unique<PPC32Got2Section>();
452     add(*in.ppc32Got2);
453   }
454 
455   if (config->emachine == EM_PPC64) {
456     in.ppc64LongBranchTarget = std::make_unique<PPC64LongBranchTargetSection>();
457     add(*in.ppc64LongBranchTarget);
458   }
459 
460   in.gotPlt = std::make_unique<GotPltSection>();
461   add(*in.gotPlt);
462   in.igotPlt = std::make_unique<IgotPltSection>();
463   add(*in.igotPlt);
464 
465   // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
466   // it as a relocation and ensure the referenced section is created.
467   if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
468     if (target->gotBaseSymInGotPlt)
469       in.gotPlt->hasGotPltOffRel = true;
470     else
471       in.got->hasGotOffRel = true;
472   }
473 
474   if (config->gdbIndex)
475     add(*GdbIndexSection::create<ELFT>());
476 
477   // We always need to add rel[a].plt to output if it has entries.
478   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
479   in.relaPlt = std::make_unique<RelocationSection<ELFT>>(
480       config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false);
481   add(*in.relaPlt);
482 
483   // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
484   // relocations are processed last by the dynamic loader. We cannot place the
485   // iplt section in .rel.dyn when Android relocation packing is enabled because
486   // that would cause a section type mismatch. However, because the Android
487   // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
488   // behaviour by placing the iplt section in .rel.plt.
489   in.relaIplt = std::make_unique<RelocationSection<ELFT>>(
490       config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
491       /*sort=*/false);
492   add(*in.relaIplt);
493 
494   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
495       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
496     in.ibtPlt = std::make_unique<IBTPltSection>();
497     add(*in.ibtPlt);
498   }
499 
500   if (config->emachine == EM_PPC)
501     in.plt = std::make_unique<PPC32GlinkSection>();
502   else
503     in.plt = std::make_unique<PltSection>();
504   add(*in.plt);
505   in.iplt = std::make_unique<IpltSection>();
506   add(*in.iplt);
507 
508   if (config->andFeatures)
509     add(*make<GnuPropertySection>());
510 
511   // .note.GNU-stack is always added when we are creating a re-linkable
512   // object file. Other linkers are using the presence of this marker
513   // section to control the executable-ness of the stack area, but that
514   // is irrelevant these days. Stack area should always be non-executable
515   // by default. So we emit this section unconditionally.
516   if (config->relocatable)
517     add(*make<GnuStackSection>());
518 
519   if (in.symTab)
520     add(*in.symTab);
521   if (in.symTabShndx)
522     add(*in.symTabShndx);
523   add(*in.shStrTab);
524   if (in.strTab)
525     add(*in.strTab);
526 }
527 
528 // The main function of the writer.
529 template <class ELFT> void Writer<ELFT>::run() {
530   copyLocalSymbols();
531 
532   if (config->copyRelocs)
533     addSectionSymbols();
534 
535   // Now that we have a complete set of output sections. This function
536   // completes section contents. For example, we need to add strings
537   // to the string table, and add entries to .got and .plt.
538   // finalizeSections does that.
539   finalizeSections();
540   checkExecuteOnly();
541 
542   // If --compressed-debug-sections is specified, compress .debug_* sections.
543   // Do it right now because it changes the size of output sections.
544   for (OutputSection *sec : outputSections)
545     sec->maybeCompress<ELFT>();
546 
547   if (script->hasSectionsCommand)
548     script->allocateHeaders(mainPart->phdrs);
549 
550   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
551   // 0 sized region. This has to be done late since only after assignAddresses
552   // we know the size of the sections.
553   for (Partition &part : partitions)
554     removeEmptyPTLoad(part.phdrs);
555 
556   if (!config->oFormatBinary)
557     assignFileOffsets();
558   else
559     assignFileOffsetsBinary();
560 
561   for (Partition &part : partitions)
562     setPhdrs(part);
563 
564   // Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()
565   // because the files may be useful in case checkSections() or openFile()
566   // fails, for example, due to an erroneous file size.
567   writeMapAndCref();
568 
569   if (config->checkSections)
570     checkSections();
571 
572   // It does not make sense try to open the file if we have error already.
573   if (errorCount())
574     return;
575 
576   {
577     llvm::TimeTraceScope timeScope("Write output file");
578     // Write the result down to a file.
579     openFile();
580     if (errorCount())
581       return;
582 
583     if (!config->oFormatBinary) {
584       if (config->zSeparate != SeparateSegmentKind::None)
585         writeTrapInstr();
586       writeHeader();
587       writeSections();
588     } else {
589       writeSectionsBinary();
590     }
591 
592     // Backfill .note.gnu.build-id section content. This is done at last
593     // because the content is usually a hash value of the entire output file.
594     writeBuildId();
595     if (errorCount())
596       return;
597 
598     if (auto e = buffer->commit())
599       error("failed to write to the output file: " + toString(std::move(e)));
600   }
601 }
602 
603 template <class ELFT, class RelTy>
604 static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
605                                      llvm::ArrayRef<RelTy> rels) {
606   for (const RelTy &rel : rels) {
607     Symbol &sym = file->getRelocTargetSym(rel);
608     if (sym.isLocal())
609       sym.used = true;
610   }
611 }
612 
613 // The function ensures that the "used" field of local symbols reflects the fact
614 // that the symbol is used in a relocation from a live section.
615 template <class ELFT> static void markUsedLocalSymbols() {
616   // With --gc-sections, the field is already filled.
617   // See MarkLive<ELFT>::resolveReloc().
618   if (config->gcSections)
619     return;
620   for (ELFFileBase *file : objectFiles) {
621     ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
622     for (InputSectionBase *s : f->getSections()) {
623       InputSection *isec = dyn_cast_or_null<InputSection>(s);
624       if (!isec)
625         continue;
626       if (isec->type == SHT_REL)
627         markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
628       else if (isec->type == SHT_RELA)
629         markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
630     }
631   }
632 }
633 
634 static bool shouldKeepInSymtab(const Defined &sym) {
635   if (sym.isSection())
636     return false;
637 
638   // If --emit-reloc or -r is given, preserve symbols referenced by relocations
639   // from live sections.
640   if (sym.used)
641     return true;
642 
643   // Exclude local symbols pointing to .ARM.exidx sections.
644   // They are probably mapping symbols "$d", which are optional for these
645   // sections. After merging the .ARM.exidx sections, some of these symbols
646   // may become dangling. The easiest way to avoid the issue is not to add
647   // them to the symbol table from the beginning.
648   if (config->emachine == EM_ARM && sym.section &&
649       sym.section->type == SHT_ARM_EXIDX)
650     return false;
651 
652   if (config->discard == DiscardPolicy::None)
653     return true;
654   if (config->discard == DiscardPolicy::All)
655     return false;
656 
657   // In ELF assembly .L symbols are normally discarded by the assembler.
658   // If the assembler fails to do so, the linker discards them if
659   // * --discard-locals is used.
660   // * The symbol is in a SHF_MERGE section, which is normally the reason for
661   //   the assembler keeping the .L symbol.
662   if (sym.getName().startswith(".L") &&
663       (config->discard == DiscardPolicy::Locals ||
664        (sym.section && (sym.section->flags & SHF_MERGE))))
665     return false;
666   return true;
667 }
668 
669 static bool includeInSymtab(const Symbol &b) {
670   if (auto *d = dyn_cast<Defined>(&b)) {
671     // Always include absolute symbols.
672     SectionBase *sec = d->section;
673     if (!sec)
674       return true;
675 
676     if (auto *s = dyn_cast<MergeInputSection>(sec))
677       return s->getSectionPiece(d->value)->live;
678     return sec->isLive();
679   }
680   return b.used || !config->gcSections;
681 }
682 
683 // Local symbols are not in the linker's symbol table. This function scans
684 // each object file's symbol table to copy local symbols to the output.
685 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
686   if (!in.symTab)
687     return;
688   llvm::TimeTraceScope timeScope("Add local symbols");
689   if (config->copyRelocs && config->discard != DiscardPolicy::None)
690     markUsedLocalSymbols<ELFT>();
691   for (ELFFileBase *file : objectFiles) {
692     for (Symbol *b : file->getLocalSymbols()) {
693       assert(b->isLocal() && "should have been caught in initializeSymbols()");
694       auto *dr = dyn_cast<Defined>(b);
695 
696       // No reason to keep local undefined symbol in symtab.
697       if (!dr)
698         continue;
699       if (includeInSymtab(*b) && shouldKeepInSymtab(*dr))
700         in.symTab->addSymbol(b);
701     }
702   }
703 }
704 
705 // Create a section symbol for each output section so that we can represent
706 // relocations that point to the section. If we know that no relocation is
707 // referring to a section (that happens if the section is a synthetic one), we
708 // don't create a section symbol for that section.
709 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
710   for (SectionCommand *cmd : script->sectionCommands) {
711     auto *sec = dyn_cast<OutputSection>(cmd);
712     if (!sec)
713       continue;
714     auto i = llvm::find_if(sec->commands, [](SectionCommand *cmd) {
715       if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
716         return !isd->sections.empty();
717       return false;
718     });
719     if (i == sec->commands.end())
720       continue;
721     InputSectionBase *isec = cast<InputSectionDescription>(*i)->sections[0];
722 
723     // Relocations are not using REL[A] section symbols.
724     if (isec->type == SHT_REL || isec->type == SHT_RELA)
725       continue;
726 
727     // Unlike other synthetic sections, mergeable output sections contain data
728     // copied from input sections, and there may be a relocation pointing to its
729     // contents if -r or --emit-reloc is given.
730     if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE))
731       continue;
732 
733     // Set the symbol to be relative to the output section so that its st_value
734     // equals the output section address. Note, there may be a gap between the
735     // start of the output section and isec.
736     in.symTab->addSymbol(
737         makeDefined(isec->file, "", STB_LOCAL, /*stOther=*/0, STT_SECTION,
738                     /*value=*/0, /*size=*/0, isec->getOutputSection()));
739   }
740 }
741 
742 // Today's loaders have a feature to make segments read-only after
743 // processing dynamic relocations to enhance security. PT_GNU_RELRO
744 // is defined for that.
745 //
746 // This function returns true if a section needs to be put into a
747 // PT_GNU_RELRO segment.
748 static bool isRelroSection(const OutputSection *sec) {
749   if (!config->zRelro)
750     return false;
751 
752   uint64_t flags = sec->flags;
753 
754   // Non-allocatable or non-writable sections don't need RELRO because
755   // they are not writable or not even mapped to memory in the first place.
756   // RELRO is for sections that are essentially read-only but need to
757   // be writable only at process startup to allow dynamic linker to
758   // apply relocations.
759   if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
760     return false;
761 
762   // Once initialized, TLS data segments are used as data templates
763   // for a thread-local storage. For each new thread, runtime
764   // allocates memory for a TLS and copy templates there. No thread
765   // are supposed to use templates directly. Thus, it can be in RELRO.
766   if (flags & SHF_TLS)
767     return true;
768 
769   // .init_array, .preinit_array and .fini_array contain pointers to
770   // functions that are executed on process startup or exit. These
771   // pointers are set by the static linker, and they are not expected
772   // to change at runtime. But if you are an attacker, you could do
773   // interesting things by manipulating pointers in .fini_array, for
774   // example. So they are put into RELRO.
775   uint32_t type = sec->type;
776   if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
777       type == SHT_PREINIT_ARRAY)
778     return true;
779 
780   // .got contains pointers to external symbols. They are resolved by
781   // the dynamic linker when a module is loaded into memory, and after
782   // that they are not expected to change. So, it can be in RELRO.
783   if (in.got && sec == in.got->getParent())
784     return true;
785 
786   // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
787   // through r2 register, which is reserved for that purpose. Since r2 is used
788   // for accessing .got as well, .got and .toc need to be close enough in the
789   // virtual address space. Usually, .toc comes just after .got. Since we place
790   // .got into RELRO, .toc needs to be placed into RELRO too.
791   if (sec->name.equals(".toc"))
792     return true;
793 
794   // .got.plt contains pointers to external function symbols. They are
795   // by default resolved lazily, so we usually cannot put it into RELRO.
796   // However, if "-z now" is given, the lazy symbol resolution is
797   // disabled, which enables us to put it into RELRO.
798   if (sec == in.gotPlt->getParent())
799     return config->zNow;
800 
801   // .dynamic section contains data for the dynamic linker, and
802   // there's no need to write to it at runtime, so it's better to put
803   // it into RELRO.
804   if (sec->name == ".dynamic")
805     return true;
806 
807   // Sections with some special names are put into RELRO. This is a
808   // bit unfortunate because section names shouldn't be significant in
809   // ELF in spirit. But in reality many linker features depend on
810   // magic section names.
811   StringRef s = sec->name;
812   return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
813          s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
814          s == ".fini_array" || s == ".init_array" ||
815          s == ".openbsd.randomdata" || s == ".preinit_array";
816 }
817 
818 // We compute a rank for each section. The rank indicates where the
819 // section should be placed in the file.  Instead of using simple
820 // numbers (0,1,2...), we use a series of flags. One for each decision
821 // point when placing the section.
822 // Using flags has two key properties:
823 // * It is easy to check if a give branch was taken.
824 // * It is easy two see how similar two ranks are (see getRankProximity).
825 enum RankFlags {
826   RF_NOT_ADDR_SET = 1 << 27,
827   RF_NOT_ALLOC = 1 << 26,
828   RF_PARTITION = 1 << 18, // Partition number (8 bits)
829   RF_NOT_PART_EHDR = 1 << 17,
830   RF_NOT_PART_PHDR = 1 << 16,
831   RF_NOT_INTERP = 1 << 15,
832   RF_NOT_NOTE = 1 << 14,
833   RF_WRITE = 1 << 13,
834   RF_EXEC_WRITE = 1 << 12,
835   RF_EXEC = 1 << 11,
836   RF_RODATA = 1 << 10,
837   RF_NOT_RELRO = 1 << 9,
838   RF_NOT_TLS = 1 << 8,
839   RF_BSS = 1 << 7,
840   RF_PPC_NOT_TOCBSS = 1 << 6,
841   RF_PPC_TOCL = 1 << 5,
842   RF_PPC_TOC = 1 << 4,
843   RF_PPC_GOT = 1 << 3,
844   RF_PPC_BRANCH_LT = 1 << 2,
845   RF_MIPS_GPREL = 1 << 1,
846   RF_MIPS_NOT_GOT = 1 << 0
847 };
848 
849 static unsigned getSectionRank(const OutputSection *sec) {
850   unsigned rank = sec->partition * RF_PARTITION;
851 
852   // We want to put section specified by -T option first, so we
853   // can start assigning VA starting from them later.
854   if (config->sectionStartMap.count(sec->name))
855     return rank;
856   rank |= RF_NOT_ADDR_SET;
857 
858   // Allocatable sections go first to reduce the total PT_LOAD size and
859   // so debug info doesn't change addresses in actual code.
860   if (!(sec->flags & SHF_ALLOC))
861     return rank | RF_NOT_ALLOC;
862 
863   if (sec->type == SHT_LLVM_PART_EHDR)
864     return rank;
865   rank |= RF_NOT_PART_EHDR;
866 
867   if (sec->type == SHT_LLVM_PART_PHDR)
868     return rank;
869   rank |= RF_NOT_PART_PHDR;
870 
871   // Put .interp first because some loaders want to see that section
872   // on the first page of the executable file when loaded into memory.
873   if (sec->name == ".interp")
874     return rank;
875   rank |= RF_NOT_INTERP;
876 
877   // Put .note sections (which make up one PT_NOTE) at the beginning so that
878   // they are likely to be included in a core file even if core file size is
879   // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
880   // included in a core to match core files with executables.
881   if (sec->type == SHT_NOTE)
882     return rank;
883   rank |= RF_NOT_NOTE;
884 
885   // Sort sections based on their access permission in the following
886   // order: R, RX, RWX, RW.  This order is based on the following
887   // considerations:
888   // * Read-only sections come first such that they go in the
889   //   PT_LOAD covering the program headers at the start of the file.
890   // * Read-only, executable sections come next.
891   // * Writable, executable sections follow such that .plt on
892   //   architectures where it needs to be writable will be placed
893   //   between .text and .data.
894   // * Writable sections come last, such that .bss lands at the very
895   //   end of the last PT_LOAD.
896   bool isExec = sec->flags & SHF_EXECINSTR;
897   bool isWrite = sec->flags & SHF_WRITE;
898 
899   if (isExec) {
900     if (isWrite)
901       rank |= RF_EXEC_WRITE;
902     else
903       rank |= RF_EXEC;
904   } else if (isWrite) {
905     rank |= RF_WRITE;
906   } else if (sec->type == SHT_PROGBITS) {
907     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
908     // .eh_frame) closer to .text. They likely contain PC or GOT relative
909     // relocations and there could be relocation overflow if other huge sections
910     // (.dynstr .dynsym) were placed in between.
911     rank |= RF_RODATA;
912   }
913 
914   // Place RelRo sections first. After considering SHT_NOBITS below, the
915   // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
916   // where | marks where page alignment happens. An alternative ordering is
917   // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
918   // waste more bytes due to 2 alignment places.
919   if (!isRelroSection(sec))
920     rank |= RF_NOT_RELRO;
921 
922   // If we got here we know that both A and B are in the same PT_LOAD.
923 
924   // The TLS initialization block needs to be a single contiguous block in a R/W
925   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
926   // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
927   // after PROGBITS.
928   if (!(sec->flags & SHF_TLS))
929     rank |= RF_NOT_TLS;
930 
931   // Within TLS sections, or within other RelRo sections, or within non-RelRo
932   // sections, place non-NOBITS sections first.
933   if (sec->type == SHT_NOBITS)
934     rank |= RF_BSS;
935 
936   // Some architectures have additional ordering restrictions for sections
937   // within the same PT_LOAD.
938   if (config->emachine == EM_PPC64) {
939     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
940     // that we would like to make sure appear is a specific order to maximize
941     // their coverage by a single signed 16-bit offset from the TOC base
942     // pointer. Conversely, the special .tocbss section should be first among
943     // all SHT_NOBITS sections. This will put it next to the loaded special
944     // PPC64 sections (and, thus, within reach of the TOC base pointer).
945     StringRef name = sec->name;
946     if (name != ".tocbss")
947       rank |= RF_PPC_NOT_TOCBSS;
948 
949     if (name == ".toc1")
950       rank |= RF_PPC_TOCL;
951 
952     if (name == ".toc")
953       rank |= RF_PPC_TOC;
954 
955     if (name == ".got")
956       rank |= RF_PPC_GOT;
957 
958     if (name == ".branch_lt")
959       rank |= RF_PPC_BRANCH_LT;
960   }
961 
962   if (config->emachine == EM_MIPS) {
963     // All sections with SHF_MIPS_GPREL flag should be grouped together
964     // because data in these sections is addressable with a gp relative address.
965     if (sec->flags & SHF_MIPS_GPREL)
966       rank |= RF_MIPS_GPREL;
967 
968     if (sec->name != ".got")
969       rank |= RF_MIPS_NOT_GOT;
970   }
971 
972   return rank;
973 }
974 
975 static bool compareSections(const SectionCommand *aCmd,
976                             const SectionCommand *bCmd) {
977   const OutputSection *a = cast<OutputSection>(aCmd);
978   const OutputSection *b = cast<OutputSection>(bCmd);
979 
980   if (a->sortRank != b->sortRank)
981     return a->sortRank < b->sortRank;
982 
983   if (!(a->sortRank & RF_NOT_ADDR_SET))
984     return config->sectionStartMap.lookup(a->name) <
985            config->sectionStartMap.lookup(b->name);
986   return false;
987 }
988 
989 void PhdrEntry::add(OutputSection *sec) {
990   lastSec = sec;
991   if (!firstSec)
992     firstSec = sec;
993   p_align = std::max(p_align, sec->alignment);
994   if (p_type == PT_LOAD)
995     sec->ptLoad = this;
996 }
997 
998 // The beginning and the ending of .rel[a].plt section are marked
999 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1000 // executable. The runtime needs these symbols in order to resolve
1001 // all IRELATIVE relocs on startup. For dynamic executables, we don't
1002 // need these symbols, since IRELATIVE relocs are resolved through GOT
1003 // and PLT. For details, see http://www.airs.com/blog/archives/403.
1004 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
1005   if (config->relocatable || config->isPic)
1006     return;
1007 
1008   // By default, __rela_iplt_{start,end} belong to a dummy section 0
1009   // because .rela.plt might be empty and thus removed from output.
1010   // We'll override Out::elfHeader with In.relaIplt later when we are
1011   // sure that .rela.plt exists in output.
1012   ElfSym::relaIpltStart = addOptionalRegular(
1013       config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
1014       Out::elfHeader, 0, STV_HIDDEN);
1015 
1016   ElfSym::relaIpltEnd = addOptionalRegular(
1017       config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
1018       Out::elfHeader, 0, STV_HIDDEN);
1019 }
1020 
1021 // This function generates assignments for predefined symbols (e.g. _end or
1022 // _etext) and inserts them into the commands sequence to be processed at the
1023 // appropriate time. This ensures that the value is going to be correct by the
1024 // time any references to these symbols are processed and is equivalent to
1025 // defining these symbols explicitly in the linker script.
1026 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
1027   if (ElfSym::globalOffsetTable) {
1028     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
1029     // to the start of the .got or .got.plt section.
1030     InputSection *sec = in.gotPlt.get();
1031     if (!target->gotBaseSymInGotPlt)
1032       sec = in.mipsGot.get() ? cast<InputSection>(in.mipsGot.get())
1033                              : cast<InputSection>(in.got.get());
1034     ElfSym::globalOffsetTable->section = sec;
1035   }
1036 
1037   // .rela_iplt_{start,end} mark the start and the end of in.relaIplt.
1038   if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
1039     ElfSym::relaIpltStart->section = in.relaIplt.get();
1040     ElfSym::relaIpltEnd->section = in.relaIplt.get();
1041     ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
1042   }
1043 
1044   PhdrEntry *last = nullptr;
1045   PhdrEntry *lastRO = nullptr;
1046 
1047   for (Partition &part : partitions) {
1048     for (PhdrEntry *p : part.phdrs) {
1049       if (p->p_type != PT_LOAD)
1050         continue;
1051       last = p;
1052       if (!(p->p_flags & PF_W))
1053         lastRO = p;
1054     }
1055   }
1056 
1057   if (lastRO) {
1058     // _etext is the first location after the last read-only loadable segment.
1059     if (ElfSym::etext1)
1060       ElfSym::etext1->section = lastRO->lastSec;
1061     if (ElfSym::etext2)
1062       ElfSym::etext2->section = lastRO->lastSec;
1063   }
1064 
1065   if (last) {
1066     // _edata points to the end of the last mapped initialized section.
1067     OutputSection *edata = nullptr;
1068     for (OutputSection *os : outputSections) {
1069       if (os->type != SHT_NOBITS)
1070         edata = os;
1071       if (os == last->lastSec)
1072         break;
1073     }
1074 
1075     if (ElfSym::edata1)
1076       ElfSym::edata1->section = edata;
1077     if (ElfSym::edata2)
1078       ElfSym::edata2->section = edata;
1079 
1080     // _end is the first location after the uninitialized data region.
1081     if (ElfSym::end1)
1082       ElfSym::end1->section = last->lastSec;
1083     if (ElfSym::end2)
1084       ElfSym::end2->section = last->lastSec;
1085   }
1086 
1087   if (ElfSym::bss)
1088     ElfSym::bss->section = findSection(".bss");
1089 
1090   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1091   // be equal to the _gp symbol's value.
1092   if (ElfSym::mipsGp) {
1093     // Find GP-relative section with the lowest address
1094     // and use this address to calculate default _gp value.
1095     for (OutputSection *os : outputSections) {
1096       if (os->flags & SHF_MIPS_GPREL) {
1097         ElfSym::mipsGp->section = os;
1098         ElfSym::mipsGp->value = 0x7ff0;
1099         break;
1100       }
1101     }
1102   }
1103 }
1104 
1105 // We want to find how similar two ranks are.
1106 // The more branches in getSectionRank that match, the more similar they are.
1107 // Since each branch corresponds to a bit flag, we can just use
1108 // countLeadingZeros.
1109 static int getRankProximityAux(OutputSection *a, OutputSection *b) {
1110   return countLeadingZeros(a->sortRank ^ b->sortRank);
1111 }
1112 
1113 static int getRankProximity(OutputSection *a, SectionCommand *b) {
1114   auto *sec = dyn_cast<OutputSection>(b);
1115   return (sec && sec->hasInputSections) ? getRankProximityAux(a, sec) : -1;
1116 }
1117 
1118 // When placing orphan sections, we want to place them after symbol assignments
1119 // so that an orphan after
1120 //   begin_foo = .;
1121 //   foo : { *(foo) }
1122 //   end_foo = .;
1123 // doesn't break the intended meaning of the begin/end symbols.
1124 // We don't want to go over sections since findOrphanPos is the
1125 // one in charge of deciding the order of the sections.
1126 // We don't want to go over changes to '.', since doing so in
1127 //  rx_sec : { *(rx_sec) }
1128 //  . = ALIGN(0x1000);
1129 //  /* The RW PT_LOAD starts here*/
1130 //  rw_sec : { *(rw_sec) }
1131 // would mean that the RW PT_LOAD would become unaligned.
1132 static bool shouldSkip(SectionCommand *cmd) {
1133   if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
1134     return assign->name != ".";
1135   return false;
1136 }
1137 
1138 // We want to place orphan sections so that they share as much
1139 // characteristics with their neighbors as possible. For example, if
1140 // both are rw, or both are tls.
1141 static SmallVectorImpl<SectionCommand *>::iterator
1142 findOrphanPos(SmallVectorImpl<SectionCommand *>::iterator b,
1143               SmallVectorImpl<SectionCommand *>::iterator e) {
1144   OutputSection *sec = cast<OutputSection>(*e);
1145 
1146   // Find the first element that has as close a rank as possible.
1147   auto i = std::max_element(b, e, [=](SectionCommand *a, SectionCommand *b) {
1148     return getRankProximity(sec, a) < getRankProximity(sec, b);
1149   });
1150   if (i == e)
1151     return e;
1152   auto foundSec = dyn_cast<OutputSection>(*i);
1153   if (!foundSec)
1154     return e;
1155 
1156   // Consider all existing sections with the same proximity.
1157   int proximity = getRankProximity(sec, *i);
1158   unsigned sortRank = sec->sortRank;
1159   if (script->hasPhdrsCommands() || !script->memoryRegions.empty())
1160     // Prevent the orphan section to be placed before the found section. If
1161     // custom program headers are defined, that helps to avoid adding it to a
1162     // previous segment and changing flags of that segment, for example, making
1163     // a read-only segment writable. If memory regions are defined, an orphan
1164     // section should continue the same region as the found section to better
1165     // resemble the behavior of GNU ld.
1166     sortRank = std::max(sortRank, foundSec->sortRank);
1167   for (; i != e; ++i) {
1168     auto *curSec = dyn_cast<OutputSection>(*i);
1169     if (!curSec || !curSec->hasInputSections)
1170       continue;
1171     if (getRankProximity(sec, curSec) != proximity ||
1172         sortRank < curSec->sortRank)
1173       break;
1174   }
1175 
1176   auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
1177     auto *os = dyn_cast<OutputSection>(cmd);
1178     return os && os->hasInputSections;
1179   };
1180   auto j =
1181       std::find_if(std::make_reverse_iterator(i), std::make_reverse_iterator(b),
1182                    isOutputSecWithInputSections);
1183   i = j.base();
1184 
1185   // As a special case, if the orphan section is the last section, put
1186   // it at the very end, past any other commands.
1187   // This matches bfd's behavior and is convenient when the linker script fully
1188   // specifies the start of the file, but doesn't care about the end (the non
1189   // alloc sections for example).
1190   auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1191   if (nextSec == e)
1192     return e;
1193 
1194   while (i != e && shouldSkip(*i))
1195     ++i;
1196   return i;
1197 }
1198 
1199 // Adds random priorities to sections not already in the map.
1200 static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {
1201   if (config->shuffleSections.empty())
1202     return;
1203 
1204   SmallVector<InputSectionBase *, 0> matched, sections = inputSections;
1205   matched.reserve(sections.size());
1206   for (const auto &patAndSeed : config->shuffleSections) {
1207     matched.clear();
1208     for (InputSectionBase *sec : sections)
1209       if (patAndSeed.first.match(sec->name))
1210         matched.push_back(sec);
1211     const uint32_t seed = patAndSeed.second;
1212     if (seed == UINT32_MAX) {
1213       // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1214       // section order is stable even if the number of sections changes. This is
1215       // useful to catch issues like static initialization order fiasco
1216       // reliably.
1217       std::reverse(matched.begin(), matched.end());
1218     } else {
1219       std::mt19937 g(seed ? seed : std::random_device()());
1220       llvm::shuffle(matched.begin(), matched.end(), g);
1221     }
1222     size_t i = 0;
1223     for (InputSectionBase *&sec : sections)
1224       if (patAndSeed.first.match(sec->name))
1225         sec = matched[i++];
1226   }
1227 
1228   // Existing priorities are < 0, so use priorities >= 0 for the missing
1229   // sections.
1230   int prio = 0;
1231   for (InputSectionBase *sec : sections) {
1232     if (order.try_emplace(sec, prio).second)
1233       ++prio;
1234   }
1235 }
1236 
1237 // Builds section order for handling --symbol-ordering-file.
1238 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1239   DenseMap<const InputSectionBase *, int> sectionOrder;
1240   // Use the rarely used option --call-graph-ordering-file to sort sections.
1241   if (!config->callGraphProfile.empty())
1242     return computeCallGraphProfileOrder();
1243 
1244   if (config->symbolOrderingFile.empty())
1245     return sectionOrder;
1246 
1247   struct SymbolOrderEntry {
1248     int priority;
1249     bool present;
1250   };
1251 
1252   // Build a map from symbols to their priorities. Symbols that didn't
1253   // appear in the symbol ordering file have the lowest priority 0.
1254   // All explicitly mentioned symbols have negative (higher) priorities.
1255   DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;
1256   int priority = -config->symbolOrderingFile.size();
1257   for (StringRef s : config->symbolOrderingFile)
1258     symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});
1259 
1260   // Build a map from sections to their priorities.
1261   auto addSym = [&](Symbol &sym) {
1262     auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));
1263     if (it == symbolOrder.end())
1264       return;
1265     SymbolOrderEntry &ent = it->second;
1266     ent.present = true;
1267 
1268     maybeWarnUnorderableSymbol(&sym);
1269 
1270     if (auto *d = dyn_cast<Defined>(&sym)) {
1271       if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1272         int &priority = sectionOrder[cast<InputSectionBase>(sec)];
1273         priority = std::min(priority, ent.priority);
1274       }
1275     }
1276   };
1277 
1278   // We want both global and local symbols. We get the global ones from the
1279   // symbol table and iterate the object files for the local ones.
1280   for (Symbol *sym : symtab->symbols())
1281     addSym(*sym);
1282 
1283   for (ELFFileBase *file : objectFiles)
1284     for (Symbol *sym : file->getLocalSymbols())
1285       addSym(*sym);
1286 
1287   if (config->warnSymbolOrdering)
1288     for (auto orderEntry : symbolOrder)
1289       if (!orderEntry.second.present)
1290         warn("symbol ordering file: no such symbol: " + orderEntry.first.val());
1291 
1292   return sectionOrder;
1293 }
1294 
1295 // Sorts the sections in ISD according to the provided section order.
1296 static void
1297 sortISDBySectionOrder(InputSectionDescription *isd,
1298                       const DenseMap<const InputSectionBase *, int> &order) {
1299   SmallVector<InputSection *, 0> unorderedSections;
1300   SmallVector<std::pair<InputSection *, int>, 0> orderedSections;
1301   uint64_t unorderedSize = 0;
1302 
1303   for (InputSection *isec : isd->sections) {
1304     auto i = order.find(isec);
1305     if (i == order.end()) {
1306       unorderedSections.push_back(isec);
1307       unorderedSize += isec->getSize();
1308       continue;
1309     }
1310     orderedSections.push_back({isec, i->second});
1311   }
1312   llvm::sort(orderedSections, llvm::less_second());
1313 
1314   // Find an insertion point for the ordered section list in the unordered
1315   // section list. On targets with limited-range branches, this is the mid-point
1316   // of the unordered section list. This decreases the likelihood that a range
1317   // extension thunk will be needed to enter or exit the ordered region. If the
1318   // ordered section list is a list of hot functions, we can generally expect
1319   // the ordered functions to be called more often than the unordered functions,
1320   // making it more likely that any particular call will be within range, and
1321   // therefore reducing the number of thunks required.
1322   //
1323   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1324   // If the layout is:
1325   //
1326   // 8MB hot
1327   // 32MB cold
1328   //
1329   // only the first 8-16MB of the cold code (depending on which hot function it
1330   // is actually calling) can call the hot code without a range extension thunk.
1331   // However, if we use this layout:
1332   //
1333   // 16MB cold
1334   // 8MB hot
1335   // 16MB cold
1336   //
1337   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1338   // of the second block of cold code can call the hot code without a thunk. So
1339   // we effectively double the amount of code that could potentially call into
1340   // the hot code without a thunk.
1341   size_t insPt = 0;
1342   if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
1343     uint64_t unorderedPos = 0;
1344     for (; insPt != unorderedSections.size(); ++insPt) {
1345       unorderedPos += unorderedSections[insPt]->getSize();
1346       if (unorderedPos > unorderedSize / 2)
1347         break;
1348     }
1349   }
1350 
1351   isd->sections.clear();
1352   for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
1353     isd->sections.push_back(isec);
1354   for (std::pair<InputSection *, int> p : orderedSections)
1355     isd->sections.push_back(p.first);
1356   for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
1357     isd->sections.push_back(isec);
1358 }
1359 
1360 static void sortSection(OutputSection *sec,
1361                         const DenseMap<const InputSectionBase *, int> &order) {
1362   StringRef name = sec->name;
1363 
1364   // Never sort these.
1365   if (name == ".init" || name == ".fini")
1366     return;
1367 
1368   // IRelative relocations that usually live in the .rel[a].dyn section should
1369   // be processed last by the dynamic loader. To achieve that we add synthetic
1370   // sections in the required order from the beginning so that the in.relaIplt
1371   // section is placed last in an output section. Here we just do not apply
1372   // sorting for an output section which holds the in.relaIplt section.
1373   if (in.relaIplt->getParent() == sec)
1374     return;
1375 
1376   // Sort input sections by priority using the list provided by
1377   // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1378   // digit radix sort. The sections may be sorted stably again by a more
1379   // significant key.
1380   if (!order.empty())
1381     for (SectionCommand *b : sec->commands)
1382       if (auto *isd = dyn_cast<InputSectionDescription>(b))
1383         sortISDBySectionOrder(isd, order);
1384 
1385   if (script->hasSectionsCommand)
1386     return;
1387 
1388   if (name == ".init_array" || name == ".fini_array") {
1389     sec->sortInitFini();
1390   } else if (name == ".ctors" || name == ".dtors") {
1391     sec->sortCtorsDtors();
1392   } else if (config->emachine == EM_PPC64 && name == ".toc") {
1393     // .toc is allocated just after .got and is accessed using GOT-relative
1394     // relocations. Object files compiled with small code model have an
1395     // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1396     // To reduce the risk of relocation overflow, .toc contents are sorted so
1397     // that sections having smaller relocation offsets are at beginning of .toc
1398     assert(sec->commands.size() == 1);
1399     auto *isd = cast<InputSectionDescription>(sec->commands[0]);
1400     llvm::stable_sort(isd->sections,
1401                       [](const InputSection *a, const InputSection *b) -> bool {
1402                         return a->file->ppc64SmallCodeModelTocRelocs &&
1403                                !b->file->ppc64SmallCodeModelTocRelocs;
1404                       });
1405   }
1406 }
1407 
1408 // If no layout was provided by linker script, we want to apply default
1409 // sorting for special input sections. This also handles --symbol-ordering-file.
1410 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1411   // Build the order once since it is expensive.
1412   DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1413   maybeShuffle(order);
1414   for (SectionCommand *cmd : script->sectionCommands)
1415     if (auto *sec = dyn_cast<OutputSection>(cmd))
1416       sortSection(sec, order);
1417 }
1418 
1419 template <class ELFT> void Writer<ELFT>::sortSections() {
1420   llvm::TimeTraceScope timeScope("Sort sections");
1421 
1422   // Don't sort if using -r. It is not necessary and we want to preserve the
1423   // relative order for SHF_LINK_ORDER sections.
1424   if (config->relocatable) {
1425     script->adjustOutputSections();
1426     return;
1427   }
1428 
1429   sortInputSections();
1430 
1431   for (SectionCommand *cmd : script->sectionCommands)
1432     if (auto *osec = dyn_cast<OutputSection>(cmd))
1433       osec->sortRank = getSectionRank(osec);
1434   if (!script->hasSectionsCommand) {
1435     // We know that all the OutputSections are contiguous in this case.
1436     auto isSection = [](SectionCommand *cmd) {
1437       return isa<OutputSection>(cmd);
1438     };
1439     std::stable_sort(
1440         llvm::find_if(script->sectionCommands, isSection),
1441         llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1442         compareSections);
1443   }
1444 
1445   // Process INSERT commands and update output section attributes. From this
1446   // point onwards the order of script->sectionCommands is fixed.
1447   script->processInsertCommands();
1448   script->adjustOutputSections();
1449 
1450   if (!script->hasSectionsCommand)
1451     return;
1452 
1453   // Orphan sections are sections present in the input files which are
1454   // not explicitly placed into the output file by the linker script.
1455   //
1456   // The sections in the linker script are already in the correct
1457   // order. We have to figuere out where to insert the orphan
1458   // sections.
1459   //
1460   // The order of the sections in the script is arbitrary and may not agree with
1461   // compareSections. This means that we cannot easily define a strict weak
1462   // ordering. To see why, consider a comparison of a section in the script and
1463   // one not in the script. We have a two simple options:
1464   // * Make them equivalent (a is not less than b, and b is not less than a).
1465   //   The problem is then that equivalence has to be transitive and we can
1466   //   have sections a, b and c with only b in a script and a less than c
1467   //   which breaks this property.
1468   // * Use compareSectionsNonScript. Given that the script order doesn't have
1469   //   to match, we can end up with sections a, b, c, d where b and c are in the
1470   //   script and c is compareSectionsNonScript less than b. In which case d
1471   //   can be equivalent to c, a to b and d < a. As a concrete example:
1472   //   .a (rx) # not in script
1473   //   .b (rx) # in script
1474   //   .c (ro) # in script
1475   //   .d (ro) # not in script
1476   //
1477   // The way we define an order then is:
1478   // *  Sort only the orphan sections. They are in the end right now.
1479   // *  Move each orphan section to its preferred position. We try
1480   //    to put each section in the last position where it can share
1481   //    a PT_LOAD.
1482   //
1483   // There is some ambiguity as to where exactly a new entry should be
1484   // inserted, because Commands contains not only output section
1485   // commands but also other types of commands such as symbol assignment
1486   // expressions. There's no correct answer here due to the lack of the
1487   // formal specification of the linker script. We use heuristics to
1488   // determine whether a new output command should be added before or
1489   // after another commands. For the details, look at shouldSkip
1490   // function.
1491 
1492   auto i = script->sectionCommands.begin();
1493   auto e = script->sectionCommands.end();
1494   auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {
1495     if (auto *sec = dyn_cast<OutputSection>(cmd))
1496       return sec->sectionIndex == UINT32_MAX;
1497     return false;
1498   });
1499 
1500   // Sort the orphan sections.
1501   std::stable_sort(nonScriptI, e, compareSections);
1502 
1503   // As a horrible special case, skip the first . assignment if it is before any
1504   // section. We do this because it is common to set a load address by starting
1505   // the script with ". = 0xabcd" and the expectation is that every section is
1506   // after that.
1507   auto firstSectionOrDotAssignment =
1508       std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });
1509   if (firstSectionOrDotAssignment != e &&
1510       isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1511     ++firstSectionOrDotAssignment;
1512   i = firstSectionOrDotAssignment;
1513 
1514   while (nonScriptI != e) {
1515     auto pos = findOrphanPos(i, nonScriptI);
1516     OutputSection *orphan = cast<OutputSection>(*nonScriptI);
1517 
1518     // As an optimization, find all sections with the same sort rank
1519     // and insert them with one rotate.
1520     unsigned rank = orphan->sortRank;
1521     auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {
1522       return cast<OutputSection>(cmd)->sortRank != rank;
1523     });
1524     std::rotate(pos, nonScriptI, end);
1525     nonScriptI = end;
1526   }
1527 
1528   script->adjustSectionsAfterSorting();
1529 }
1530 
1531 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1532   InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1533   InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1534   // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1535   // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1536   if (!la || !lb)
1537     return la && !lb;
1538   OutputSection *aOut = la->getParent();
1539   OutputSection *bOut = lb->getParent();
1540 
1541   if (aOut != bOut)
1542     return aOut->addr < bOut->addr;
1543   return la->outSecOff < lb->outSecOff;
1544 }
1545 
1546 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1547   llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1548   for (OutputSection *sec : outputSections) {
1549     if (!(sec->flags & SHF_LINK_ORDER))
1550       continue;
1551 
1552     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1553     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1554     if (!config->relocatable && config->emachine == EM_ARM &&
1555         sec->type == SHT_ARM_EXIDX)
1556       continue;
1557 
1558     // Link order may be distributed across several InputSectionDescriptions.
1559     // Sorting is performed separately.
1560     SmallVector<InputSection **, 0> scriptSections;
1561     SmallVector<InputSection *, 0> sections;
1562     for (SectionCommand *cmd : sec->commands) {
1563       auto *isd = dyn_cast<InputSectionDescription>(cmd);
1564       if (!isd)
1565         continue;
1566       bool hasLinkOrder = false;
1567       scriptSections.clear();
1568       sections.clear();
1569       for (InputSection *&isec : isd->sections) {
1570         if (isec->flags & SHF_LINK_ORDER) {
1571           InputSection *link = isec->getLinkOrderDep();
1572           if (link && !link->getParent())
1573             error(toString(isec) + ": sh_link points to discarded section " +
1574                   toString(link));
1575           hasLinkOrder = true;
1576         }
1577         scriptSections.push_back(&isec);
1578         sections.push_back(isec);
1579       }
1580       if (hasLinkOrder && errorCount() == 0) {
1581         llvm::stable_sort(sections, compareByFilePosition);
1582         for (int i = 0, n = sections.size(); i != n; ++i)
1583           *scriptSections[i] = sections[i];
1584       }
1585     }
1586   }
1587 }
1588 
1589 static void finalizeSynthetic(SyntheticSection *sec) {
1590   if (sec && sec->isNeeded() && sec->getParent()) {
1591     llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1592     sec->finalizeContents();
1593   }
1594 }
1595 
1596 // We need to generate and finalize the content that depends on the address of
1597 // InputSections. As the generation of the content may also alter InputSection
1598 // addresses we must converge to a fixed point. We do that here. See the comment
1599 // in Writer<ELFT>::finalizeSections().
1600 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1601   llvm::TimeTraceScope timeScope("Finalize address dependent content");
1602   ThunkCreator tc;
1603   AArch64Err843419Patcher a64p;
1604   ARMErr657417Patcher a32p;
1605   script->assignAddresses();
1606   // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1607   // do require the relative addresses of OutputSections because linker scripts
1608   // can assign Virtual Addresses to OutputSections that are not monotonically
1609   // increasing.
1610   for (Partition &part : partitions)
1611     finalizeSynthetic(part.armExidx.get());
1612   resolveShfLinkOrder();
1613 
1614   // Converts call x@GDPLT to call __tls_get_addr
1615   if (config->emachine == EM_HEXAGON)
1616     hexagonTLSSymbolUpdate(outputSections);
1617 
1618   int assignPasses = 0;
1619   for (;;) {
1620     bool changed = target->needsThunks && tc.createThunks(outputSections);
1621 
1622     // With Thunk Size much smaller than branch range we expect to
1623     // converge quickly; if we get to 15 something has gone wrong.
1624     if (changed && tc.pass >= 15) {
1625       error("thunk creation not converged");
1626       break;
1627     }
1628 
1629     if (config->fixCortexA53Errata843419) {
1630       if (changed)
1631         script->assignAddresses();
1632       changed |= a64p.createFixes();
1633     }
1634     if (config->fixCortexA8) {
1635       if (changed)
1636         script->assignAddresses();
1637       changed |= a32p.createFixes();
1638     }
1639 
1640     if (in.mipsGot)
1641       in.mipsGot->updateAllocSize();
1642 
1643     for (Partition &part : partitions) {
1644       changed |= part.relaDyn->updateAllocSize();
1645       if (part.relrDyn)
1646         changed |= part.relrDyn->updateAllocSize();
1647     }
1648 
1649     const Defined *changedSym = script->assignAddresses();
1650     if (!changed) {
1651       // Some symbols may be dependent on section addresses. When we break the
1652       // loop, the symbol values are finalized because a previous
1653       // assignAddresses() finalized section addresses.
1654       if (!changedSym)
1655         break;
1656       if (++assignPasses == 5) {
1657         errorOrWarn("assignment to symbol " + toString(*changedSym) +
1658                     " does not converge");
1659         break;
1660       }
1661     }
1662   }
1663 
1664   if (config->relocatable)
1665     for (OutputSection *sec : outputSections)
1666       sec->addr = 0;
1667 
1668   // If addrExpr is set, the address may not be a multiple of the alignment.
1669   // Warn because this is error-prone.
1670   for (SectionCommand *cmd : script->sectionCommands)
1671     if (auto *os = dyn_cast<OutputSection>(cmd))
1672       if (os->addr % os->alignment != 0)
1673         warn("address (0x" + Twine::utohexstr(os->addr) + ") of section " +
1674              os->name + " is not a multiple of alignment (" +
1675              Twine(os->alignment) + ")");
1676 }
1677 
1678 // If Input Sections have been shrunk (basic block sections) then
1679 // update symbol values and sizes associated with these sections.  With basic
1680 // block sections, input sections can shrink when the jump instructions at
1681 // the end of the section are relaxed.
1682 static void fixSymbolsAfterShrinking() {
1683   for (InputFile *File : objectFiles) {
1684     parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1685       auto *def = dyn_cast<Defined>(Sym);
1686       if (!def)
1687         return;
1688 
1689       const SectionBase *sec = def->section;
1690       if (!sec)
1691         return;
1692 
1693       const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
1694       if (!inputSec || !inputSec->bytesDropped)
1695         return;
1696 
1697       const size_t OldSize = inputSec->rawData.size();
1698       const size_t NewSize = OldSize - inputSec->bytesDropped;
1699 
1700       if (def->value > NewSize && def->value <= OldSize) {
1701         LLVM_DEBUG(llvm::dbgs()
1702                    << "Moving symbol " << Sym->getName() << " from "
1703                    << def->value << " to "
1704                    << def->value - inputSec->bytesDropped << " bytes\n");
1705         def->value -= inputSec->bytesDropped;
1706         return;
1707       }
1708 
1709       if (def->value + def->size > NewSize && def->value <= OldSize &&
1710           def->value + def->size <= OldSize) {
1711         LLVM_DEBUG(llvm::dbgs()
1712                    << "Shrinking symbol " << Sym->getName() << " from "
1713                    << def->size << " to " << def->size - inputSec->bytesDropped
1714                    << " bytes\n");
1715         def->size -= inputSec->bytesDropped;
1716       }
1717     });
1718   }
1719 }
1720 
1721 // If basic block sections exist, there are opportunities to delete fall thru
1722 // jumps and shrink jump instructions after basic block reordering.  This
1723 // relaxation pass does that.  It is only enabled when --optimize-bb-jumps
1724 // option is used.
1725 template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1726   assert(config->optimizeBBJumps);
1727 
1728   script->assignAddresses();
1729   // For every output section that has executable input sections, this
1730   // does the following:
1731   //   1. Deletes all direct jump instructions in input sections that
1732   //      jump to the following section as it is not required.
1733   //   2. If there are two consecutive jump instructions, it checks
1734   //      if they can be flipped and one can be deleted.
1735   for (OutputSection *osec : outputSections) {
1736     if (!(osec->flags & SHF_EXECINSTR))
1737       continue;
1738     SmallVector<InputSection *, 0> sections = getInputSections(*osec);
1739     size_t numDeleted = 0;
1740     // Delete all fall through jump instructions.  Also, check if two
1741     // consecutive jump instructions can be flipped so that a fall
1742     // through jmp instruction can be deleted.
1743     for (size_t i = 0, e = sections.size(); i != e; ++i) {
1744       InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
1745       InputSection &sec = *sections[i];
1746       numDeleted += target->deleteFallThruJmpInsn(sec, sec.file, next);
1747     }
1748     if (numDeleted > 0) {
1749       script->assignAddresses();
1750       LLVM_DEBUG(llvm::dbgs()
1751                  << "Removing " << numDeleted << " fall through jumps\n");
1752     }
1753   }
1754 
1755   fixSymbolsAfterShrinking();
1756 
1757   for (OutputSection *osec : outputSections)
1758     for (InputSection *is : getInputSections(*osec))
1759       is->trim();
1760 }
1761 
1762 // In order to allow users to manipulate linker-synthesized sections,
1763 // we had to add synthetic sections to the input section list early,
1764 // even before we make decisions whether they are needed. This allows
1765 // users to write scripts like this: ".mygot : { .got }".
1766 //
1767 // Doing it has an unintended side effects. If it turns out that we
1768 // don't need a .got (for example) at all because there's no
1769 // relocation that needs a .got, we don't want to emit .got.
1770 //
1771 // To deal with the above problem, this function is called after
1772 // scanRelocations is called to remove synthetic sections that turn
1773 // out to be empty.
1774 static void removeUnusedSyntheticSections() {
1775   // All input synthetic sections that can be empty are placed after
1776   // all regular ones. Reverse iterate to find the first synthetic section
1777   // after a non-synthetic one which will be our starting point.
1778   auto start = std::find_if(inputSections.rbegin(), inputSections.rend(),
1779                             [](InputSectionBase *s) {
1780                               return !isa<SyntheticSection>(s);
1781                             })
1782                    .base();
1783 
1784   // Remove unused synthetic sections from inputSections;
1785   DenseSet<InputSectionBase *> unused;
1786   auto end =
1787       std::remove_if(start, inputSections.end(), [&](InputSectionBase *s) {
1788         auto *sec = cast<SyntheticSection>(s);
1789         if (sec->getParent() && sec->isNeeded())
1790           return false;
1791         unused.insert(sec);
1792         return true;
1793       });
1794   inputSections.erase(end, inputSections.end());
1795 
1796   // Remove unused synthetic sections from the corresponding input section
1797   // description and orphanSections.
1798   for (auto *sec : unused)
1799     if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
1800       for (SectionCommand *cmd : osec->commands)
1801         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
1802           llvm::erase_if(isd->sections, [&](InputSection *isec) {
1803             return unused.count(isec);
1804           });
1805   llvm::erase_if(script->orphanSections, [&](const InputSectionBase *sec) {
1806     return unused.count(sec);
1807   });
1808 }
1809 
1810 // Create output section objects and add them to OutputSections.
1811 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1812   Out::preinitArray = findSection(".preinit_array");
1813   Out::initArray = findSection(".init_array");
1814   Out::finiArray = findSection(".fini_array");
1815 
1816   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1817   // symbols for sections, so that the runtime can get the start and end
1818   // addresses of each section by section name. Add such symbols.
1819   if (!config->relocatable) {
1820     addStartEndSymbols();
1821     for (SectionCommand *cmd : script->sectionCommands)
1822       if (auto *sec = dyn_cast<OutputSection>(cmd))
1823         addStartStopSymbols(sec);
1824   }
1825 
1826   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1827   // It should be okay as no one seems to care about the type.
1828   // Even the author of gold doesn't remember why gold behaves that way.
1829   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1830   if (mainPart->dynamic->parent)
1831     symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
1832         /*value=*/0, /*size=*/0, mainPart->dynamic.get()})->isUsedInRegularObj = true;
1833 
1834   // Define __rel[a]_iplt_{start,end} symbols if needed.
1835   addRelIpltSymbols();
1836 
1837   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1838   // should only be defined in an executable. If .sdata does not exist, its
1839   // value/section does not matter but it has to be relative, so set its
1840   // st_shndx arbitrarily to 1 (Out::elfHeader).
1841   if (config->emachine == EM_RISCV && !config->shared) {
1842     OutputSection *sec = findSection(".sdata");
1843     ElfSym::riscvGlobalPointer =
1844         addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader,
1845                            0x800, STV_DEFAULT);
1846   }
1847 
1848   if (config->emachine == EM_386 || config->emachine == EM_X86_64) {
1849     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1850     // way that:
1851     //
1852     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1853     // computes 0.
1854     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1855     // the TLS block).
1856     //
1857     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1858     // an absolute symbol of zero. This is different from GNU linkers which
1859     // define _TLS_MODULE_BASE_ relative to the first TLS section.
1860     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1861     if (s && s->isUndefined()) {
1862       s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
1863                          STT_TLS, /*value=*/0, 0,
1864                          /*section=*/nullptr});
1865       ElfSym::tlsModuleBase = cast<Defined>(s);
1866     }
1867   }
1868 
1869   {
1870     llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1871     // This responsible for splitting up .eh_frame section into
1872     // pieces. The relocation scan uses those pieces, so this has to be
1873     // earlier.
1874     for (Partition &part : partitions)
1875       finalizeSynthetic(part.ehFrame.get());
1876   }
1877 
1878   if (config->hasDynSymTab) {
1879     parallelForEach(symtab->symbols(), [](Symbol *sym) {
1880       sym->isPreemptible = computeIsPreemptible(*sym);
1881     });
1882   }
1883 
1884   // Change values of linker-script-defined symbols from placeholders (assigned
1885   // by declareSymbols) to actual definitions.
1886   script->processSymbolAssignments();
1887 
1888   {
1889     llvm::TimeTraceScope timeScope("Scan relocations");
1890     // Scan relocations. This must be done after every symbol is declared so
1891     // that we can correctly decide if a dynamic relocation is needed. This is
1892     // called after processSymbolAssignments() because it needs to know whether
1893     // a linker-script-defined symbol is absolute.
1894     ppc64noTocRelax.clear();
1895     if (!config->relocatable) {
1896       // Scan all relocations. Each relocation goes through a series of tests to
1897       // determine if it needs special treatment, such as creating GOT, PLT,
1898       // copy relocations, etc. Note that relocations for non-alloc sections are
1899       // directly processed by InputSection::relocateNonAlloc.
1900       for (InputSectionBase *sec : inputSections)
1901         if (sec->isLive() && isa<InputSection>(sec) && (sec->flags & SHF_ALLOC))
1902           scanRelocations<ELFT>(*sec);
1903       for (Partition &part : partitions) {
1904         for (EhInputSection *sec : part.ehFrame->sections)
1905           scanRelocations<ELFT>(*sec);
1906         if (part.armExidx && part.armExidx->isLive())
1907           for (InputSection *sec : part.armExidx->exidxSections)
1908             scanRelocations<ELFT>(*sec);
1909       }
1910 
1911       reportUndefinedSymbols();
1912       postScanRelocations();
1913     }
1914   }
1915 
1916   if (in.plt && in.plt->isNeeded())
1917     in.plt->addSymbols();
1918   if (in.iplt && in.iplt->isNeeded())
1919     in.iplt->addSymbols();
1920 
1921   if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1922     auto diagnose =
1923         config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
1924             ? errorOrWarn
1925             : warn;
1926     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1927     // entries are seen. These cases would otherwise lead to runtime errors
1928     // reported by the dynamic linker.
1929     //
1930     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1931     // catch more cases. That is too much for us. Our approach resembles the one
1932     // used in ld.gold, achieves a good balance to be useful but not too smart.
1933     for (SharedFile *file : sharedFiles) {
1934       bool allNeededIsKnown =
1935           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1936             return symtab->soNames.count(CachedHashStringRef(needed));
1937           });
1938       if (!allNeededIsKnown)
1939         continue;
1940       for (Symbol *sym : file->requiredSymbols)
1941         if (sym->isUndefined() && !sym->isWeak())
1942           diagnose(toString(file) + ": undefined reference to " +
1943                    toString(*sym) + " [--no-allow-shlib-undefined]");
1944     }
1945   }
1946 
1947   {
1948     llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1949     // Now that we have defined all possible global symbols including linker-
1950     // synthesized ones. Visit all symbols to give the finishing touches.
1951     for (Symbol *sym : symtab->symbols()) {
1952       if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))
1953         continue;
1954       if (!config->relocatable)
1955         sym->binding = sym->computeBinding();
1956       if (in.symTab)
1957         in.symTab->addSymbol(sym);
1958 
1959       if (sym->includeInDynsym()) {
1960         partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1961         if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
1962           if (file->isNeeded && !sym->isUndefined())
1963             addVerneed(sym);
1964       }
1965     }
1966 
1967     // We also need to scan the dynamic relocation tables of the other
1968     // partitions and add any referenced symbols to the partition's dynsym.
1969     for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
1970       DenseSet<Symbol *> syms;
1971       for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1972         syms.insert(e.sym);
1973       for (DynamicReloc &reloc : part.relaDyn->relocs)
1974         if (reloc.sym && reloc.needsDynSymIndex() &&
1975             syms.insert(reloc.sym).second)
1976           part.dynSymTab->addSymbol(reloc.sym);
1977     }
1978   }
1979 
1980   if (in.mipsGot)
1981     in.mipsGot->build();
1982 
1983   removeUnusedSyntheticSections();
1984   script->diagnoseOrphanHandling();
1985 
1986   sortSections();
1987 
1988   // Create a list of OutputSections, assign sectionIndex, and populate
1989   // in.shStrTab.
1990   for (SectionCommand *cmd : script->sectionCommands)
1991     if (auto *osec = dyn_cast<OutputSection>(cmd)) {
1992       outputSections.push_back(osec);
1993       osec->sectionIndex = outputSections.size();
1994       osec->shName = in.shStrTab->addString(osec->name);
1995     }
1996 
1997   // Prefer command line supplied address over other constraints.
1998   for (OutputSection *sec : outputSections) {
1999     auto i = config->sectionStartMap.find(sec->name);
2000     if (i != config->sectionStartMap.end())
2001       sec->addrExpr = [=] { return i->second; };
2002   }
2003 
2004   // With the outputSections available check for GDPLT relocations
2005   // and add __tls_get_addr symbol if needed.
2006   if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
2007     Symbol *sym = symtab->addSymbol(Undefined{
2008         nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2009     sym->isPreemptible = true;
2010     partitions[0].dynSymTab->addSymbol(sym);
2011   }
2012 
2013   // This is a bit of a hack. A value of 0 means undef, so we set it
2014   // to 1 to make __ehdr_start defined. The section number is not
2015   // particularly relevant.
2016   Out::elfHeader->sectionIndex = 1;
2017   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2018 
2019   // Binary and relocatable output does not have PHDRS.
2020   // The headers have to be created before finalize as that can influence the
2021   // image base and the dynamic section on mips includes the image base.
2022   if (!config->relocatable && !config->oFormatBinary) {
2023     for (Partition &part : partitions) {
2024       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2025                                               : createPhdrs(part);
2026       if (config->emachine == EM_ARM) {
2027         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2028         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2029       }
2030       if (config->emachine == EM_MIPS) {
2031         // Add separate segments for MIPS-specific sections.
2032         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2033         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2034         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2035       }
2036     }
2037     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2038 
2039     // Find the TLS segment. This happens before the section layout loop so that
2040     // Android relocation packing can look up TLS symbol addresses. We only need
2041     // to care about the main partition here because all TLS symbols were moved
2042     // to the main partition (see MarkLive.cpp).
2043     for (PhdrEntry *p : mainPart->phdrs)
2044       if (p->p_type == PT_TLS)
2045         Out::tlsPhdr = p;
2046   }
2047 
2048   // Some symbols are defined in term of program headers. Now that we
2049   // have the headers, we can find out which sections they point to.
2050   setReservedSymbolSections();
2051 
2052   {
2053     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2054 
2055     finalizeSynthetic(in.bss.get());
2056     finalizeSynthetic(in.bssRelRo.get());
2057     finalizeSynthetic(in.symTabShndx.get());
2058     finalizeSynthetic(in.shStrTab.get());
2059     finalizeSynthetic(in.strTab.get());
2060     finalizeSynthetic(in.got.get());
2061     finalizeSynthetic(in.mipsGot.get());
2062     finalizeSynthetic(in.igotPlt.get());
2063     finalizeSynthetic(in.gotPlt.get());
2064     finalizeSynthetic(in.relaIplt.get());
2065     finalizeSynthetic(in.relaPlt.get());
2066     finalizeSynthetic(in.plt.get());
2067     finalizeSynthetic(in.iplt.get());
2068     finalizeSynthetic(in.ppc32Got2.get());
2069     finalizeSynthetic(in.partIndex.get());
2070 
2071     // Dynamic section must be the last one in this list and dynamic
2072     // symbol table section (dynSymTab) must be the first one.
2073     for (Partition &part : partitions) {
2074       if (part.relaDyn) {
2075         // Compute DT_RELACOUNT to be used by part.dynamic.
2076         part.relaDyn->partitionRels();
2077         finalizeSynthetic(part.relaDyn.get());
2078       }
2079 
2080       finalizeSynthetic(part.dynSymTab.get());
2081       finalizeSynthetic(part.gnuHashTab.get());
2082       finalizeSynthetic(part.hashTab.get());
2083       finalizeSynthetic(part.verDef.get());
2084       finalizeSynthetic(part.relrDyn.get());
2085       finalizeSynthetic(part.ehFrameHdr.get());
2086       finalizeSynthetic(part.verSym.get());
2087       finalizeSynthetic(part.verNeed.get());
2088       finalizeSynthetic(part.dynamic.get());
2089     }
2090   }
2091 
2092   if (!script->hasSectionsCommand && !config->relocatable)
2093     fixSectionAlignments();
2094 
2095   // This is used to:
2096   // 1) Create "thunks":
2097   //    Jump instructions in many ISAs have small displacements, and therefore
2098   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
2099   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
2100   //    responsibility to create and insert small pieces of code between
2101   //    sections to extend the ranges if jump targets are out of range. Such
2102   //    code pieces are called "thunks".
2103   //
2104   //    We add thunks at this stage. We couldn't do this before this point
2105   //    because this is the earliest point where we know sizes of sections and
2106   //    their layouts (that are needed to determine if jump targets are in
2107   //    range).
2108   //
2109   // 2) Update the sections. We need to generate content that depends on the
2110   //    address of InputSections. For example, MIPS GOT section content or
2111   //    android packed relocations sections content.
2112   //
2113   // 3) Assign the final values for the linker script symbols. Linker scripts
2114   //    sometimes using forward symbol declarations. We want to set the correct
2115   //    values. They also might change after adding the thunks.
2116   finalizeAddressDependentContent();
2117 
2118   // All information needed for OutputSection part of Map file is available.
2119   if (errorCount())
2120     return;
2121 
2122   {
2123     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2124     // finalizeAddressDependentContent may have added local symbols to the
2125     // static symbol table.
2126     finalizeSynthetic(in.symTab.get());
2127     finalizeSynthetic(in.ppc64LongBranchTarget.get());
2128   }
2129 
2130   // Relaxation to delete inter-basic block jumps created by basic block
2131   // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2132   // can relax jump instructions based on symbol offset.
2133   if (config->optimizeBBJumps)
2134     optimizeBasicBlockJumps();
2135 
2136   // Fill other section headers. The dynamic table is finalized
2137   // at the end because some tags like RELSZ depend on result
2138   // of finalizing other sections.
2139   for (OutputSection *sec : outputSections)
2140     sec->finalize();
2141 }
2142 
2143 // Ensure data sections are not mixed with executable sections when
2144 // --execute-only is used. --execute-only make pages executable but not
2145 // readable.
2146 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2147   if (!config->executeOnly)
2148     return;
2149 
2150   for (OutputSection *osec : outputSections)
2151     if (osec->flags & SHF_EXECINSTR)
2152       for (InputSection *isec : getInputSections(*osec))
2153         if (!(isec->flags & SHF_EXECINSTR))
2154           error("cannot place " + toString(isec) + " into " +
2155                 toString(osec->name) +
2156                 ": --execute-only does not support intermingling data and code");
2157 }
2158 
2159 // The linker is expected to define SECNAME_start and SECNAME_end
2160 // symbols for a few sections. This function defines them.
2161 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2162   // If a section does not exist, there's ambiguity as to how we
2163   // define _start and _end symbols for an init/fini section. Since
2164   // the loader assume that the symbols are always defined, we need to
2165   // always define them. But what value? The loader iterates over all
2166   // pointers between _start and _end to run global ctors/dtors, so if
2167   // the section is empty, their symbol values don't actually matter
2168   // as long as _start and _end point to the same location.
2169   //
2170   // That said, we don't want to set the symbols to 0 (which is
2171   // probably the simplest value) because that could cause some
2172   // program to fail to link due to relocation overflow, if their
2173   // program text is above 2 GiB. We use the address of the .text
2174   // section instead to prevent that failure.
2175   //
2176   // In rare situations, the .text section may not exist. If that's the
2177   // case, use the image base address as a last resort.
2178   OutputSection *Default = findSection(".text");
2179   if (!Default)
2180     Default = Out::elfHeader;
2181 
2182   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2183     if (os && !script->isDiscarded(os)) {
2184       addOptionalRegular(start, os, 0);
2185       addOptionalRegular(end, os, -1);
2186     } else {
2187       addOptionalRegular(start, Default, 0);
2188       addOptionalRegular(end, Default, 0);
2189     }
2190   };
2191 
2192   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2193   define("__init_array_start", "__init_array_end", Out::initArray);
2194   define("__fini_array_start", "__fini_array_end", Out::finiArray);
2195 
2196   if (OutputSection *sec = findSection(".ARM.exidx"))
2197     define("__exidx_start", "__exidx_end", sec);
2198 }
2199 
2200 // If a section name is valid as a C identifier (which is rare because of
2201 // the leading '.'), linkers are expected to define __start_<secname> and
2202 // __stop_<secname> symbols. They are at beginning and end of the section,
2203 // respectively. This is not requested by the ELF standard, but GNU ld and
2204 // gold provide the feature, and used by many programs.
2205 template <class ELFT>
2206 void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
2207   StringRef s = sec->name;
2208   if (!isValidCIdentifier(s))
2209     return;
2210   addOptionalRegular(saver().save("__start_" + s), sec, 0,
2211                      config->zStartStopVisibility);
2212   addOptionalRegular(saver().save("__stop_" + s), sec, -1,
2213                      config->zStartStopVisibility);
2214 }
2215 
2216 static bool needsPtLoad(OutputSection *sec) {
2217   if (!(sec->flags & SHF_ALLOC))
2218     return false;
2219 
2220   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2221   // responsible for allocating space for them, not the PT_LOAD that
2222   // contains the TLS initialization image.
2223   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2224     return false;
2225   return true;
2226 }
2227 
2228 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2229 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2230 // RW. This means that there is no alignment in the RO to RX transition and we
2231 // cannot create a PT_LOAD there.
2232 static uint64_t computeFlags(uint64_t flags) {
2233   if (config->omagic)
2234     return PF_R | PF_W | PF_X;
2235   if (config->executeOnly && (flags & PF_X))
2236     return flags & ~PF_R;
2237   if (config->singleRoRx && !(flags & PF_W))
2238     return flags | PF_X;
2239   return flags;
2240 }
2241 
2242 // Decide which program headers to create and which sections to include in each
2243 // one.
2244 template <class ELFT>
2245 SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {
2246   SmallVector<PhdrEntry *, 0> ret;
2247   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2248     ret.push_back(make<PhdrEntry>(type, flags));
2249     return ret.back();
2250   };
2251 
2252   unsigned partNo = part.getNumber();
2253   bool isMain = partNo == 1;
2254 
2255   // Add the first PT_LOAD segment for regular output sections.
2256   uint64_t flags = computeFlags(PF_R);
2257   PhdrEntry *load = nullptr;
2258 
2259   // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2260   // PT_LOAD.
2261   if (!config->nmagic && !config->omagic) {
2262     // The first phdr entry is PT_PHDR which describes the program header
2263     // itself.
2264     if (isMain)
2265       addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2266     else
2267       addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2268 
2269     // PT_INTERP must be the second entry if exists.
2270     if (OutputSection *cmd = findSection(".interp", partNo))
2271       addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2272 
2273     // Add the headers. We will remove them if they don't fit.
2274     // In the other partitions the headers are ordinary sections, so they don't
2275     // need to be added here.
2276     if (isMain) {
2277       load = addHdr(PT_LOAD, flags);
2278       load->add(Out::elfHeader);
2279       load->add(Out::programHeaders);
2280     }
2281   }
2282 
2283   // PT_GNU_RELRO includes all sections that should be marked as
2284   // read-only by dynamic linker after processing relocations.
2285   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2286   // an error message if more than one PT_GNU_RELRO PHDR is required.
2287   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2288   bool inRelroPhdr = false;
2289   OutputSection *relroEnd = nullptr;
2290   for (OutputSection *sec : outputSections) {
2291     if (sec->partition != partNo || !needsPtLoad(sec))
2292       continue;
2293     if (isRelroSection(sec)) {
2294       inRelroPhdr = true;
2295       if (!relroEnd)
2296         relRo->add(sec);
2297       else
2298         error("section: " + sec->name + " is not contiguous with other relro" +
2299               " sections");
2300     } else if (inRelroPhdr) {
2301       inRelroPhdr = false;
2302       relroEnd = sec;
2303     }
2304   }
2305 
2306   for (OutputSection *sec : outputSections) {
2307     if (!needsPtLoad(sec))
2308       continue;
2309 
2310     // Normally, sections in partitions other than the current partition are
2311     // ignored. But partition number 255 is a special case: it contains the
2312     // partition end marker (.part.end). It needs to be added to the main
2313     // partition so that a segment is created for it in the main partition,
2314     // which will cause the dynamic loader to reserve space for the other
2315     // partitions.
2316     if (sec->partition != partNo) {
2317       if (isMain && sec->partition == 255)
2318         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2319       continue;
2320     }
2321 
2322     // Segments are contiguous memory regions that has the same attributes
2323     // (e.g. executable or writable). There is one phdr for each segment.
2324     // Therefore, we need to create a new phdr when the next section has
2325     // different flags or is loaded at a discontiguous address or memory
2326     // region using AT or AT> linker script command, respectively. At the same
2327     // time, we don't want to create a separate load segment for the headers,
2328     // even if the first output section has an AT or AT> attribute.
2329     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2330     bool sameLMARegion =
2331         load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2332     if (!(load && newFlags == flags && sec != relroEnd &&
2333           sec->memRegion == load->firstSec->memRegion &&
2334           (sameLMARegion || load->lastSec == Out::programHeaders))) {
2335       load = addHdr(PT_LOAD, newFlags);
2336       flags = newFlags;
2337     }
2338 
2339     load->add(sec);
2340   }
2341 
2342   // Add a TLS segment if any.
2343   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2344   for (OutputSection *sec : outputSections)
2345     if (sec->partition == partNo && sec->flags & SHF_TLS)
2346       tlsHdr->add(sec);
2347   if (tlsHdr->firstSec)
2348     ret.push_back(tlsHdr);
2349 
2350   // Add an entry for .dynamic.
2351   if (OutputSection *sec = part.dynamic->getParent())
2352     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2353 
2354   if (relRo->firstSec)
2355     ret.push_back(relRo);
2356 
2357   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2358   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2359       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2360     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2361         ->add(part.ehFrameHdr->getParent());
2362 
2363   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2364   // the dynamic linker fill the segment with random data.
2365   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2366     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2367 
2368   if (config->zGnustack != GnuStackKind::None) {
2369     // PT_GNU_STACK is a special section to tell the loader to make the
2370     // pages for the stack non-executable. If you really want an executable
2371     // stack, you can pass -z execstack, but that's not recommended for
2372     // security reasons.
2373     unsigned perm = PF_R | PF_W;
2374     if (config->zGnustack == GnuStackKind::Exec)
2375       perm |= PF_X;
2376     addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2377   }
2378 
2379   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2380   // is expected to perform W^X violations, such as calling mprotect(2) or
2381   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2382   // OpenBSD.
2383   if (config->zWxneeded)
2384     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2385 
2386   if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2387     addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2388 
2389   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2390   // same alignment.
2391   PhdrEntry *note = nullptr;
2392   for (OutputSection *sec : outputSections) {
2393     if (sec->partition != partNo)
2394       continue;
2395     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2396       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2397         note = addHdr(PT_NOTE, PF_R);
2398       note->add(sec);
2399     } else {
2400       note = nullptr;
2401     }
2402   }
2403   return ret;
2404 }
2405 
2406 template <class ELFT>
2407 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2408                                      unsigned pType, unsigned pFlags) {
2409   unsigned partNo = part.getNumber();
2410   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2411     return cmd->partition == partNo && cmd->type == shType;
2412   });
2413   if (i == outputSections.end())
2414     return;
2415 
2416   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2417   entry->add(*i);
2418   part.phdrs.push_back(entry);
2419 }
2420 
2421 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2422 // This is achieved by assigning an alignment expression to addrExpr of each
2423 // such section.
2424 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2425   const PhdrEntry *prev;
2426   auto pageAlign = [&](const PhdrEntry *p) {
2427     OutputSection *cmd = p->firstSec;
2428     if (!cmd)
2429       return;
2430     cmd->alignExpr = [align = cmd->alignment]() { return align; };
2431     if (!cmd->addrExpr) {
2432       // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2433       // padding in the file contents.
2434       //
2435       // When -z separate-code is used we must not have any overlap in pages
2436       // between an executable segment and a non-executable segment. We align to
2437       // the next maximum page size boundary on transitions between executable
2438       // and non-executable segments.
2439       //
2440       // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2441       // sections will be extracted to a separate file. Align to the next
2442       // maximum page size boundary so that we can find the ELF header at the
2443       // start. We cannot benefit from overlapping p_offset ranges with the
2444       // previous segment anyway.
2445       if (config->zSeparate == SeparateSegmentKind::Loadable ||
2446           (config->zSeparate == SeparateSegmentKind::Code && prev &&
2447            (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2448           cmd->type == SHT_LLVM_PART_EHDR)
2449         cmd->addrExpr = [] {
2450           return alignTo(script->getDot(), config->maxPageSize);
2451         };
2452       // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2453       // it must be the RW. Align to p_align(PT_TLS) to make sure
2454       // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2455       // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2456       // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2457       // be congruent to 0 modulo p_align(PT_TLS).
2458       //
2459       // Technically this is not required, but as of 2019, some dynamic loaders
2460       // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2461       // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2462       // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2463       // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2464       // blocks correctly. We need to keep the workaround for a while.
2465       else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2466         cmd->addrExpr = [] {
2467           return alignTo(script->getDot(), config->maxPageSize) +
2468                  alignTo(script->getDot() % config->maxPageSize,
2469                          Out::tlsPhdr->p_align);
2470         };
2471       else
2472         cmd->addrExpr = [] {
2473           return alignTo(script->getDot(), config->maxPageSize) +
2474                  script->getDot() % config->maxPageSize;
2475         };
2476     }
2477   };
2478 
2479   for (Partition &part : partitions) {
2480     prev = nullptr;
2481     for (const PhdrEntry *p : part.phdrs)
2482       if (p->p_type == PT_LOAD && p->firstSec) {
2483         pageAlign(p);
2484         prev = p;
2485       }
2486   }
2487 }
2488 
2489 // Compute an in-file position for a given section. The file offset must be the
2490 // same with its virtual address modulo the page size, so that the loader can
2491 // load executables without any address adjustment.
2492 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2493   // The first section in a PT_LOAD has to have congruent offset and address
2494   // modulo the maximum page size.
2495   if (os->ptLoad && os->ptLoad->firstSec == os)
2496     return alignTo(off, os->ptLoad->p_align, os->addr);
2497 
2498   // File offsets are not significant for .bss sections other than the first one
2499   // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2500   // increasing rather than setting to zero.
2501   if (os->type == SHT_NOBITS &&
2502       (!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
2503      return off;
2504 
2505   // If the section is not in a PT_LOAD, we just have to align it.
2506   if (!os->ptLoad)
2507     return alignTo(off, os->alignment);
2508 
2509   // If two sections share the same PT_LOAD the file offset is calculated
2510   // using this formula: Off2 = Off1 + (VA2 - VA1).
2511   OutputSection *first = os->ptLoad->firstSec;
2512   return first->offset + os->addr - first->addr;
2513 }
2514 
2515 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2516   // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2517   auto needsOffset = [](OutputSection &sec) {
2518     return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2519   };
2520   uint64_t minAddr = UINT64_MAX;
2521   for (OutputSection *sec : outputSections)
2522     if (needsOffset(*sec)) {
2523       sec->offset = sec->getLMA();
2524       minAddr = std::min(minAddr, sec->offset);
2525     }
2526 
2527   // Sections are laid out at LMA minus minAddr.
2528   fileSize = 0;
2529   for (OutputSection *sec : outputSections)
2530     if (needsOffset(*sec)) {
2531       sec->offset -= minAddr;
2532       fileSize = std::max(fileSize, sec->offset + sec->size);
2533     }
2534 }
2535 
2536 static std::string rangeToString(uint64_t addr, uint64_t len) {
2537   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2538 }
2539 
2540 // Assign file offsets to output sections.
2541 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2542   Out::programHeaders->offset = Out::elfHeader->size;
2543   uint64_t off = Out::elfHeader->size + Out::programHeaders->size;
2544 
2545   PhdrEntry *lastRX = nullptr;
2546   for (Partition &part : partitions)
2547     for (PhdrEntry *p : part.phdrs)
2548       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2549         lastRX = p;
2550 
2551   // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2552   // will not occupy file offsets contained by a PT_LOAD.
2553   for (OutputSection *sec : outputSections) {
2554     if (!(sec->flags & SHF_ALLOC))
2555       continue;
2556     off = computeFileOffset(sec, off);
2557     sec->offset = off;
2558     if (sec->type != SHT_NOBITS)
2559       off += sec->size;
2560 
2561     // If this is a last section of the last executable segment and that
2562     // segment is the last loadable segment, align the offset of the
2563     // following section to avoid loading non-segments parts of the file.
2564     if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2565         lastRX->lastSec == sec)
2566       off = alignTo(off, config->maxPageSize);
2567   }
2568   for (OutputSection *osec : outputSections)
2569     if (!(osec->flags & SHF_ALLOC)) {
2570       osec->offset = alignTo(off, osec->alignment);
2571       off = osec->offset + osec->size;
2572     }
2573 
2574   sectionHeaderOff = alignTo(off, config->wordsize);
2575   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2576 
2577   // Our logic assumes that sections have rising VA within the same segment.
2578   // With use of linker scripts it is possible to violate this rule and get file
2579   // offset overlaps or overflows. That should never happen with a valid script
2580   // which does not move the location counter backwards and usually scripts do
2581   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2582   // kernel, which control segment distribution explicitly and move the counter
2583   // backwards, so we have to allow doing that to support linking them. We
2584   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2585   // we want to prevent file size overflows because it would crash the linker.
2586   for (OutputSection *sec : outputSections) {
2587     if (sec->type == SHT_NOBITS)
2588       continue;
2589     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2590       error("unable to place section " + sec->name + " at file offset " +
2591             rangeToString(sec->offset, sec->size) +
2592             "; check your linker script for overflows");
2593   }
2594 }
2595 
2596 // Finalize the program headers. We call this function after we assign
2597 // file offsets and VAs to all sections.
2598 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2599   for (PhdrEntry *p : part.phdrs) {
2600     OutputSection *first = p->firstSec;
2601     OutputSection *last = p->lastSec;
2602 
2603     if (first) {
2604       p->p_filesz = last->offset - first->offset;
2605       if (last->type != SHT_NOBITS)
2606         p->p_filesz += last->size;
2607 
2608       p->p_memsz = last->addr + last->size - first->addr;
2609       p->p_offset = first->offset;
2610       p->p_vaddr = first->addr;
2611 
2612       // File offsets in partitions other than the main partition are relative
2613       // to the offset of the ELF headers. Perform that adjustment now.
2614       if (part.elfHeader)
2615         p->p_offset -= part.elfHeader->getParent()->offset;
2616 
2617       if (!p->hasLMA)
2618         p->p_paddr = first->getLMA();
2619     }
2620 
2621     if (p->p_type == PT_GNU_RELRO) {
2622       p->p_align = 1;
2623       // musl/glibc ld.so rounds the size down, so we need to round up
2624       // to protect the last page. This is a no-op on FreeBSD which always
2625       // rounds up.
2626       p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) -
2627                    p->p_offset;
2628     }
2629   }
2630 }
2631 
2632 // A helper struct for checkSectionOverlap.
2633 namespace {
2634 struct SectionOffset {
2635   OutputSection *sec;
2636   uint64_t offset;
2637 };
2638 } // namespace
2639 
2640 // Check whether sections overlap for a specific address range (file offsets,
2641 // load and virtual addresses).
2642 static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2643                          bool isVirtualAddr) {
2644   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2645     return a.offset < b.offset;
2646   });
2647 
2648   // Finding overlap is easy given a vector is sorted by start position.
2649   // If an element starts before the end of the previous element, they overlap.
2650   for (size_t i = 1, end = sections.size(); i < end; ++i) {
2651     SectionOffset a = sections[i - 1];
2652     SectionOffset b = sections[i];
2653     if (b.offset >= a.offset + a.sec->size)
2654       continue;
2655 
2656     // If both sections are in OVERLAY we allow the overlapping of virtual
2657     // addresses, because it is what OVERLAY was designed for.
2658     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2659       continue;
2660 
2661     errorOrWarn("section " + a.sec->name + " " + name +
2662                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2663                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2664                 b.sec->name + " range is " +
2665                 rangeToString(b.offset, b.sec->size));
2666   }
2667 }
2668 
2669 // Check for overlapping sections and address overflows.
2670 //
2671 // In this function we check that none of the output sections have overlapping
2672 // file offsets. For SHF_ALLOC sections we also check that the load address
2673 // ranges and the virtual address ranges don't overlap
2674 template <class ELFT> void Writer<ELFT>::checkSections() {
2675   // First, check that section's VAs fit in available address space for target.
2676   for (OutputSection *os : outputSections)
2677     if ((os->addr + os->size < os->addr) ||
2678         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2679       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2680                   " of size 0x" + utohexstr(os->size) +
2681                   " exceeds available address space");
2682 
2683   // Check for overlapping file offsets. In this case we need to skip any
2684   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2685   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2686   // binary is specified only add SHF_ALLOC sections are added to the output
2687   // file so we skip any non-allocated sections in that case.
2688   std::vector<SectionOffset> fileOffs;
2689   for (OutputSection *sec : outputSections)
2690     if (sec->size > 0 && sec->type != SHT_NOBITS &&
2691         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2692       fileOffs.push_back({sec, sec->offset});
2693   checkOverlap("file", fileOffs, false);
2694 
2695   // When linking with -r there is no need to check for overlapping virtual/load
2696   // addresses since those addresses will only be assigned when the final
2697   // executable/shared object is created.
2698   if (config->relocatable)
2699     return;
2700 
2701   // Checking for overlapping virtual and load addresses only needs to take
2702   // into account SHF_ALLOC sections since others will not be loaded.
2703   // Furthermore, we also need to skip SHF_TLS sections since these will be
2704   // mapped to other addresses at runtime and can therefore have overlapping
2705   // ranges in the file.
2706   std::vector<SectionOffset> vmas;
2707   for (OutputSection *sec : outputSections)
2708     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2709       vmas.push_back({sec, sec->addr});
2710   checkOverlap("virtual address", vmas, true);
2711 
2712   // Finally, check that the load addresses don't overlap. This will usually be
2713   // the same as the virtual addresses but can be different when using a linker
2714   // script with AT().
2715   std::vector<SectionOffset> lmas;
2716   for (OutputSection *sec : outputSections)
2717     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2718       lmas.push_back({sec, sec->getLMA()});
2719   checkOverlap("load address", lmas, false);
2720 }
2721 
2722 // The entry point address is chosen in the following ways.
2723 //
2724 // 1. the '-e' entry command-line option;
2725 // 2. the ENTRY(symbol) command in a linker control script;
2726 // 3. the value of the symbol _start, if present;
2727 // 4. the number represented by the entry symbol, if it is a number;
2728 // 5. the address 0.
2729 static uint64_t getEntryAddr() {
2730   // Case 1, 2 or 3
2731   if (Symbol *b = symtab->find(config->entry))
2732     return b->getVA();
2733 
2734   // Case 4
2735   uint64_t addr;
2736   if (to_integer(config->entry, addr))
2737     return addr;
2738 
2739   // Case 5
2740   if (config->warnMissingEntry)
2741     warn("cannot find entry symbol " + config->entry +
2742          "; not setting start address");
2743   return 0;
2744 }
2745 
2746 static uint16_t getELFType() {
2747   if (config->isPic)
2748     return ET_DYN;
2749   if (config->relocatable)
2750     return ET_REL;
2751   return ET_EXEC;
2752 }
2753 
2754 template <class ELFT> void Writer<ELFT>::writeHeader() {
2755   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2756   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2757 
2758   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2759   eHdr->e_type = getELFType();
2760   eHdr->e_entry = getEntryAddr();
2761   eHdr->e_shoff = sectionHeaderOff;
2762 
2763   // Write the section header table.
2764   //
2765   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2766   // and e_shstrndx fields. When the value of one of these fields exceeds
2767   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2768   // use fields in the section header at index 0 to store
2769   // the value. The sentinel values and fields are:
2770   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2771   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2772   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2773   size_t num = outputSections.size() + 1;
2774   if (num >= SHN_LORESERVE)
2775     sHdrs->sh_size = num;
2776   else
2777     eHdr->e_shnum = num;
2778 
2779   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2780   if (strTabIndex >= SHN_LORESERVE) {
2781     sHdrs->sh_link = strTabIndex;
2782     eHdr->e_shstrndx = SHN_XINDEX;
2783   } else {
2784     eHdr->e_shstrndx = strTabIndex;
2785   }
2786 
2787   for (OutputSection *sec : outputSections)
2788     sec->writeHeaderTo<ELFT>(++sHdrs);
2789 }
2790 
2791 // Open a result file.
2792 template <class ELFT> void Writer<ELFT>::openFile() {
2793   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2794   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2795     std::string msg;
2796     raw_string_ostream s(msg);
2797     s << "output file too large: " << Twine(fileSize) << " bytes\n"
2798       << "section sizes:\n";
2799     for (OutputSection *os : outputSections)
2800       s << os->name << ' ' << os->size << "\n";
2801     error(s.str());
2802     return;
2803   }
2804 
2805   unlinkAsync(config->outputFile);
2806   unsigned flags = 0;
2807   if (!config->relocatable)
2808     flags |= FileOutputBuffer::F_executable;
2809   if (!config->mmapOutputFile)
2810     flags |= FileOutputBuffer::F_no_mmap;
2811   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2812       FileOutputBuffer::create(config->outputFile, fileSize, flags);
2813 
2814   if (!bufferOrErr) {
2815     error("failed to open " + config->outputFile + ": " +
2816           llvm::toString(bufferOrErr.takeError()));
2817     return;
2818   }
2819   buffer = std::move(*bufferOrErr);
2820   Out::bufferStart = buffer->getBufferStart();
2821 }
2822 
2823 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2824   for (OutputSection *sec : outputSections)
2825     if (sec->flags & SHF_ALLOC)
2826       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2827 }
2828 
2829 static void fillTrap(uint8_t *i, uint8_t *end) {
2830   for (; i + 4 <= end; i += 4)
2831     memcpy(i, &target->trapInstr, 4);
2832 }
2833 
2834 // Fill the last page of executable segments with trap instructions
2835 // instead of leaving them as zero. Even though it is not required by any
2836 // standard, it is in general a good thing to do for security reasons.
2837 //
2838 // We'll leave other pages in segments as-is because the rest will be
2839 // overwritten by output sections.
2840 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2841   for (Partition &part : partitions) {
2842     // Fill the last page.
2843     for (PhdrEntry *p : part.phdrs)
2844       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2845         fillTrap(Out::bufferStart +
2846                      alignDown(p->firstSec->offset + p->p_filesz, 4),
2847                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2848                                             config->maxPageSize));
2849 
2850     // Round up the file size of the last segment to the page boundary iff it is
2851     // an executable segment to ensure that other tools don't accidentally
2852     // trim the instruction padding (e.g. when stripping the file).
2853     PhdrEntry *last = nullptr;
2854     for (PhdrEntry *p : part.phdrs)
2855       if (p->p_type == PT_LOAD)
2856         last = p;
2857 
2858     if (last && (last->p_flags & PF_X))
2859       last->p_memsz = last->p_filesz =
2860           alignTo(last->p_filesz, config->maxPageSize);
2861   }
2862 }
2863 
2864 // Write section contents to a mmap'ed file.
2865 template <class ELFT> void Writer<ELFT>::writeSections() {
2866   llvm::TimeTraceScope timeScope("Write sections");
2867 
2868   // In -r or --emit-relocs mode, write the relocation sections first as in
2869   // ELf_Rel targets we might find out that we need to modify the relocated
2870   // section while doing it.
2871   for (OutputSection *sec : outputSections)
2872     if (sec->type == SHT_REL || sec->type == SHT_RELA)
2873       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2874 
2875   for (OutputSection *sec : outputSections)
2876     if (sec->type != SHT_REL && sec->type != SHT_RELA)
2877       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2878 
2879   // Finally, check that all dynamic relocation addends were written correctly.
2880   if (config->checkDynamicRelocs && config->writeAddends) {
2881     for (OutputSection *sec : outputSections)
2882       if (sec->type == SHT_REL || sec->type == SHT_RELA)
2883         sec->checkDynRelAddends(Out::bufferStart);
2884   }
2885 }
2886 
2887 // Computes a hash value of Data using a given hash function.
2888 // In order to utilize multiple cores, we first split data into 1MB
2889 // chunks, compute a hash for each chunk, and then compute a hash value
2890 // of the hash values.
2891 static void
2892 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2893             llvm::ArrayRef<uint8_t> data,
2894             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2895   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2896   const size_t hashesSize = chunks.size() * hashBuf.size();
2897   std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2898 
2899   // Compute hash values.
2900   parallelForEachN(0, chunks.size(), [&](size_t i) {
2901     hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2902   });
2903 
2904   // Write to the final output buffer.
2905   hashFn(hashBuf.data(), makeArrayRef(hashes.get(), hashesSize));
2906 }
2907 
2908 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2909   if (!mainPart->buildId || !mainPart->buildId->getParent())
2910     return;
2911 
2912   if (config->buildId == BuildIdKind::Hexstring) {
2913     for (Partition &part : partitions)
2914       part.buildId->writeBuildId(config->buildIdVector);
2915     return;
2916   }
2917 
2918   // Compute a hash of all sections of the output file.
2919   size_t hashSize = mainPart->buildId->hashSize;
2920   std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
2921   MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
2922   llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};
2923 
2924   switch (config->buildId) {
2925   case BuildIdKind::Fast:
2926     computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2927       write64le(dest, xxHash64(arr));
2928     });
2929     break;
2930   case BuildIdKind::Md5:
2931     computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2932       memcpy(dest, MD5::hash(arr).data(), hashSize);
2933     });
2934     break;
2935   case BuildIdKind::Sha1:
2936     computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2937       memcpy(dest, SHA1::hash(arr).data(), hashSize);
2938     });
2939     break;
2940   case BuildIdKind::Uuid:
2941     if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
2942       error("entropy source failure: " + ec.message());
2943     break;
2944   default:
2945     llvm_unreachable("unknown BuildIdKind");
2946   }
2947   for (Partition &part : partitions)
2948     part.buildId->writeBuildId(output);
2949 }
2950 
2951 template void elf::createSyntheticSections<ELF32LE>();
2952 template void elf::createSyntheticSections<ELF32BE>();
2953 template void elf::createSyntheticSections<ELF64LE>();
2954 template void elf::createSyntheticSections<ELF64BE>();
2955 
2956 template void elf::writeResult<ELF32LE>();
2957 template void elf::writeResult<ELF32BE>();
2958 template void elf::writeResult<ELF64LE>();
2959 template void elf::writeResult<ELF64BE>();
2960