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