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