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