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