xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 779bbbf2)
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 "LinkerScript.h"
15 #include "MapFile.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
18 #include "SymbolTable.h"
19 #include "Symbols.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "lld/Common/Arrays.h"
23 #include "lld/Common/CommonLinkerContext.h"
24 #include "lld/Common/Filesystem.h"
25 #include "lld/Common/Strings.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/Support/Parallel.h"
28 #include "llvm/Support/RandomNumberGenerator.h"
29 #include "llvm/Support/SHA1.h"
30 #include "llvm/Support/TimeProfiler.h"
31 #include "llvm/Support/xxhash.h"
32 #include <climits>
33 
34 #define DEBUG_TYPE "lld"
35 
36 using namespace llvm;
37 using namespace llvm::ELF;
38 using namespace llvm::object;
39 using namespace llvm::support;
40 using namespace llvm::support::endian;
41 using namespace lld;
42 using namespace lld::elf;
43 
44 namespace {
45 // The writer writes a SymbolTable result to a file.
46 template <class ELFT> class Writer {
47 public:
48   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
49 
50   Writer() : buffer(errorHandler().outputBuffer) {}
51 
52   void run();
53 
54 private:
55   void copyLocalSymbols();
56   void addSectionSymbols();
57   void sortSections();
58   void resolveShfLinkOrder();
59   void finalizeAddressDependentContent();
60   void optimizeBasicBlockJumps();
61   void sortInputSections();
62   void finalizeSections();
63   void checkExecuteOnly();
64   void setReservedSymbolSections();
65 
66   SmallVector<PhdrEntry *, 0> createPhdrs(Partition &part);
67   void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
68                          unsigned pFlags);
69   void assignFileOffsets();
70   void assignFileOffsetsBinary();
71   void setPhdrs(Partition &part);
72   void checkSections();
73   void fixSectionAlignments();
74   void openFile();
75   void writeTrapInstr();
76   void writeHeader();
77   void writeSections();
78   void writeSectionsBinary();
79   void writeBuildId();
80 
81   std::unique_ptr<FileOutputBuffer> &buffer;
82 
83   void addRelIpltSymbols();
84   void addStartEndSymbols();
85   void addStartStopSymbols(OutputSection *sec);
86 
87   uint64_t fileSize;
88   uint64_t sectionHeaderOff;
89 };
90 } // anonymous namespace
91 
92 static bool needsInterpSection() {
93   return !config->relocatable && !config->shared &&
94          !config->dynamicLinker.empty() && script->needsInterpSection();
95 }
96 
97 template <class ELFT> void elf::writeResult() {
98   Writer<ELFT>().run();
99 }
100 
101 static void removeEmptyPTLoad(SmallVector<PhdrEntry *, 0> &phdrs) {
102   auto it = std::stable_partition(
103       phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {
104         if (p->p_type != PT_LOAD)
105           return true;
106         if (!p->firstSec)
107           return false;
108         uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
109         return size != 0;
110       });
111 
112   // Clear OutputSection::ptLoad for sections contained in removed
113   // segments.
114   DenseSet<PhdrEntry *> removed(it, phdrs.end());
115   for (OutputSection *sec : outputSections)
116     if (removed.count(sec->ptLoad))
117       sec->ptLoad = nullptr;
118   phdrs.erase(it, phdrs.end());
119 }
120 
121 void elf::copySectionsIntoPartitions() {
122   SmallVector<InputSectionBase *, 0> newSections;
123   for (unsigned part = 2; part != partitions.size() + 1; ++part) {
124     for (InputSectionBase *s : inputSections) {
125       if (!(s->flags & SHF_ALLOC) || !s->isLive())
126         continue;
127       InputSectionBase *copy;
128       if (s->type == SHT_NOTE)
129         copy = make<InputSection>(cast<InputSection>(*s));
130       else if (auto *es = dyn_cast<EhInputSection>(s))
131         copy = make<EhInputSection>(*es);
132       else
133         continue;
134       copy->partition = part;
135       newSections.push_back(copy);
136     }
137   }
138 
139   inputSections.insert(inputSections.end(), newSections.begin(),
140                        newSections.end());
141 }
142 
143 void elf::combineEhSections() {
144   llvm::TimeTraceScope timeScope("Combine EH sections");
145   for (InputSectionBase *&s : inputSections) {
146     // Ignore dead sections and the partition end marker (.part.end),
147     // whose partition number is out of bounds.
148     if (!s->isLive() || s->partition == 255)
149       continue;
150 
151     Partition &part = s->getPartition();
152     if (auto *es = dyn_cast<EhInputSection>(s)) {
153       part.ehFrame->addSection(es);
154       s = nullptr;
155     } else if (s->kind() == SectionBase::Regular && part.armExidx &&
156                part.armExidx->addSection(cast<InputSection>(s))) {
157       s = nullptr;
158     }
159   }
160 
161   llvm::erase_value(inputSections, nullptr);
162 }
163 
164 static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
165                                    uint64_t val, uint8_t stOther = STV_HIDDEN) {
166   Symbol *s = symtab->find(name);
167   if (!s || s->isDefined())
168     return nullptr;
169 
170   s->resolve(Defined{nullptr, StringRef(), STB_GLOBAL, stOther, STT_NOTYPE, val,
171                      /*size=*/0, sec});
172   return cast<Defined>(s);
173 }
174 
175 static Defined *addAbsolute(StringRef name) {
176   Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
177                                           STT_NOTYPE, 0, 0, nullptr});
178   return cast<Defined>(sym);
179 }
180 
181 // The linker is expected to define some symbols depending on
182 // the linking result. This function defines such symbols.
183 void elf::addReservedSymbols() {
184   if (config->emachine == EM_MIPS) {
185     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
186     // so that it points to an absolute address which by default is relative
187     // to GOT. Default offset is 0x7ff0.
188     // See "Global Data Symbols" in Chapter 6 in the following document:
189     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
190     ElfSym::mipsGp = addAbsolute("_gp");
191 
192     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
193     // start of function and 'gp' pointer into GOT.
194     if (symtab->find("_gp_disp"))
195       ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
196 
197     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
198     // pointer. This symbol is used in the code generated by .cpload pseudo-op
199     // in case of using -mno-shared option.
200     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
201     if (symtab->find("__gnu_local_gp"))
202       ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
203   } else if (config->emachine == EM_PPC) {
204     // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
205     // support Small Data Area, define it arbitrarily as 0.
206     addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
207   } else if (config->emachine == EM_PPC64) {
208     addPPC64SaveRestore();
209   }
210 
211   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
212   // combines the typical ELF GOT with the small data sections. It commonly
213   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
214   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
215   // represent the TOC base which is offset by 0x8000 bytes from the start of
216   // the .got section.
217   // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
218   // correctness of some relocations depends on its value.
219   StringRef gotSymName =
220       (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
221 
222   if (Symbol *s = symtab->find(gotSymName)) {
223     if (s->isDefined()) {
224       error(toString(s->file) + " cannot redefine linker defined symbol '" +
225             gotSymName + "'");
226       return;
227     }
228 
229     uint64_t gotOff = 0;
230     if (config->emachine == EM_PPC64)
231       gotOff = 0x8000;
232 
233     s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
234                        STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
235     ElfSym::globalOffsetTable = cast<Defined>(s);
236   }
237 
238   // __ehdr_start is the location of ELF file headers. Note that we define
239   // this symbol unconditionally even when using a linker script, which
240   // differs from the behavior implemented by GNU linker which only define
241   // this symbol if ELF headers are in the memory mapped segment.
242   addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
243 
244   // __executable_start is not documented, but the expectation of at
245   // least the Android libc is that it points to the ELF header.
246   addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
247 
248   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
249   // each DSO. The address of the symbol doesn't matter as long as they are
250   // different in different DSOs, so we chose the start address of the DSO.
251   addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
252 
253   // If linker script do layout we do not need to create any standard symbols.
254   if (script->hasSectionsCommand)
255     return;
256 
257   auto add = [](StringRef s, int64_t pos) {
258     return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
259   };
260 
261   ElfSym::bss = add("__bss_start", 0);
262   ElfSym::end1 = add("end", -1);
263   ElfSym::end2 = add("_end", -1);
264   ElfSym::etext1 = add("etext", -1);
265   ElfSym::etext2 = add("_etext", -1);
266   ElfSym::edata1 = add("edata", -1);
267   ElfSym::edata2 = add("_edata", -1);
268 }
269 
270 static OutputSection *findSection(StringRef name, unsigned partition = 1) {
271   for (SectionCommand *cmd : script->sectionCommands)
272     if (auto *sec = dyn_cast<OutputSection>(cmd))
273       if (sec->name == name && sec->partition == partition)
274         return sec;
275   return nullptr;
276 }
277 
278 template <class ELFT> void elf::createSyntheticSections() {
279   // Initialize all pointers with NULL. This is needed because
280   // you can call lld::elf::main more than once as a library.
281   Out::tlsPhdr = nullptr;
282   Out::preinitArray = nullptr;
283   Out::initArray = nullptr;
284   Out::finiArray = nullptr;
285 
286   // Add the .interp section first because it is not a SyntheticSection.
287   // The removeUnusedSyntheticSections() function relies on the
288   // SyntheticSections coming last.
289   if (needsInterpSection()) {
290     for (size_t i = 1; i <= partitions.size(); ++i) {
291       InputSection *sec = createInterpSection();
292       sec->partition = i;
293       inputSections.push_back(sec);
294     }
295   }
296 
297   auto add = [](SyntheticSection &sec) { inputSections.push_back(&sec); };
298 
299   in.shStrTab = std::make_unique<StringTableSection>(".shstrtab", false);
300 
301   Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
302   Out::programHeaders->alignment = config->wordsize;
303 
304   if (config->strip != StripPolicy::All) {
305     in.strTab = std::make_unique<StringTableSection>(".strtab", false);
306     in.symTab = std::make_unique<SymbolTableSection<ELFT>>(*in.strTab);
307     in.symTabShndx = std::make_unique<SymtabShndxSection>();
308   }
309 
310   in.bss = std::make_unique<BssSection>(".bss", 0, 1);
311   add(*in.bss);
312 
313   // If there is a SECTIONS command and a .data.rel.ro section name use name
314   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
315   // This makes sure our relro is contiguous.
316   bool hasDataRelRo = script->hasSectionsCommand && findSection(".data.rel.ro");
317   in.bssRelRo = std::make_unique<BssSection>(
318       hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
319   add(*in.bssRelRo);
320 
321   // Add MIPS-specific sections.
322   if (config->emachine == EM_MIPS) {
323     if (!config->shared && config->hasDynSymTab) {
324       in.mipsRldMap = std::make_unique<MipsRldMapSection>();
325       add(*in.mipsRldMap);
326     }
327     if ((in.mipsAbiFlags = MipsAbiFlagsSection<ELFT>::create()))
328       add(*in.mipsAbiFlags);
329     if ((in.mipsOptions = MipsOptionsSection<ELFT>::create()))
330       add(*in.mipsOptions);
331     if ((in.mipsReginfo = MipsReginfoSection<ELFT>::create()))
332       add(*in.mipsReginfo);
333   }
334 
335   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
336 
337   for (Partition &part : partitions) {
338     auto add = [&](SyntheticSection &sec) {
339       sec.partition = part.getNumber();
340       inputSections.push_back(&sec);
341     };
342 
343     if (!part.name.empty()) {
344       part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>();
345       part.elfHeader->name = part.name;
346       add(*part.elfHeader);
347 
348       part.programHeaders =
349           std::make_unique<PartitionProgramHeadersSection<ELFT>>();
350       add(*part.programHeaders);
351     }
352 
353     if (config->buildId != BuildIdKind::None) {
354       part.buildId = std::make_unique<BuildIdSection>();
355       add(*part.buildId);
356     }
357 
358     part.dynStrTab = std::make_unique<StringTableSection>(".dynstr", true);
359     part.dynSymTab =
360         std::make_unique<SymbolTableSection<ELFT>>(*part.dynStrTab);
361     part.dynamic = std::make_unique<DynamicSection<ELFT>>();
362     if (config->androidPackDynRelocs)
363       part.relaDyn =
364           std::make_unique<AndroidPackedRelocationSection<ELFT>>(relaDynName);
365     else
366       part.relaDyn = std::make_unique<RelocationSection<ELFT>>(
367           relaDynName, config->zCombreloc);
368 
369     if (config->hasDynSymTab) {
370       add(*part.dynSymTab);
371 
372       part.verSym = std::make_unique<VersionTableSection>();
373       add(*part.verSym);
374 
375       if (!namedVersionDefs().empty()) {
376         part.verDef = std::make_unique<VersionDefinitionSection>();
377         add(*part.verDef);
378       }
379 
380       part.verNeed = std::make_unique<VersionNeedSection<ELFT>>();
381       add(*part.verNeed);
382 
383       if (config->gnuHash) {
384         part.gnuHashTab = std::make_unique<GnuHashTableSection>();
385         add(*part.gnuHashTab);
386       }
387 
388       if (config->sysvHash) {
389         part.hashTab = std::make_unique<HashTableSection>();
390         add(*part.hashTab);
391       }
392 
393       add(*part.dynamic);
394       add(*part.dynStrTab);
395       add(*part.relaDyn);
396     }
397 
398     if (config->relrPackDynRelocs) {
399       part.relrDyn = std::make_unique<RelrSection<ELFT>>();
400       add(*part.relrDyn);
401     }
402 
403     if (!config->relocatable) {
404       if (config->ehFrameHdr) {
405         part.ehFrameHdr = std::make_unique<EhFrameHeader>();
406         add(*part.ehFrameHdr);
407       }
408       part.ehFrame = std::make_unique<EhFrameSection>();
409       add(*part.ehFrame);
410     }
411 
412     if (config->emachine == EM_ARM && !config->relocatable) {
413       // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx
414       // InputSections.
415       part.armExidx = std::make_unique<ARMExidxSyntheticSection>();
416       add(*part.armExidx);
417     }
418   }
419 
420   if (partitions.size() != 1) {
421     // Create the partition end marker. This needs to be in partition number 255
422     // so that it is sorted after all other partitions. It also has other
423     // special handling (see createPhdrs() and combineEhSections()).
424     in.partEnd =
425         std::make_unique<BssSection>(".part.end", config->maxPageSize, 1);
426     in.partEnd->partition = 255;
427     add(*in.partEnd);
428 
429     in.partIndex = std::make_unique<PartitionIndexSection>();
430     addOptionalRegular("__part_index_begin", in.partIndex.get(), 0);
431     addOptionalRegular("__part_index_end", in.partIndex.get(),
432                        in.partIndex->getSize());
433     add(*in.partIndex);
434   }
435 
436   // Add .got. MIPS' .got is so different from the other archs,
437   // it has its own class.
438   if (config->emachine == EM_MIPS) {
439     in.mipsGot = std::make_unique<MipsGotSection>();
440     add(*in.mipsGot);
441   } else {
442     in.got = std::make_unique<GotSection>();
443     add(*in.got);
444   }
445 
446   if (config->emachine == EM_PPC) {
447     in.ppc32Got2 = std::make_unique<PPC32Got2Section>();
448     add(*in.ppc32Got2);
449   }
450 
451   if (config->emachine == EM_PPC64) {
452     in.ppc64LongBranchTarget = std::make_unique<PPC64LongBranchTargetSection>();
453     add(*in.ppc64LongBranchTarget);
454   }
455 
456   in.gotPlt = std::make_unique<GotPltSection>();
457   add(*in.gotPlt);
458   in.igotPlt = std::make_unique<IgotPltSection>();
459   add(*in.igotPlt);
460 
461   // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
462   // it as a relocation and ensure the referenced section is created.
463   if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
464     if (target->gotBaseSymInGotPlt)
465       in.gotPlt->hasGotPltOffRel = true;
466     else
467       in.got->hasGotOffRel = true;
468   }
469 
470   if (config->gdbIndex)
471     add(*GdbIndexSection::create<ELFT>());
472 
473   // We always need to add rel[a].plt to output if it has entries.
474   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
475   in.relaPlt = std::make_unique<RelocationSection<ELFT>>(
476       config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false);
477   add(*in.relaPlt);
478 
479   // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
480   // relocations are processed last by the dynamic loader. We cannot place the
481   // iplt section in .rel.dyn when Android relocation packing is enabled because
482   // that would cause a section type mismatch. However, because the Android
483   // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
484   // behaviour by placing the iplt section in .rel.plt.
485   in.relaIplt = std::make_unique<RelocationSection<ELFT>>(
486       config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
487       /*sort=*/false);
488   add(*in.relaIplt);
489 
490   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
491       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
492     in.ibtPlt = std::make_unique<IBTPltSection>();
493     add(*in.ibtPlt);
494   }
495 
496   if (config->emachine == EM_PPC)
497     in.plt = std::make_unique<PPC32GlinkSection>();
498   else
499     in.plt = std::make_unique<PltSection>();
500   add(*in.plt);
501   in.iplt = std::make_unique<IpltSection>();
502   add(*in.iplt);
503 
504   if (config->andFeatures)
505     add(*make<GnuPropertySection>());
506 
507   // .note.GNU-stack is always added when we are creating a re-linkable
508   // object file. Other linkers are using the presence of this marker
509   // section to control the executable-ness of the stack area, but that
510   // is irrelevant these days. Stack area should always be non-executable
511   // by default. So we emit this section unconditionally.
512   if (config->relocatable)
513     add(*make<GnuStackSection>());
514 
515   if (in.symTab)
516     add(*in.symTab);
517   if (in.symTabShndx)
518     add(*in.symTabShndx);
519   add(*in.shStrTab);
520   if (in.strTab)
521     add(*in.strTab);
522 }
523 
524 // The main function of the writer.
525 template <class ELFT> void Writer<ELFT>::run() {
526   copyLocalSymbols();
527 
528   if (config->copyRelocs)
529     addSectionSymbols();
530 
531   // Now that we have a complete set of output sections. This function
532   // completes section contents. For example, we need to add strings
533   // to the string table, and add entries to .got and .plt.
534   // finalizeSections does that.
535   finalizeSections();
536   checkExecuteOnly();
537 
538   // If --compressed-debug-sections is specified, compress .debug_* sections.
539   // Do it right now because it changes the size of output sections.
540   for (OutputSection *sec : outputSections)
541     sec->maybeCompress<ELFT>();
542 
543   if (script->hasSectionsCommand)
544     script->allocateHeaders(mainPart->phdrs);
545 
546   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
547   // 0 sized region. This has to be done late since only after assignAddresses
548   // we know the size of the sections.
549   for (Partition &part : partitions)
550     removeEmptyPTLoad(part.phdrs);
551 
552   if (!config->oFormatBinary)
553     assignFileOffsets();
554   else
555     assignFileOffsetsBinary();
556 
557   for (Partition &part : partitions)
558     setPhdrs(part);
559 
560 
561   // Handle --print-map(-M)/--Map, --why-extract=, --cref and
562   // --print-archive-stats=. Dump them before checkSections() because the files
563   // may be useful in case checkSections() or openFile() fails, for example, due
564   // to an erroneous file size.
565   writeMapAndCref();
566   writeWhyExtract();
567   writeArchiveStats();
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_or_null<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->data().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(
1832         Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
1833                 /*value=*/0, /*size=*/0, mainPart->dynamic.get()});
1834 
1835   // Define __rel[a]_iplt_{start,end} symbols if needed.
1836   addRelIpltSymbols();
1837 
1838   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1839   // should only be defined in an executable. If .sdata does not exist, its
1840   // value/section does not matter but it has to be relative, so set its
1841   // st_shndx arbitrarily to 1 (Out::elfHeader).
1842   if (config->emachine == EM_RISCV && !config->shared) {
1843     OutputSection *sec = findSection(".sdata");
1844     ElfSym::riscvGlobalPointer =
1845         addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader,
1846                            0x800, STV_DEFAULT);
1847   }
1848 
1849   if (config->emachine == EM_386 || config->emachine == EM_X86_64) {
1850     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1851     // way that:
1852     //
1853     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1854     // computes 0.
1855     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1856     // the TLS block).
1857     //
1858     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1859     // an absolute symbol of zero. This is different from GNU linkers which
1860     // define _TLS_MODULE_BASE_ relative to the first TLS section.
1861     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1862     if (s && s->isUndefined()) {
1863       s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
1864                          STT_TLS, /*value=*/0, 0,
1865                          /*section=*/nullptr});
1866       ElfSym::tlsModuleBase = cast<Defined>(s);
1867     }
1868   }
1869 
1870   {
1871     llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1872     // This responsible for splitting up .eh_frame section into
1873     // pieces. The relocation scan uses those pieces, so this has to be
1874     // earlier.
1875     for (Partition &part : partitions)
1876       finalizeSynthetic(part.ehFrame.get());
1877   }
1878 
1879   if (config->hasDynSymTab) {
1880     parallelForEach(symtab->symbols(), [](Symbol *sym) {
1881       sym->isPreemptible = computeIsPreemptible(*sym);
1882     });
1883   }
1884 
1885   // Change values of linker-script-defined symbols from placeholders (assigned
1886   // by declareSymbols) to actual definitions.
1887   script->processSymbolAssignments();
1888 
1889   {
1890     llvm::TimeTraceScope timeScope("Scan relocations");
1891     // Scan relocations. This must be done after every symbol is declared so
1892     // that we can correctly decide if a dynamic relocation is needed. This is
1893     // called after processSymbolAssignments() because it needs to know whether
1894     // a linker-script-defined symbol is absolute.
1895     ppc64noTocRelax.clear();
1896     if (!config->relocatable) {
1897       // Scan all relocations. Each relocation goes through a series of tests to
1898       // determine if it needs special treatment, such as creating GOT, PLT,
1899       // copy relocations, etc. Note that relocations for non-alloc sections are
1900       // directly processed by InputSection::relocateNonAlloc.
1901       for (InputSectionBase *sec : inputSections)
1902         if (sec->isLive() && isa<InputSection>(sec) && (sec->flags & SHF_ALLOC))
1903           scanRelocations<ELFT>(*sec);
1904       for (Partition &part : partitions) {
1905         for (EhInputSection *sec : part.ehFrame->sections)
1906           scanRelocations<ELFT>(*sec);
1907         if (part.armExidx && part.armExidx->isLive())
1908           for (InputSection *sec : part.armExidx->exidxSections)
1909             scanRelocations<ELFT>(*sec);
1910       }
1911 
1912       reportUndefinedSymbols();
1913       postScanRelocations();
1914     }
1915   }
1916 
1917   if (in.plt && in.plt->isNeeded())
1918     in.plt->addSymbols();
1919   if (in.iplt && in.iplt->isNeeded())
1920     in.iplt->addSymbols();
1921 
1922   if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1923     auto diagnose =
1924         config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
1925             ? errorOrWarn
1926             : warn;
1927     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1928     // entries are seen. These cases would otherwise lead to runtime errors
1929     // reported by the dynamic linker.
1930     //
1931     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1932     // catch more cases. That is too much for us. Our approach resembles the one
1933     // used in ld.gold, achieves a good balance to be useful but not too smart.
1934     for (SharedFile *file : sharedFiles) {
1935       bool allNeededIsKnown =
1936           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1937             return symtab->soNames.count(CachedHashStringRef(needed));
1938           });
1939       if (!allNeededIsKnown)
1940         continue;
1941       for (Symbol *sym : file->requiredSymbols)
1942         if (sym->isUndefined() && !sym->isWeak())
1943           diagnose(toString(file) + ": undefined reference to " +
1944                    toString(*sym) + " [--no-allow-shlib-undefined]");
1945     }
1946   }
1947 
1948   {
1949     llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1950     // Now that we have defined all possible global symbols including linker-
1951     // synthesized ones. Visit all symbols to give the finishing touches.
1952     for (Symbol *sym : symtab->symbols()) {
1953       if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))
1954         continue;
1955       if (!config->relocatable)
1956         sym->binding = sym->computeBinding();
1957       if (in.symTab)
1958         in.symTab->addSymbol(sym);
1959 
1960       if (sym->includeInDynsym()) {
1961         partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1962         if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
1963           if (file->isNeeded && !sym->isUndefined())
1964             addVerneed(sym);
1965       }
1966     }
1967 
1968     // We also need to scan the dynamic relocation tables of the other
1969     // partitions and add any referenced symbols to the partition's dynsym.
1970     for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
1971       DenseSet<Symbol *> syms;
1972       for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1973         syms.insert(e.sym);
1974       for (DynamicReloc &reloc : part.relaDyn->relocs)
1975         if (reloc.sym && reloc.needsDynSymIndex() &&
1976             syms.insert(reloc.sym).second)
1977           part.dynSymTab->addSymbol(reloc.sym);
1978     }
1979   }
1980 
1981   if (in.mipsGot)
1982     in.mipsGot->build();
1983 
1984   removeUnusedSyntheticSections();
1985   script->diagnoseOrphanHandling();
1986 
1987   sortSections();
1988 
1989   // Create a list of OutputSections, assign sectionIndex, and populate
1990   // in.shStrTab.
1991   for (SectionCommand *cmd : script->sectionCommands)
1992     if (auto *osec = dyn_cast<OutputSection>(cmd)) {
1993       outputSections.push_back(osec);
1994       osec->sectionIndex = outputSections.size();
1995       osec->shName = in.shStrTab->addString(osec->name);
1996     }
1997 
1998   // Prefer command line supplied address over other constraints.
1999   for (OutputSection *sec : outputSections) {
2000     auto i = config->sectionStartMap.find(sec->name);
2001     if (i != config->sectionStartMap.end())
2002       sec->addrExpr = [=] { return i->second; };
2003   }
2004 
2005   // With the outputSections available check for GDPLT relocations
2006   // and add __tls_get_addr symbol if needed.
2007   if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
2008     Symbol *sym = symtab->addSymbol(Undefined{
2009         nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2010     sym->isPreemptible = true;
2011     partitions[0].dynSymTab->addSymbol(sym);
2012   }
2013 
2014   // This is a bit of a hack. A value of 0 means undef, so we set it
2015   // to 1 to make __ehdr_start defined. The section number is not
2016   // particularly relevant.
2017   Out::elfHeader->sectionIndex = 1;
2018   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2019 
2020   // Binary and relocatable output does not have PHDRS.
2021   // The headers have to be created before finalize as that can influence the
2022   // image base and the dynamic section on mips includes the image base.
2023   if (!config->relocatable && !config->oFormatBinary) {
2024     for (Partition &part : partitions) {
2025       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2026                                               : createPhdrs(part);
2027       if (config->emachine == EM_ARM) {
2028         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2029         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2030       }
2031       if (config->emachine == EM_MIPS) {
2032         // Add separate segments for MIPS-specific sections.
2033         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2034         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2035         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2036       }
2037     }
2038     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2039 
2040     // Find the TLS segment. This happens before the section layout loop so that
2041     // Android relocation packing can look up TLS symbol addresses. We only need
2042     // to care about the main partition here because all TLS symbols were moved
2043     // to the main partition (see MarkLive.cpp).
2044     for (PhdrEntry *p : mainPart->phdrs)
2045       if (p->p_type == PT_TLS)
2046         Out::tlsPhdr = p;
2047   }
2048 
2049   // Some symbols are defined in term of program headers. Now that we
2050   // have the headers, we can find out which sections they point to.
2051   setReservedSymbolSections();
2052 
2053   {
2054     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2055 
2056     finalizeSynthetic(in.bss.get());
2057     finalizeSynthetic(in.bssRelRo.get());
2058     finalizeSynthetic(in.symTabShndx.get());
2059     finalizeSynthetic(in.shStrTab.get());
2060     finalizeSynthetic(in.strTab.get());
2061     finalizeSynthetic(in.got.get());
2062     finalizeSynthetic(in.mipsGot.get());
2063     finalizeSynthetic(in.igotPlt.get());
2064     finalizeSynthetic(in.gotPlt.get());
2065     finalizeSynthetic(in.relaIplt.get());
2066     finalizeSynthetic(in.relaPlt.get());
2067     finalizeSynthetic(in.plt.get());
2068     finalizeSynthetic(in.iplt.get());
2069     finalizeSynthetic(in.ppc32Got2.get());
2070     finalizeSynthetic(in.partIndex.get());
2071 
2072     // Dynamic section must be the last one in this list and dynamic
2073     // symbol table section (dynSymTab) must be the first one.
2074     for (Partition &part : partitions) {
2075       if (part.relaDyn) {
2076         // Compute DT_RELACOUNT to be used by part.dynamic.
2077         part.relaDyn->partitionRels();
2078         finalizeSynthetic(part.relaDyn.get());
2079       }
2080 
2081       finalizeSynthetic(part.dynSymTab.get());
2082       finalizeSynthetic(part.gnuHashTab.get());
2083       finalizeSynthetic(part.hashTab.get());
2084       finalizeSynthetic(part.verDef.get());
2085       finalizeSynthetic(part.relrDyn.get());
2086       finalizeSynthetic(part.ehFrameHdr.get());
2087       finalizeSynthetic(part.verSym.get());
2088       finalizeSynthetic(part.verNeed.get());
2089       finalizeSynthetic(part.dynamic.get());
2090     }
2091   }
2092 
2093   if (!script->hasSectionsCommand && !config->relocatable)
2094     fixSectionAlignments();
2095 
2096   // This is used to:
2097   // 1) Create "thunks":
2098   //    Jump instructions in many ISAs have small displacements, and therefore
2099   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
2100   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
2101   //    responsibility to create and insert small pieces of code between
2102   //    sections to extend the ranges if jump targets are out of range. Such
2103   //    code pieces are called "thunks".
2104   //
2105   //    We add thunks at this stage. We couldn't do this before this point
2106   //    because this is the earliest point where we know sizes of sections and
2107   //    their layouts (that are needed to determine if jump targets are in
2108   //    range).
2109   //
2110   // 2) Update the sections. We need to generate content that depends on the
2111   //    address of InputSections. For example, MIPS GOT section content or
2112   //    android packed relocations sections content.
2113   //
2114   // 3) Assign the final values for the linker script symbols. Linker scripts
2115   //    sometimes using forward symbol declarations. We want to set the correct
2116   //    values. They also might change after adding the thunks.
2117   finalizeAddressDependentContent();
2118 
2119   // All information needed for OutputSection part of Map file is available.
2120   if (errorCount())
2121     return;
2122 
2123   {
2124     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2125     // finalizeAddressDependentContent may have added local symbols to the
2126     // static symbol table.
2127     finalizeSynthetic(in.symTab.get());
2128     finalizeSynthetic(in.ppc64LongBranchTarget.get());
2129   }
2130 
2131   // Relaxation to delete inter-basic block jumps created by basic block
2132   // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2133   // can relax jump instructions based on symbol offset.
2134   if (config->optimizeBBJumps)
2135     optimizeBasicBlockJumps();
2136 
2137   // Fill other section headers. The dynamic table is finalized
2138   // at the end because some tags like RELSZ depend on result
2139   // of finalizing other sections.
2140   for (OutputSection *sec : outputSections)
2141     sec->finalize();
2142 }
2143 
2144 // Ensure data sections are not mixed with executable sections when
2145 // --execute-only is used. --execute-only make pages executable but not
2146 // readable.
2147 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2148   if (!config->executeOnly)
2149     return;
2150 
2151   for (OutputSection *osec : outputSections)
2152     if (osec->flags & SHF_EXECINSTR)
2153       for (InputSection *isec : getInputSections(*osec))
2154         if (!(isec->flags & SHF_EXECINSTR))
2155           error("cannot place " + toString(isec) + " into " +
2156                 toString(osec->name) +
2157                 ": --execute-only does not support intermingling data and code");
2158 }
2159 
2160 // The linker is expected to define SECNAME_start and SECNAME_end
2161 // symbols for a few sections. This function defines them.
2162 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2163   // If a section does not exist, there's ambiguity as to how we
2164   // define _start and _end symbols for an init/fini section. Since
2165   // the loader assume that the symbols are always defined, we need to
2166   // always define them. But what value? The loader iterates over all
2167   // pointers between _start and _end to run global ctors/dtors, so if
2168   // the section is empty, their symbol values don't actually matter
2169   // as long as _start and _end point to the same location.
2170   //
2171   // That said, we don't want to set the symbols to 0 (which is
2172   // probably the simplest value) because that could cause some
2173   // program to fail to link due to relocation overflow, if their
2174   // program text is above 2 GiB. We use the address of the .text
2175   // section instead to prevent that failure.
2176   //
2177   // In rare situations, the .text section may not exist. If that's the
2178   // case, use the image base address as a last resort.
2179   OutputSection *Default = findSection(".text");
2180   if (!Default)
2181     Default = Out::elfHeader;
2182 
2183   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2184     if (os && !script->isDiscarded(os)) {
2185       addOptionalRegular(start, os, 0);
2186       addOptionalRegular(end, os, -1);
2187     } else {
2188       addOptionalRegular(start, Default, 0);
2189       addOptionalRegular(end, Default, 0);
2190     }
2191   };
2192 
2193   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2194   define("__init_array_start", "__init_array_end", Out::initArray);
2195   define("__fini_array_start", "__fini_array_end", Out::finiArray);
2196 
2197   if (OutputSection *sec = findSection(".ARM.exidx"))
2198     define("__exidx_start", "__exidx_end", sec);
2199 }
2200 
2201 // If a section name is valid as a C identifier (which is rare because of
2202 // the leading '.'), linkers are expected to define __start_<secname> and
2203 // __stop_<secname> symbols. They are at beginning and end of the section,
2204 // respectively. This is not requested by the ELF standard, but GNU ld and
2205 // gold provide the feature, and used by many programs.
2206 template <class ELFT>
2207 void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
2208   StringRef s = sec->name;
2209   if (!isValidCIdentifier(s))
2210     return;
2211   addOptionalRegular(saver().save("__start_" + s), sec, 0,
2212                      config->zStartStopVisibility);
2213   addOptionalRegular(saver().save("__stop_" + s), sec, -1,
2214                      config->zStartStopVisibility);
2215 }
2216 
2217 static bool needsPtLoad(OutputSection *sec) {
2218   if (!(sec->flags & SHF_ALLOC))
2219     return false;
2220 
2221   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2222   // responsible for allocating space for them, not the PT_LOAD that
2223   // contains the TLS initialization image.
2224   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2225     return false;
2226   return true;
2227 }
2228 
2229 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2230 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2231 // RW. This means that there is no alignment in the RO to RX transition and we
2232 // cannot create a PT_LOAD there.
2233 static uint64_t computeFlags(uint64_t flags) {
2234   if (config->omagic)
2235     return PF_R | PF_W | PF_X;
2236   if (config->executeOnly && (flags & PF_X))
2237     return flags & ~PF_R;
2238   if (config->singleRoRx && !(flags & PF_W))
2239     return flags | PF_X;
2240   return flags;
2241 }
2242 
2243 // Decide which program headers to create and which sections to include in each
2244 // one.
2245 template <class ELFT>
2246 SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {
2247   SmallVector<PhdrEntry *, 0> ret;
2248   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2249     ret.push_back(make<PhdrEntry>(type, flags));
2250     return ret.back();
2251   };
2252 
2253   unsigned partNo = part.getNumber();
2254   bool isMain = partNo == 1;
2255 
2256   // Add the first PT_LOAD segment for regular output sections.
2257   uint64_t flags = computeFlags(PF_R);
2258   PhdrEntry *load = nullptr;
2259 
2260   // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2261   // PT_LOAD.
2262   if (!config->nmagic && !config->omagic) {
2263     // The first phdr entry is PT_PHDR which describes the program header
2264     // itself.
2265     if (isMain)
2266       addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2267     else
2268       addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2269 
2270     // PT_INTERP must be the second entry if exists.
2271     if (OutputSection *cmd = findSection(".interp", partNo))
2272       addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2273 
2274     // Add the headers. We will remove them if they don't fit.
2275     // In the other partitions the headers are ordinary sections, so they don't
2276     // need to be added here.
2277     if (isMain) {
2278       load = addHdr(PT_LOAD, flags);
2279       load->add(Out::elfHeader);
2280       load->add(Out::programHeaders);
2281     }
2282   }
2283 
2284   // PT_GNU_RELRO includes all sections that should be marked as
2285   // read-only by dynamic linker after processing relocations.
2286   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2287   // an error message if more than one PT_GNU_RELRO PHDR is required.
2288   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2289   bool inRelroPhdr = false;
2290   OutputSection *relroEnd = nullptr;
2291   for (OutputSection *sec : outputSections) {
2292     if (sec->partition != partNo || !needsPtLoad(sec))
2293       continue;
2294     if (isRelroSection(sec)) {
2295       inRelroPhdr = true;
2296       if (!relroEnd)
2297         relRo->add(sec);
2298       else
2299         error("section: " + sec->name + " is not contiguous with other relro" +
2300               " sections");
2301     } else if (inRelroPhdr) {
2302       inRelroPhdr = false;
2303       relroEnd = sec;
2304     }
2305   }
2306 
2307   for (OutputSection *sec : outputSections) {
2308     if (!needsPtLoad(sec))
2309       continue;
2310 
2311     // Normally, sections in partitions other than the current partition are
2312     // ignored. But partition number 255 is a special case: it contains the
2313     // partition end marker (.part.end). It needs to be added to the main
2314     // partition so that a segment is created for it in the main partition,
2315     // which will cause the dynamic loader to reserve space for the other
2316     // partitions.
2317     if (sec->partition != partNo) {
2318       if (isMain && sec->partition == 255)
2319         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2320       continue;
2321     }
2322 
2323     // Segments are contiguous memory regions that has the same attributes
2324     // (e.g. executable or writable). There is one phdr for each segment.
2325     // Therefore, we need to create a new phdr when the next section has
2326     // different flags or is loaded at a discontiguous address or memory
2327     // region using AT or AT> linker script command, respectively. At the same
2328     // time, we don't want to create a separate load segment for the headers,
2329     // even if the first output section has an AT or AT> attribute.
2330     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2331     bool sameLMARegion =
2332         load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2333     if (!(load && newFlags == flags && sec != relroEnd &&
2334           sec->memRegion == load->firstSec->memRegion &&
2335           (sameLMARegion || load->lastSec == Out::programHeaders))) {
2336       load = addHdr(PT_LOAD, newFlags);
2337       flags = newFlags;
2338     }
2339 
2340     load->add(sec);
2341   }
2342 
2343   // Add a TLS segment if any.
2344   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2345   for (OutputSection *sec : outputSections)
2346     if (sec->partition == partNo && sec->flags & SHF_TLS)
2347       tlsHdr->add(sec);
2348   if (tlsHdr->firstSec)
2349     ret.push_back(tlsHdr);
2350 
2351   // Add an entry for .dynamic.
2352   if (OutputSection *sec = part.dynamic->getParent())
2353     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2354 
2355   if (relRo->firstSec)
2356     ret.push_back(relRo);
2357 
2358   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2359   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2360       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2361     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2362         ->add(part.ehFrameHdr->getParent());
2363 
2364   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2365   // the dynamic linker fill the segment with random data.
2366   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2367     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2368 
2369   if (config->zGnustack != GnuStackKind::None) {
2370     // PT_GNU_STACK is a special section to tell the loader to make the
2371     // pages for the stack non-executable. If you really want an executable
2372     // stack, you can pass -z execstack, but that's not recommended for
2373     // security reasons.
2374     unsigned perm = PF_R | PF_W;
2375     if (config->zGnustack == GnuStackKind::Exec)
2376       perm |= PF_X;
2377     addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2378   }
2379 
2380   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2381   // is expected to perform W^X violations, such as calling mprotect(2) or
2382   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2383   // OpenBSD.
2384   if (config->zWxneeded)
2385     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2386 
2387   if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2388     addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2389 
2390   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2391   // same alignment.
2392   PhdrEntry *note = nullptr;
2393   for (OutputSection *sec : outputSections) {
2394     if (sec->partition != partNo)
2395       continue;
2396     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2397       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2398         note = addHdr(PT_NOTE, PF_R);
2399       note->add(sec);
2400     } else {
2401       note = nullptr;
2402     }
2403   }
2404   return ret;
2405 }
2406 
2407 template <class ELFT>
2408 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2409                                      unsigned pType, unsigned pFlags) {
2410   unsigned partNo = part.getNumber();
2411   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2412     return cmd->partition == partNo && cmd->type == shType;
2413   });
2414   if (i == outputSections.end())
2415     return;
2416 
2417   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2418   entry->add(*i);
2419   part.phdrs.push_back(entry);
2420 }
2421 
2422 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2423 // This is achieved by assigning an alignment expression to addrExpr of each
2424 // such section.
2425 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2426   const PhdrEntry *prev;
2427   auto pageAlign = [&](const PhdrEntry *p) {
2428     OutputSection *cmd = p->firstSec;
2429     if (!cmd)
2430       return;
2431     cmd->alignExpr = [align = cmd->alignment]() { return align; };
2432     if (!cmd->addrExpr) {
2433       // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2434       // padding in the file contents.
2435       //
2436       // When -z separate-code is used we must not have any overlap in pages
2437       // between an executable segment and a non-executable segment. We align to
2438       // the next maximum page size boundary on transitions between executable
2439       // and non-executable segments.
2440       //
2441       // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2442       // sections will be extracted to a separate file. Align to the next
2443       // maximum page size boundary so that we can find the ELF header at the
2444       // start. We cannot benefit from overlapping p_offset ranges with the
2445       // previous segment anyway.
2446       if (config->zSeparate == SeparateSegmentKind::Loadable ||
2447           (config->zSeparate == SeparateSegmentKind::Code && prev &&
2448            (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2449           cmd->type == SHT_LLVM_PART_EHDR)
2450         cmd->addrExpr = [] {
2451           return alignTo(script->getDot(), config->maxPageSize);
2452         };
2453       // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2454       // it must be the RW. Align to p_align(PT_TLS) to make sure
2455       // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2456       // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2457       // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2458       // be congruent to 0 modulo p_align(PT_TLS).
2459       //
2460       // Technically this is not required, but as of 2019, some dynamic loaders
2461       // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2462       // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2463       // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2464       // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2465       // blocks correctly. We need to keep the workaround for a while.
2466       else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2467         cmd->addrExpr = [] {
2468           return alignTo(script->getDot(), config->maxPageSize) +
2469                  alignTo(script->getDot() % config->maxPageSize,
2470                          Out::tlsPhdr->p_align);
2471         };
2472       else
2473         cmd->addrExpr = [] {
2474           return alignTo(script->getDot(), config->maxPageSize) +
2475                  script->getDot() % config->maxPageSize;
2476         };
2477     }
2478   };
2479 
2480   for (Partition &part : partitions) {
2481     prev = nullptr;
2482     for (const PhdrEntry *p : part.phdrs)
2483       if (p->p_type == PT_LOAD && p->firstSec) {
2484         pageAlign(p);
2485         prev = p;
2486       }
2487   }
2488 }
2489 
2490 // Compute an in-file position for a given section. The file offset must be the
2491 // same with its virtual address modulo the page size, so that the loader can
2492 // load executables without any address adjustment.
2493 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2494   // The first section in a PT_LOAD has to have congruent offset and address
2495   // modulo the maximum page size.
2496   if (os->ptLoad && os->ptLoad->firstSec == os)
2497     return alignTo(off, os->ptLoad->p_align, os->addr);
2498 
2499   // File offsets are not significant for .bss sections other than the first one
2500   // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2501   // increasing rather than setting to zero.
2502   if (os->type == SHT_NOBITS &&
2503       (!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
2504      return off;
2505 
2506   // If the section is not in a PT_LOAD, we just have to align it.
2507   if (!os->ptLoad)
2508     return alignTo(off, os->alignment);
2509 
2510   // If two sections share the same PT_LOAD the file offset is calculated
2511   // using this formula: Off2 = Off1 + (VA2 - VA1).
2512   OutputSection *first = os->ptLoad->firstSec;
2513   return first->offset + os->addr - first->addr;
2514 }
2515 
2516 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2517   // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2518   auto needsOffset = [](OutputSection &sec) {
2519     return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2520   };
2521   uint64_t minAddr = UINT64_MAX;
2522   for (OutputSection *sec : outputSections)
2523     if (needsOffset(*sec)) {
2524       sec->offset = sec->getLMA();
2525       minAddr = std::min(minAddr, sec->offset);
2526     }
2527 
2528   // Sections are laid out at LMA minus minAddr.
2529   fileSize = 0;
2530   for (OutputSection *sec : outputSections)
2531     if (needsOffset(*sec)) {
2532       sec->offset -= minAddr;
2533       fileSize = std::max(fileSize, sec->offset + sec->size);
2534     }
2535 }
2536 
2537 static std::string rangeToString(uint64_t addr, uint64_t len) {
2538   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2539 }
2540 
2541 // Assign file offsets to output sections.
2542 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2543   Out::programHeaders->offset = Out::elfHeader->size;
2544   uint64_t off = Out::elfHeader->size + Out::programHeaders->size;
2545 
2546   PhdrEntry *lastRX = nullptr;
2547   for (Partition &part : partitions)
2548     for (PhdrEntry *p : part.phdrs)
2549       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2550         lastRX = p;
2551 
2552   // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2553   // will not occupy file offsets contained by a PT_LOAD.
2554   for (OutputSection *sec : outputSections) {
2555     if (!(sec->flags & SHF_ALLOC))
2556       continue;
2557     off = computeFileOffset(sec, off);
2558     sec->offset = off;
2559     if (sec->type != SHT_NOBITS)
2560       off += sec->size;
2561 
2562     // If this is a last section of the last executable segment and that
2563     // segment is the last loadable segment, align the offset of the
2564     // following section to avoid loading non-segments parts of the file.
2565     if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2566         lastRX->lastSec == sec)
2567       off = alignTo(off, config->maxPageSize);
2568   }
2569   for (OutputSection *osec : outputSections)
2570     if (!(osec->flags & SHF_ALLOC)) {
2571       osec->offset = alignTo(off, osec->alignment);
2572       off = osec->offset + osec->size;
2573     }
2574 
2575   sectionHeaderOff = alignTo(off, config->wordsize);
2576   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2577 
2578   // Our logic assumes that sections have rising VA within the same segment.
2579   // With use of linker scripts it is possible to violate this rule and get file
2580   // offset overlaps or overflows. That should never happen with a valid script
2581   // which does not move the location counter backwards and usually scripts do
2582   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2583   // kernel, which control segment distribution explicitly and move the counter
2584   // backwards, so we have to allow doing that to support linking them. We
2585   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2586   // we want to prevent file size overflows because it would crash the linker.
2587   for (OutputSection *sec : outputSections) {
2588     if (sec->type == SHT_NOBITS)
2589       continue;
2590     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2591       error("unable to place section " + sec->name + " at file offset " +
2592             rangeToString(sec->offset, sec->size) +
2593             "; check your linker script for overflows");
2594   }
2595 }
2596 
2597 // Finalize the program headers. We call this function after we assign
2598 // file offsets and VAs to all sections.
2599 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2600   for (PhdrEntry *p : part.phdrs) {
2601     OutputSection *first = p->firstSec;
2602     OutputSection *last = p->lastSec;
2603 
2604     if (first) {
2605       p->p_filesz = last->offset - first->offset;
2606       if (last->type != SHT_NOBITS)
2607         p->p_filesz += last->size;
2608 
2609       p->p_memsz = last->addr + last->size - first->addr;
2610       p->p_offset = first->offset;
2611       p->p_vaddr = first->addr;
2612 
2613       // File offsets in partitions other than the main partition are relative
2614       // to the offset of the ELF headers. Perform that adjustment now.
2615       if (part.elfHeader)
2616         p->p_offset -= part.elfHeader->getParent()->offset;
2617 
2618       if (!p->hasLMA)
2619         p->p_paddr = first->getLMA();
2620     }
2621 
2622     if (p->p_type == PT_GNU_RELRO) {
2623       p->p_align = 1;
2624       // musl/glibc ld.so rounds the size down, so we need to round up
2625       // to protect the last page. This is a no-op on FreeBSD which always
2626       // rounds up.
2627       p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) -
2628                    p->p_offset;
2629     }
2630   }
2631 }
2632 
2633 // A helper struct for checkSectionOverlap.
2634 namespace {
2635 struct SectionOffset {
2636   OutputSection *sec;
2637   uint64_t offset;
2638 };
2639 } // namespace
2640 
2641 // Check whether sections overlap for a specific address range (file offsets,
2642 // load and virtual addresses).
2643 static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2644                          bool isVirtualAddr) {
2645   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2646     return a.offset < b.offset;
2647   });
2648 
2649   // Finding overlap is easy given a vector is sorted by start position.
2650   // If an element starts before the end of the previous element, they overlap.
2651   for (size_t i = 1, end = sections.size(); i < end; ++i) {
2652     SectionOffset a = sections[i - 1];
2653     SectionOffset b = sections[i];
2654     if (b.offset >= a.offset + a.sec->size)
2655       continue;
2656 
2657     // If both sections are in OVERLAY we allow the overlapping of virtual
2658     // addresses, because it is what OVERLAY was designed for.
2659     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2660       continue;
2661 
2662     errorOrWarn("section " + a.sec->name + " " + name +
2663                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2664                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2665                 b.sec->name + " range is " +
2666                 rangeToString(b.offset, b.sec->size));
2667   }
2668 }
2669 
2670 // Check for overlapping sections and address overflows.
2671 //
2672 // In this function we check that none of the output sections have overlapping
2673 // file offsets. For SHF_ALLOC sections we also check that the load address
2674 // ranges and the virtual address ranges don't overlap
2675 template <class ELFT> void Writer<ELFT>::checkSections() {
2676   // First, check that section's VAs fit in available address space for target.
2677   for (OutputSection *os : outputSections)
2678     if ((os->addr + os->size < os->addr) ||
2679         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2680       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2681                   " of size 0x" + utohexstr(os->size) +
2682                   " exceeds available address space");
2683 
2684   // Check for overlapping file offsets. In this case we need to skip any
2685   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2686   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2687   // binary is specified only add SHF_ALLOC sections are added to the output
2688   // file so we skip any non-allocated sections in that case.
2689   std::vector<SectionOffset> fileOffs;
2690   for (OutputSection *sec : outputSections)
2691     if (sec->size > 0 && sec->type != SHT_NOBITS &&
2692         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2693       fileOffs.push_back({sec, sec->offset});
2694   checkOverlap("file", fileOffs, false);
2695 
2696   // When linking with -r there is no need to check for overlapping virtual/load
2697   // addresses since those addresses will only be assigned when the final
2698   // executable/shared object is created.
2699   if (config->relocatable)
2700     return;
2701 
2702   // Checking for overlapping virtual and load addresses only needs to take
2703   // into account SHF_ALLOC sections since others will not be loaded.
2704   // Furthermore, we also need to skip SHF_TLS sections since these will be
2705   // mapped to other addresses at runtime and can therefore have overlapping
2706   // ranges in the file.
2707   std::vector<SectionOffset> vmas;
2708   for (OutputSection *sec : outputSections)
2709     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2710       vmas.push_back({sec, sec->addr});
2711   checkOverlap("virtual address", vmas, true);
2712 
2713   // Finally, check that the load addresses don't overlap. This will usually be
2714   // the same as the virtual addresses but can be different when using a linker
2715   // script with AT().
2716   std::vector<SectionOffset> lmas;
2717   for (OutputSection *sec : outputSections)
2718     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2719       lmas.push_back({sec, sec->getLMA()});
2720   checkOverlap("load address", lmas, false);
2721 }
2722 
2723 // The entry point address is chosen in the following ways.
2724 //
2725 // 1. the '-e' entry command-line option;
2726 // 2. the ENTRY(symbol) command in a linker control script;
2727 // 3. the value of the symbol _start, if present;
2728 // 4. the number represented by the entry symbol, if it is a number;
2729 // 5. the address 0.
2730 static uint64_t getEntryAddr() {
2731   // Case 1, 2 or 3
2732   if (Symbol *b = symtab->find(config->entry))
2733     return b->getVA();
2734 
2735   // Case 4
2736   uint64_t addr;
2737   if (to_integer(config->entry, addr))
2738     return addr;
2739 
2740   // Case 5
2741   if (config->warnMissingEntry)
2742     warn("cannot find entry symbol " + config->entry +
2743          "; not setting start address");
2744   return 0;
2745 }
2746 
2747 static uint16_t getELFType() {
2748   if (config->isPic)
2749     return ET_DYN;
2750   if (config->relocatable)
2751     return ET_REL;
2752   return ET_EXEC;
2753 }
2754 
2755 template <class ELFT> void Writer<ELFT>::writeHeader() {
2756   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2757   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2758 
2759   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2760   eHdr->e_type = getELFType();
2761   eHdr->e_entry = getEntryAddr();
2762   eHdr->e_shoff = sectionHeaderOff;
2763 
2764   // Write the section header table.
2765   //
2766   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2767   // and e_shstrndx fields. When the value of one of these fields exceeds
2768   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2769   // use fields in the section header at index 0 to store
2770   // the value. The sentinel values and fields are:
2771   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2772   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2773   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2774   size_t num = outputSections.size() + 1;
2775   if (num >= SHN_LORESERVE)
2776     sHdrs->sh_size = num;
2777   else
2778     eHdr->e_shnum = num;
2779 
2780   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2781   if (strTabIndex >= SHN_LORESERVE) {
2782     sHdrs->sh_link = strTabIndex;
2783     eHdr->e_shstrndx = SHN_XINDEX;
2784   } else {
2785     eHdr->e_shstrndx = strTabIndex;
2786   }
2787 
2788   for (OutputSection *sec : outputSections)
2789     sec->writeHeaderTo<ELFT>(++sHdrs);
2790 }
2791 
2792 // Open a result file.
2793 template <class ELFT> void Writer<ELFT>::openFile() {
2794   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2795   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2796     std::string msg;
2797     raw_string_ostream s(msg);
2798     s << "output file too large: " << Twine(fileSize) << " bytes\n"
2799       << "section sizes:\n";
2800     for (OutputSection *os : outputSections)
2801       s << os->name << ' ' << os->size << "\n";
2802     error(s.str());
2803     return;
2804   }
2805 
2806   unlinkAsync(config->outputFile);
2807   unsigned flags = 0;
2808   if (!config->relocatable)
2809     flags |= FileOutputBuffer::F_executable;
2810   if (!config->mmapOutputFile)
2811     flags |= FileOutputBuffer::F_no_mmap;
2812   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2813       FileOutputBuffer::create(config->outputFile, fileSize, flags);
2814 
2815   if (!bufferOrErr) {
2816     error("failed to open " + config->outputFile + ": " +
2817           llvm::toString(bufferOrErr.takeError()));
2818     return;
2819   }
2820   buffer = std::move(*bufferOrErr);
2821   Out::bufferStart = buffer->getBufferStart();
2822 }
2823 
2824 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2825   for (OutputSection *sec : outputSections)
2826     if (sec->flags & SHF_ALLOC)
2827       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2828 }
2829 
2830 static void fillTrap(uint8_t *i, uint8_t *end) {
2831   for (; i + 4 <= end; i += 4)
2832     memcpy(i, &target->trapInstr, 4);
2833 }
2834 
2835 // Fill the last page of executable segments with trap instructions
2836 // instead of leaving them as zero. Even though it is not required by any
2837 // standard, it is in general a good thing to do for security reasons.
2838 //
2839 // We'll leave other pages in segments as-is because the rest will be
2840 // overwritten by output sections.
2841 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2842   for (Partition &part : partitions) {
2843     // Fill the last page.
2844     for (PhdrEntry *p : part.phdrs)
2845       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2846         fillTrap(Out::bufferStart +
2847                      alignDown(p->firstSec->offset + p->p_filesz, 4),
2848                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2849                                             config->maxPageSize));
2850 
2851     // Round up the file size of the last segment to the page boundary iff it is
2852     // an executable segment to ensure that other tools don't accidentally
2853     // trim the instruction padding (e.g. when stripping the file).
2854     PhdrEntry *last = nullptr;
2855     for (PhdrEntry *p : part.phdrs)
2856       if (p->p_type == PT_LOAD)
2857         last = p;
2858 
2859     if (last && (last->p_flags & PF_X))
2860       last->p_memsz = last->p_filesz =
2861           alignTo(last->p_filesz, config->maxPageSize);
2862   }
2863 }
2864 
2865 // Write section contents to a mmap'ed file.
2866 template <class ELFT> void Writer<ELFT>::writeSections() {
2867   llvm::TimeTraceScope timeScope("Write sections");
2868 
2869   // In -r or --emit-relocs mode, write the relocation sections first as in
2870   // ELf_Rel targets we might find out that we need to modify the relocated
2871   // section while doing it.
2872   for (OutputSection *sec : outputSections)
2873     if (sec->type == SHT_REL || sec->type == SHT_RELA)
2874       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2875 
2876   for (OutputSection *sec : outputSections)
2877     if (sec->type != SHT_REL && sec->type != SHT_RELA)
2878       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2879 
2880   // Finally, check that all dynamic relocation addends were written correctly.
2881   if (config->checkDynamicRelocs && config->writeAddends) {
2882     for (OutputSection *sec : outputSections)
2883       if (sec->type == SHT_REL || sec->type == SHT_RELA)
2884         sec->checkDynRelAddends(Out::bufferStart);
2885   }
2886 }
2887 
2888 // Computes a hash value of Data using a given hash function.
2889 // In order to utilize multiple cores, we first split data into 1MB
2890 // chunks, compute a hash for each chunk, and then compute a hash value
2891 // of the hash values.
2892 static void
2893 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2894             llvm::ArrayRef<uint8_t> data,
2895             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2896   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2897   const size_t hashesSize = chunks.size() * hashBuf.size();
2898   std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2899 
2900   // Compute hash values.
2901   parallelForEachN(0, chunks.size(), [&](size_t i) {
2902     hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2903   });
2904 
2905   // Write to the final output buffer.
2906   hashFn(hashBuf.data(), makeArrayRef(hashes.get(), hashesSize));
2907 }
2908 
2909 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2910   if (!mainPart->buildId || !mainPart->buildId->getParent())
2911     return;
2912 
2913   if (config->buildId == BuildIdKind::Hexstring) {
2914     for (Partition &part : partitions)
2915       part.buildId->writeBuildId(config->buildIdVector);
2916     return;
2917   }
2918 
2919   // Compute a hash of all sections of the output file.
2920   size_t hashSize = mainPart->buildId->hashSize;
2921   std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
2922   MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
2923   llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};
2924 
2925   switch (config->buildId) {
2926   case BuildIdKind::Fast:
2927     computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2928       write64le(dest, xxHash64(arr));
2929     });
2930     break;
2931   case BuildIdKind::Md5:
2932     computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2933       memcpy(dest, MD5::hash(arr).data(), hashSize);
2934     });
2935     break;
2936   case BuildIdKind::Sha1:
2937     computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2938       memcpy(dest, SHA1::hash(arr).data(), hashSize);
2939     });
2940     break;
2941   case BuildIdKind::Uuid:
2942     if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
2943       error("entropy source failure: " + ec.message());
2944     break;
2945   default:
2946     llvm_unreachable("unknown BuildIdKind");
2947   }
2948   for (Partition &part : partitions)
2949     part.buildId->writeBuildId(output);
2950 }
2951 
2952 template void elf::createSyntheticSections<ELF32LE>();
2953 template void elf::createSyntheticSections<ELF32BE>();
2954 template void elf::createSyntheticSections<ELF64LE>();
2955 template void elf::createSyntheticSections<ELF64BE>();
2956 
2957 template void elf::writeResult<ELF32LE>();
2958 template void elf::writeResult<ELF32BE>();
2959 template void elf::writeResult<ELF64LE>();
2960 template void elf::writeResult<ELF64BE>();
2961