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