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