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