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