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