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