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