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