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