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