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