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