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