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