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