xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision e11fb13b)
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Writer.h"
11 #include "Config.h"
12 #include "Filesystem.h"
13 #include "LinkerScript.h"
14 #include "MapFile.h"
15 #include "Memory.h"
16 #include "OutputSections.h"
17 #include "Relocations.h"
18 #include "Strings.h"
19 #include "SymbolTable.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "Threads.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/FileOutputBuffer.h"
26 #include "llvm/Support/raw_ostream.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   typedef typename ELFT::Shdr Elf_Shdr;
43   typedef typename ELFT::Ehdr Elf_Ehdr;
44   typedef typename ELFT::Phdr Elf_Phdr;
45 
46   void run();
47 
48 private:
49   void createSyntheticSections();
50   void copyLocalSymbols();
51   void addSectionSymbols();
52   void addReservedSymbols();
53   void createSections();
54   void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
55   void sortSections();
56   void finalizeSections();
57   void addPredefinedSections();
58 
59   std::vector<PhdrEntry> createPhdrs();
60   void removeEmptyPTLoad();
61   void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
62   void assignAddresses();
63   void assignFileOffsets();
64   void assignFileOffsetsBinary();
65   void setPhdrs();
66   void fixHeaders();
67   void fixSectionAlignments();
68   void fixPredefinedSymbols();
69   void openFile();
70   void writeHeader();
71   void writeSections();
72   void writeSectionsBinary();
73   void writeBuildId();
74 
75   std::unique_ptr<FileOutputBuffer> Buffer;
76 
77   std::vector<OutputSection *> OutputSections;
78   OutputSectionFactory Factory{OutputSections};
79 
80   void addRelIpltSymbols();
81   void addStartEndSymbols();
82   void addStartStopSymbols(OutputSection *Sec);
83   uint64_t getEntryAddr();
84   OutputSection *findSection(StringRef Name);
85 
86   std::vector<PhdrEntry> Phdrs;
87 
88   uint64_t FileSize;
89   uint64_t SectionHeaderOff;
90   bool AllocateHeader = true;
91 };
92 } // anonymous namespace
93 
94 StringRef elf::getOutputSectionName(StringRef Name) {
95   if (Config->Relocatable)
96     return Name;
97 
98   // If -emit-relocs is given (which is rare), we need to copy
99   // relocation sections to the output. If input section .foo is
100   // output as .bar, we want to rename .rel.foo .rel.bar as well.
101   if (Config->EmitRelocs) {
102     for (StringRef V : {".rel.", ".rela."}) {
103       if (Name.startswith(V)) {
104         StringRef Inner = getOutputSectionName(Name.substr(V.size() - 1));
105         return Saver.save(Twine(V.drop_back()) + Inner);
106       }
107     }
108   }
109 
110   for (StringRef V :
111        {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
112         ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
113         ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
114     StringRef Prefix = V.drop_back();
115     if (Name.startswith(V) || Name == Prefix)
116       return Prefix;
117   }
118 
119   // CommonSection is identified as "COMMON" in linker scripts.
120   // By default, it should go to .bss section.
121   if (Name == "COMMON")
122     return ".bss";
123 
124   // ".zdebug_" is a prefix for ZLIB-compressed sections.
125   // Because we decompressed input sections, we want to remove 'z'.
126   if (Name.startswith(".zdebug_"))
127     return Saver.save(Twine(".") + Name.substr(2));
128   return Name;
129 }
130 
131 template <class ELFT> static bool needsInterpSection() {
132   return !Symtab<ELFT>::X->getSharedFiles().empty() &&
133          !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
134 }
135 
136 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
137 
138 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
139   auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
140     if (P.p_type != PT_LOAD)
141       return false;
142     if (!P.First)
143       return true;
144     uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
145     return Size == 0;
146   });
147   Phdrs.erase(I, Phdrs.end());
148 }
149 
150 // This function scans over the input sections and creates mergeable
151 // synthetic sections. It removes MergeInputSections from array and
152 // adds new synthetic ones. Each synthetic section is added to the
153 // location of the first input section it replaces.
154 static void combineMergableSections() {
155   std::vector<MergeSyntheticSection *> MergeSections;
156   for (InputSectionBase *&S : InputSections) {
157     MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
158     if (!MS)
159       continue;
160 
161     // We do not want to handle sections that are not alive, so just remove
162     // them instead of trying to merge.
163     if (!MS->Live)
164       continue;
165 
166     StringRef OutsecName = getOutputSectionName(MS->Name);
167     uint64_t Flags = MS->Flags & ~(uint64_t)(SHF_GROUP | SHF_COMPRESSED);
168     uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
169 
170     auto I =
171         llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
172           return Sec->Name == OutsecName && Sec->Flags == Flags &&
173                  Sec->Alignment == Alignment;
174         });
175     if (I == MergeSections.end()) {
176       MergeSyntheticSection *Syn =
177           make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment);
178       MergeSections.push_back(Syn);
179       I = std::prev(MergeSections.end());
180       S = Syn;
181     } else {
182       S = nullptr;
183     }
184     (*I)->addSection(MS);
185   }
186 
187   std::vector<InputSectionBase *> &V = InputSections;
188   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
189 }
190 
191 template <class ELFT> static void combineEhFrameSections() {
192   for (InputSectionBase *&S : InputSections) {
193     EhInputSection *ES = dyn_cast<EhInputSection>(S);
194     if (!ES || !ES->Live)
195       continue;
196 
197     In<ELFT>::EhFrame->addSection(ES);
198     S = nullptr;
199   }
200 
201   std::vector<InputSectionBase *> &V = InputSections;
202   V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
203 }
204 
205 // The main function of the writer.
206 template <class ELFT> void Writer<ELFT>::run() {
207   // Create linker-synthesized sections such as .got or .plt.
208   // Such sections are of type input section.
209   createSyntheticSections();
210   combineMergableSections();
211 
212   if (!Config->Relocatable)
213     combineEhFrameSections<ELFT>();
214 
215   // We need to create some reserved symbols such as _end. Create them.
216   if (!Config->Relocatable)
217     addReservedSymbols();
218 
219   // Create output sections.
220   Script->OutputSections = &OutputSections;
221   if (Script->Opt.HasSections) {
222     // If linker script contains SECTIONS commands, let it create sections.
223     Script->processCommands(Factory);
224 
225     // Linker scripts may have left some input sections unassigned.
226     // Assign such sections using the default rule.
227     Script->addOrphanSections(Factory);
228   } else {
229     // If linker script does not contain SECTIONS commands, create
230     // output sections by default rules. We still need to give the
231     // linker script a chance to run, because it might contain
232     // non-SECTIONS commands such as ASSERT.
233     createSections();
234     Script->processCommands(Factory);
235   }
236 
237   if (Config->Discard != DiscardPolicy::All)
238     copyLocalSymbols();
239 
240   if (Config->CopyRelocs)
241     addSectionSymbols();
242 
243   // Now that we have a complete set of output sections. This function
244   // completes section contents. For example, we need to add strings
245   // to the string table, and add entries to .got and .plt.
246   // finalizeSections does that.
247   finalizeSections();
248   if (ErrorCount)
249     return;
250 
251   if (Config->Relocatable) {
252     assignFileOffsets();
253   } else {
254     if (Script->Opt.HasSections) {
255       Script->assignAddresses(Phdrs);
256     } else {
257       fixSectionAlignments();
258       assignAddresses();
259       Script->processNonSectionCommands();
260     }
261 
262     // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
263     // 0 sized region. This has to be done late since only after assignAddresses
264     // we know the size of the sections.
265     removeEmptyPTLoad();
266 
267     if (!Config->OFormatBinary)
268       assignFileOffsets();
269     else
270       assignFileOffsetsBinary();
271 
272     setPhdrs();
273     fixPredefinedSymbols();
274   }
275 
276   // It does not make sense try to open the file if we have error already.
277   if (ErrorCount)
278     return;
279   // Write the result down to a file.
280   openFile();
281   if (ErrorCount)
282     return;
283   if (!Config->OFormatBinary) {
284     writeHeader();
285     writeSections();
286   } else {
287     writeSectionsBinary();
288   }
289 
290   // Backfill .note.gnu.build-id section content. This is done at last
291   // because the content is usually a hash value of the entire output file.
292   writeBuildId();
293   if (ErrorCount)
294     return;
295 
296   // Handle -Map option.
297   writeMapFile<ELFT>(OutputSections);
298   if (ErrorCount)
299     return;
300 
301   if (auto EC = Buffer->commit())
302     error("failed to write to the output file: " + EC.message());
303 
304   // Flush the output streams and exit immediately. A full shutdown
305   // is a good test that we are keeping track of all allocated memory,
306   // but actually freeing it is a waste of time in a regular linker run.
307   if (Config->ExitEarly)
308     exitLld(0);
309 }
310 
311 // Initialize Out members.
312 template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
313   // Initialize all pointers with NULL. This is needed because
314   // you can call lld::elf::main more than once as a library.
315   memset(&Out::First, 0, sizeof(Out));
316 
317   auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
318 
319   In<ELFT>::DynStrTab = make<StringTableSection>(".dynstr", true);
320   In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
321   In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
322       Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
323   In<ELFT>::ShStrTab = make<StringTableSection>(".shstrtab", false);
324 
325   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
326   Out::ElfHeader->Size = sizeof(Elf_Ehdr);
327   Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
328   Out::ProgramHeaders->updateAlignment(Config->Wordsize);
329 
330   if (needsInterpSection<ELFT>()) {
331     In<ELFT>::Interp = createInterpSection();
332     Add(In<ELFT>::Interp);
333   } else {
334     In<ELFT>::Interp = nullptr;
335   }
336 
337   if (!Config->Relocatable)
338     Add(createCommentSection<ELFT>());
339 
340   if (Config->Strip != StripPolicy::All) {
341     In<ELFT>::StrTab = make<StringTableSection>(".strtab", false);
342     In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
343   }
344 
345   if (Config->BuildId != BuildIdKind::None) {
346     In<ELFT>::BuildId = make<BuildIdSection>();
347     Add(In<ELFT>::BuildId);
348   }
349 
350   In<ELFT>::Common = createCommonSection<ELFT>();
351   if (In<ELFT>::Common)
352     Add(InX::Common);
353 
354   In<ELFT>::Bss = make<BssSection>(".bss");
355   Add(In<ELFT>::Bss);
356   In<ELFT>::BssRelRo = make<BssSection>(".bss.rel.ro");
357   Add(In<ELFT>::BssRelRo);
358 
359   // Add MIPS-specific sections.
360   bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
361                       Config->Pic || Config->ExportDynamic;
362   if (Config->EMachine == EM_MIPS) {
363     if (!Config->Shared && HasDynSymTab) {
364       In<ELFT>::MipsRldMap = make<MipsRldMapSection>();
365       Add(In<ELFT>::MipsRldMap);
366     }
367     if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
368       Add(Sec);
369     if (auto *Sec = MipsOptionsSection<ELFT>::create())
370       Add(Sec);
371     if (auto *Sec = MipsReginfoSection<ELFT>::create())
372       Add(Sec);
373   }
374 
375   if (HasDynSymTab) {
376     In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
377     Add(In<ELFT>::DynSymTab);
378 
379     In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
380     Add(In<ELFT>::VerSym);
381 
382     if (!Config->VersionDefinitions.empty()) {
383       In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
384       Add(In<ELFT>::VerDef);
385     }
386 
387     In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
388     Add(In<ELFT>::VerNeed);
389 
390     if (Config->GnuHash) {
391       In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
392       Add(In<ELFT>::GnuHashTab);
393     }
394 
395     if (Config->SysvHash) {
396       In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
397       Add(In<ELFT>::HashTab);
398     }
399 
400     Add(In<ELFT>::Dynamic);
401     Add(In<ELFT>::DynStrTab);
402     Add(In<ELFT>::RelaDyn);
403   }
404 
405   // Add .got. MIPS' .got is so different from the other archs,
406   // it has its own class.
407   if (Config->EMachine == EM_MIPS) {
408     In<ELFT>::MipsGot = make<MipsGotSection>();
409     Add(In<ELFT>::MipsGot);
410   } else {
411     In<ELFT>::Got = make<GotSection<ELFT>>();
412     Add(In<ELFT>::Got);
413   }
414 
415   In<ELFT>::GotPlt = make<GotPltSection>();
416   Add(In<ELFT>::GotPlt);
417   In<ELFT>::IgotPlt = make<IgotPltSection>();
418   Add(In<ELFT>::IgotPlt);
419 
420   if (Config->GdbIndex) {
421     In<ELFT>::GdbIndex = make<GdbIndexSection>();
422     Add(In<ELFT>::GdbIndex);
423   }
424 
425   // We always need to add rel[a].plt to output if it has entries.
426   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
427   In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
428       Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
429   Add(In<ELFT>::RelaPlt);
430 
431   // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
432   // that the IRelative relocations are processed last by the dynamic loader
433   In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
434       (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
435       false /*Sort*/);
436   Add(In<ELFT>::RelaIplt);
437 
438   In<ELFT>::Plt = make<PltSection>(Target->PltHeaderSize);
439   Add(In<ELFT>::Plt);
440   In<ELFT>::Iplt = make<PltSection>(0);
441   Add(In<ELFT>::Iplt);
442 
443   if (!Config->Relocatable) {
444     if (Config->EhFrameHdr) {
445       In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
446       Add(In<ELFT>::EhFrameHdr);
447     }
448     In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
449     Add(In<ELFT>::EhFrame);
450   }
451 
452   if (In<ELFT>::SymTab)
453     Add(In<ELFT>::SymTab);
454   Add(In<ELFT>::ShStrTab);
455   if (In<ELFT>::StrTab)
456     Add(In<ELFT>::StrTab);
457 }
458 
459 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
460                                const SymbolBody &B) {
461   if (B.isFile() || B.isSection())
462     return false;
463 
464   // If sym references a section in a discarded group, don't keep it.
465   if (Sec == &InputSection::Discarded)
466     return false;
467 
468   if (Config->Discard == DiscardPolicy::None)
469     return true;
470 
471   // In ELF assembly .L symbols are normally discarded by the assembler.
472   // If the assembler fails to do so, the linker discards them if
473   // * --discard-locals is used.
474   // * The symbol is in a SHF_MERGE section, which is normally the reason for
475   //   the assembler keeping the .L symbol.
476   if (!SymName.startswith(".L") && !SymName.empty())
477     return true;
478 
479   if (Config->Discard == DiscardPolicy::Locals)
480     return false;
481 
482   return !Sec || !(Sec->Flags & SHF_MERGE);
483 }
484 
485 static bool includeInSymtab(const SymbolBody &B) {
486   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
487     return false;
488 
489   if (auto *D = dyn_cast<DefinedRegular>(&B)) {
490     // Always include absolute symbols.
491     SectionBase *Sec = D->Section;
492     if (!Sec)
493       return true;
494     if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
495       Sec = IS->Repl;
496       IS = cast<InputSectionBase>(Sec);
497       // Exclude symbols pointing to garbage-collected sections.
498       if (!IS->Live)
499         return false;
500     }
501     if (auto *S = dyn_cast<MergeInputSection>(Sec))
502       if (!S->getSectionPiece(D->Value)->Live)
503         return false;
504   }
505   return true;
506 }
507 
508 // Local symbols are not in the linker's symbol table. This function scans
509 // each object file's symbol table to copy local symbols to the output.
510 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
511   if (!In<ELFT>::SymTab)
512     return;
513   for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
514     for (SymbolBody *B : F->getLocalSymbols()) {
515       if (!B->IsLocal)
516         fatal(toString(F) +
517               ": broken object: getLocalSymbols returns a non-local symbol");
518       auto *DR = dyn_cast<DefinedRegular>(B);
519 
520       // No reason to keep local undefined symbol in symtab.
521       if (!DR)
522         continue;
523       if (!includeInSymtab(*B))
524         continue;
525 
526       SectionBase *Sec = DR->Section;
527       if (!shouldKeepInSymtab(Sec, B->getName(), *B))
528         continue;
529       In<ELFT>::SymTab->addSymbol(B);
530     }
531   }
532 }
533 
534 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
535   // Create one STT_SECTION symbol for each output section we might
536   // have a relocation with.
537   for (OutputSection *Sec : OutputSections) {
538     if (Sec->Sections.empty())
539       continue;
540 
541     InputSection *IS = Sec->Sections[0];
542     if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
543         IS->Type == SHT_RELA)
544       continue;
545 
546     auto *Sym =
547         make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
548                              /*Value=*/0, /*Size=*/0, IS, nullptr);
549     In<ELFT>::SymTab->addSymbol(Sym);
550   }
551 }
552 
553 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
554 // we would like to make sure appear is a specific order to maximize their
555 // coverage by a single signed 16-bit offset from the TOC base pointer.
556 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
557 // sections. This will put it next to the loaded special PPC64 sections (and,
558 // thus, within reach of the TOC base pointer).
559 static int getPPC64SectionRank(StringRef SectionName) {
560   return StringSwitch<int>(SectionName)
561       .Case(".tocbss", 0)
562       .Case(".branch_lt", 2)
563       .Case(".toc", 3)
564       .Case(".toc1", 4)
565       .Case(".opd", 5)
566       .Default(1);
567 }
568 
569 // All sections with SHF_MIPS_GPREL flag should be grouped together
570 // because data in these sections is addressable with a gp relative address.
571 static int getMipsSectionRank(const OutputSection *S) {
572   if ((S->Flags & SHF_MIPS_GPREL) == 0)
573     return 0;
574   if (S->Name == ".got")
575     return 1;
576   return 2;
577 }
578 
579 // Today's loaders have a feature to make segments read-only after
580 // processing dynamic relocations to enhance security. PT_GNU_RELRO
581 // is defined for that.
582 //
583 // This function returns true if a section needs to be put into a
584 // PT_GNU_RELRO segment.
585 template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) {
586   if (!Config->ZRelro)
587     return false;
588 
589   uint64_t Flags = Sec->Flags;
590 
591   // Non-allocatable or non-writable sections don't need RELRO because
592   // they are not writable or not even mapped to memory in the first place.
593   // RELRO is for sections that are essentially read-only but need to
594   // be writable only at process startup to allow dynamic linker to
595   // apply relocations.
596   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
597     return false;
598 
599   // Once initialized, TLS data segments are used as data templates
600   // for a thread-local storage. For each new thread, runtime
601   // allocates memory for a TLS and copy templates there. No thread
602   // are supposed to use templates directly. Thus, it can be in RELRO.
603   if (Flags & SHF_TLS)
604     return true;
605 
606   // .init_array, .preinit_array and .fini_array contain pointers to
607   // functions that are executed on process startup or exit. These
608   // pointers are set by the static linker, and they are not expected
609   // to change at runtime. But if you are an attacker, you could do
610   // interesting things by manipulating pointers in .fini_array, for
611   // example. So they are put into RELRO.
612   uint32_t Type = Sec->Type;
613   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
614       Type == SHT_PREINIT_ARRAY)
615     return true;
616 
617   // .got contains pointers to external symbols. They are resolved by
618   // the dynamic linker when a module is loaded into memory, and after
619   // that they are not expected to change. So, it can be in RELRO.
620   if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
621     return true;
622 
623   // .got.plt contains pointers to external function symbols. They are
624   // by default resolved lazily, so we usually cannot put it into RELRO.
625   // However, if "-z now" is given, the lazy symbol resolution is
626   // disabled, which enables us to put it into RELRO.
627   if (Sec == In<ELFT>::GotPlt->OutSec)
628     return Config->ZNow;
629 
630   // .dynamic section contains data for the dynamic linker, and
631   // there's no need to write to it at runtime, so it's better to put
632   // it into RELRO.
633   if (Sec == In<ELFT>::Dynamic->OutSec)
634     return true;
635 
636   // .bss.rel.ro is used for copy relocations for read-only symbols.
637   // Since the dynamic linker needs to process copy relocations, the
638   // section cannot be read-only, but once initialized, they shouldn't
639   // change.
640   if (Sec == In<ELFT>::BssRelRo->OutSec)
641     return true;
642 
643   // Sections with some special names are put into RELRO. This is a
644   // bit unfortunate because section names shouldn't be significant in
645   // ELF in spirit. But in reality many linker features depend on
646   // magic section names.
647   StringRef S = Sec->Name;
648   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
649          S == ".eh_frame" || S == ".openbsd.randomdata";
650 }
651 
652 template <class ELFT>
653 static bool compareSectionsNonScript(const OutputSection *A,
654                                      const OutputSection *B) {
655   // Put .interp first because some loaders want to see that section
656   // on the first page of the executable file when loaded into memory.
657   bool AIsInterp = A->Name == ".interp";
658   bool BIsInterp = B->Name == ".interp";
659   if (AIsInterp != BIsInterp)
660     return AIsInterp;
661 
662   // Allocatable sections go first to reduce the total PT_LOAD size and
663   // so debug info doesn't change addresses in actual code.
664   bool AIsAlloc = A->Flags & SHF_ALLOC;
665   bool BIsAlloc = B->Flags & SHF_ALLOC;
666   if (AIsAlloc != BIsAlloc)
667     return AIsAlloc;
668 
669   // We don't have any special requirements for the relative order of two non
670   // allocatable sections.
671   if (!AIsAlloc)
672     return false;
673 
674   // We want to put section specified by -T option first, so we
675   // can start assigning VA starting from them later.
676   auto AAddrSetI = Config->SectionStartMap.find(A->Name);
677   auto BAddrSetI = Config->SectionStartMap.find(B->Name);
678   bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
679   bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
680   if (AHasAddrSet != BHasAddrSet)
681     return AHasAddrSet;
682   if (AHasAddrSet)
683     return AAddrSetI->second < BAddrSetI->second;
684 
685   // We want the read only sections first so that they go in the PT_LOAD
686   // covering the program headers at the start of the file.
687   bool AIsWritable = A->Flags & SHF_WRITE;
688   bool BIsWritable = B->Flags & SHF_WRITE;
689   if (AIsWritable != BIsWritable)
690     return BIsWritable;
691 
692   if (!Config->SingleRoRx) {
693     // For a corresponding reason, put non exec sections first (the program
694     // header PT_LOAD is not executable).
695     // We only do that if we are not using linker scripts, since with linker
696     // scripts ro and rx sections are in the same PT_LOAD, so their relative
697     // order is not important. The same applies for -no-rosegment.
698     bool AIsExec = A->Flags & SHF_EXECINSTR;
699     bool BIsExec = B->Flags & SHF_EXECINSTR;
700     if (AIsExec != BIsExec)
701       return BIsExec;
702   }
703 
704   // If we got here we know that both A and B are in the same PT_LOAD.
705 
706   bool AIsTls = A->Flags & SHF_TLS;
707   bool BIsTls = B->Flags & SHF_TLS;
708   bool AIsNoBits = A->Type == SHT_NOBITS;
709   bool BIsNoBits = B->Type == SHT_NOBITS;
710 
711   // The first requirement we have is to put (non-TLS) nobits sections last. The
712   // reason is that the only thing the dynamic linker will see about them is a
713   // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
714   // PT_LOAD, so that has to correspond to the nobits sections.
715   bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
716   bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
717   if (AIsNonTlsNoBits != BIsNonTlsNoBits)
718     return BIsNonTlsNoBits;
719 
720   // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
721   // sections after r/w ones, so that the RelRo sections are contiguous.
722   bool AIsRelRo = isRelroSection<ELFT>(A);
723   bool BIsRelRo = isRelroSection<ELFT>(B);
724   if (AIsRelRo != BIsRelRo)
725     return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
726 
727   // The TLS initialization block needs to be a single contiguous block in a R/W
728   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
729   // sections. The TLS NOBITS sections are placed here as they don't take up
730   // virtual address space in the PT_LOAD.
731   if (AIsTls != BIsTls)
732     return AIsTls;
733 
734   // Within the TLS initialization block, the non-nobits sections need to appear
735   // first.
736   if (AIsNoBits != BIsNoBits)
737     return BIsNoBits;
738 
739   // Some architectures have additional ordering restrictions for sections
740   // within the same PT_LOAD.
741   if (Config->EMachine == EM_PPC64)
742     return getPPC64SectionRank(A->Name) < getPPC64SectionRank(B->Name);
743   if (Config->EMachine == EM_MIPS)
744     return getMipsSectionRank(A) < getMipsSectionRank(B);
745 
746   return false;
747 }
748 
749 // Output section ordering is determined by this function.
750 template <class ELFT>
751 static bool compareSections(const OutputSection *A, const OutputSection *B) {
752   // For now, put sections mentioned in a linker script first.
753   int AIndex = Script->getSectionIndex(A->Name);
754   int BIndex = Script->getSectionIndex(B->Name);
755   bool AInScript = AIndex != INT_MAX;
756   bool BInScript = BIndex != INT_MAX;
757   if (AInScript != BInScript)
758     return AInScript;
759   // If both are in the script, use that order.
760   if (AInScript)
761     return AIndex < BIndex;
762 
763   return compareSectionsNonScript<ELFT>(A, B);
764 }
765 
766 // Program header entry
767 PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
768   p_type = Type;
769   p_flags = Flags;
770 }
771 
772 void PhdrEntry::add(OutputSection *Sec) {
773   Last = Sec;
774   if (!First)
775     First = Sec;
776   p_align = std::max(p_align, Sec->Alignment);
777   if (p_type == PT_LOAD)
778     Sec->FirstInPtLoad = First;
779 }
780 
781 template <class ELFT>
782 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
783                           uint8_t StOther = STV_HIDDEN,
784                           uint8_t Binding = STB_WEAK) {
785   // The linker generated symbols are added as STB_WEAK to allow user defined
786   // ones to override them.
787   return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
788                                      /*Size=*/0, Binding, Sec,
789                                      /*File=*/nullptr);
790 }
791 
792 template <class ELFT>
793 static DefinedRegular *
794 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
795                    uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
796   SymbolBody *S = Symtab<ELFT>::X->find(Name);
797   if (!S)
798     return nullptr;
799   if (S->isInCurrentDSO())
800     return nullptr;
801   return cast<DefinedRegular>(
802       addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
803 }
804 
805 // The beginning and the ending of .rel[a].plt section are marked
806 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
807 // executable. The runtime needs these symbols in order to resolve
808 // all IRELATIVE relocs on startup. For dynamic executables, we don't
809 // need these symbols, since IRELATIVE relocs are resolved through GOT
810 // and PLT. For details, see http://www.airs.com/blog/archives/403.
811 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
812   if (In<ELFT>::DynSymTab)
813     return;
814   StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
815   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
816 
817   S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
818   addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
819 }
820 
821 // The linker is expected to define some symbols depending on
822 // the linking result. This function defines such symbols.
823 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
824   if (Config->EMachine == EM_MIPS) {
825     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
826     // so that it points to an absolute address which by default is relative
827     // to GOT. Default offset is 0x7ff0.
828     // See "Global Data Symbols" in Chapter 6 in the following document:
829     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
830     ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
831 
832     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
833     // start of function and 'gp' pointer into GOT.
834     if (Symtab<ELFT>::X->find("_gp_disp"))
835       ElfSym::MipsGpDisp =
836           Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
837 
838     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
839     // pointer. This symbol is used in the code generated by .cpload pseudo-op
840     // in case of using -mno-shared option.
841     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
842     if (Symtab<ELFT>::X->find("__gnu_local_gp"))
843       ElfSym::MipsLocalGp =
844           Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
845   }
846 
847   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
848   // is magical and is used to produce a R_386_GOTPC relocation.
849   // The R_386_GOTPC relocation value doesn't actually depend on the
850   // symbol value, so it could use an index of STN_UNDEF which, according
851   // to the spec, means the symbol value is 0.
852   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
853   // the object file.
854   // The situation is even stranger on x86_64 where the assembly doesn't
855   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
856   // an undefined symbol in the .o files.
857   // Given that the symbol is effectively unused, we just create a dummy
858   // hidden one to avoid the undefined symbol error.
859   Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
860 
861   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
862   // static linking the linker is required to optimize away any references to
863   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
864   // to avoid the undefined symbol error. As usual special cases are ARM and
865   // MIPS - the libc for these targets defines __tls_get_addr itself because
866   // there are no TLS optimizations for these targets.
867   if (!In<ELFT>::DynSymTab &&
868       (Config->EMachine != EM_MIPS && Config->EMachine != EM_ARM))
869     Symtab<ELFT>::X->addIgnored("__tls_get_addr");
870 
871   // If linker script do layout we do not need to create any standart symbols.
872   if (Script->Opt.HasSections)
873     return;
874 
875   // __ehdr_start is the location of ELF file headers.
876   addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
877 
878   auto Add = [](StringRef S) {
879     return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
880   };
881 
882   ElfSym::Bss = Add("__bss_start");
883   ElfSym::End1 = Add("end");
884   ElfSym::End2 = Add("_end");
885   ElfSym::Etext1 = Add("etext");
886   ElfSym::Etext2 = Add("_etext");
887   ElfSym::Edata1 = Add("edata");
888   ElfSym::Edata2 = Add("_edata");
889 }
890 
891 // Sort input sections by section name suffixes for
892 // __attribute__((init_priority(N))).
893 static void sortInitFini(OutputSection *S) {
894   if (S)
895     reinterpret_cast<OutputSection *>(S)->sortInitFini();
896 }
897 
898 // Sort input sections by the special rule for .ctors and .dtors.
899 static void sortCtorsDtors(OutputSection *S) {
900   if (S)
901     reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
902 }
903 
904 // Sort input sections using the list provided by --symbol-ordering-file.
905 template <class ELFT>
906 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
907   if (Config->SymbolOrderingFile.empty())
908     return;
909 
910   // Build a map from symbols to their priorities. Symbols that didn't
911   // appear in the symbol ordering file have the lowest priority 0.
912   // All explicitly mentioned symbols have negative (higher) priorities.
913   DenseMap<StringRef, int> SymbolOrder;
914   int Priority = -Config->SymbolOrderingFile.size();
915   for (StringRef S : Config->SymbolOrderingFile)
916     SymbolOrder.insert({S, Priority++});
917 
918   // Build a map from sections to their priorities.
919   DenseMap<SectionBase *, int> SectionOrder;
920   for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
921     for (SymbolBody *Body : File->getSymbols()) {
922       auto *D = dyn_cast<DefinedRegular>(Body);
923       if (!D || !D->Section)
924         continue;
925       int &Priority = SectionOrder[D->Section];
926       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
927     }
928   }
929 
930   // Sort sections by priority.
931   for (OutputSection *Base : OutputSections)
932     if (auto *Sec = dyn_cast<OutputSection>(Base))
933       Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
934 }
935 
936 template <class ELFT>
937 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
938   for (InputSectionBase *IS : InputSections) {
939     if (!IS->Live)
940       continue;
941     // Scan all relocations. Each relocation goes through a series
942     // of tests to determine if it needs special treatment, such as
943     // creating GOT, PLT, copy relocations, etc.
944     // Note that relocations for non-alloc sections are directly
945     // processed by InputSection::relocateNonAlloc.
946     if (!(IS->Flags & SHF_ALLOC))
947       continue;
948     if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
949       Fn(*IS);
950   }
951 
952   if (!Config->Relocatable) {
953     for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
954       Fn(*ES);
955   }
956 }
957 
958 template <class ELFT> void Writer<ELFT>::createSections() {
959   for (InputSectionBase *IS : InputSections)
960     if (IS)
961       Factory.addInputSec(IS, getOutputSectionName(IS->Name));
962 
963   sortBySymbolsOrder<ELFT>(OutputSections);
964   sortInitFini(findSection(".init_array"));
965   sortInitFini(findSection(".fini_array"));
966   sortCtorsDtors(findSection(".ctors"));
967   sortCtorsDtors(findSection(".dtors"));
968 
969   for (OutputSection *Sec : OutputSections)
970     Sec->assignOffsets();
971 }
972 
973 static bool canSharePtLoad(const OutputSection &S1, const OutputSection &S2) {
974   if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
975     return false;
976 
977   bool S1IsWrite = S1.Flags & SHF_WRITE;
978   bool S2IsWrite = S2.Flags & SHF_WRITE;
979   if (S1IsWrite != S2IsWrite)
980     return false;
981 
982   if (!S1IsWrite)
983     return true; // RO and RX share a PT_LOAD with linker scripts.
984   return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
985 }
986 
987 template <class ELFT> void Writer<ELFT>::sortSections() {
988   // Don't sort if using -r. It is not necessary and we want to preserve the
989   // relative order for SHF_LINK_ORDER sections.
990   if (Config->Relocatable)
991     return;
992   if (!Script->Opt.HasSections) {
993     std::stable_sort(OutputSections.begin(), OutputSections.end(),
994                      compareSectionsNonScript<ELFT>);
995     return;
996   }
997   Script->adjustSectionsBeforeSorting();
998 
999   // The order of the sections in the script is arbitrary and may not agree with
1000   // compareSectionsNonScript. This means that we cannot easily define a
1001   // strict weak ordering. To see why, consider a comparison of a section in the
1002   // script and one not in the script. We have a two simple options:
1003   // * Make them equivalent (a is not less than b, and b is not less than a).
1004   //   The problem is then that equivalence has to be transitive and we can
1005   //   have sections a, b and c with only b in a script and a less than c
1006   //   which breaks this property.
1007   // * Use compareSectionsNonScript. Given that the script order doesn't have
1008   //   to match, we can end up with sections a, b, c, d where b and c are in the
1009   //   script and c is compareSectionsNonScript less than b. In which case d
1010   //   can be equivalent to c, a to b and d < a. As a concrete example:
1011   //   .a (rx) # not in script
1012   //   .b (rx) # in script
1013   //   .c (ro) # in script
1014   //   .d (ro) # not in script
1015   //
1016   // The way we define an order then is:
1017   // *  First put script sections at the start and sort the script and
1018   //    non-script sections independently.
1019   // *  Move each non-script section to its preferred position. We try
1020   //    to put each section in the last position where it it can share
1021   //    a PT_LOAD.
1022 
1023   std::stable_sort(OutputSections.begin(), OutputSections.end(),
1024                    compareSections<ELFT>);
1025 
1026   auto I = OutputSections.begin();
1027   auto E = OutputSections.end();
1028   auto NonScriptI =
1029       std::find_if(OutputSections.begin(), E, [](OutputSection *S) {
1030         return Script->getSectionIndex(S->Name) == INT_MAX;
1031       });
1032   while (NonScriptI != E) {
1033     auto BestPos = std::max_element(
1034         I, NonScriptI, [&](OutputSection *&A, OutputSection *&B) {
1035           bool ACanSharePtLoad = canSharePtLoad(**NonScriptI, *A);
1036           bool BCanSharePtLoad = canSharePtLoad(**NonScriptI, *B);
1037           if (ACanSharePtLoad != BCanSharePtLoad)
1038             return BCanSharePtLoad;
1039 
1040           bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
1041           bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
1042           if (ACmp != BCmp)
1043             return BCmp; // FIXME: missing test
1044 
1045           size_t PosA = &A - &OutputSections[0];
1046           size_t PosB = &B - &OutputSections[0];
1047           return ACmp ? PosA > PosB : PosA < PosB;
1048         });
1049 
1050     // max_element only returns NonScriptI if the range is empty. If the range
1051     // is not empty we should consider moving the the element forward one
1052     // position.
1053     if (BestPos != NonScriptI &&
1054         !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
1055       ++BestPos;
1056     std::rotate(BestPos, NonScriptI, NonScriptI + 1);
1057     ++NonScriptI;
1058   }
1059 
1060   Script->adjustSectionsAfterSorting();
1061 }
1062 
1063 static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1064                            std::function<void(SyntheticSection *)> Fn) {
1065   for (SyntheticSection *SS : Sections)
1066     if (SS && SS->OutSec && !SS->empty()) {
1067       Fn(SS);
1068       SS->OutSec->assignOffsets();
1069     }
1070 }
1071 
1072 // We need to add input synthetic sections early in createSyntheticSections()
1073 // to make them visible from linkescript side. But not all sections are always
1074 // required to be in output. For example we don't need dynamic section content
1075 // sometimes. This function filters out such unused sections from the output.
1076 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
1077   // All input synthetic sections that can be empty are placed after
1078   // all regular ones. We iterate over them all and exit at first
1079   // non-synthetic.
1080   for (InputSectionBase *S : llvm::reverse(InputSections)) {
1081     SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1082     if (!SS)
1083       return;
1084     if (!SS->empty() || !SS->OutSec)
1085       continue;
1086 
1087     SS->OutSec->Sections.erase(std::find(SS->OutSec->Sections.begin(),
1088                                          SS->OutSec->Sections.end(), SS));
1089     // If there are no other sections in the output section, remove it from the
1090     // output.
1091     if (SS->OutSec->Sections.empty())
1092       V.erase(std::find(V.begin(), V.end(), SS->OutSec));
1093   }
1094 }
1095 
1096 // Create output section objects and add them to OutputSections.
1097 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1098   Out::DebugInfo = findSection(".debug_info");
1099   Out::PreinitArray = findSection(".preinit_array");
1100   Out::InitArray = findSection(".init_array");
1101   Out::FiniArray = findSection(".fini_array");
1102 
1103   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1104   // symbols for sections, so that the runtime can get the start and end
1105   // addresses of each section by section name. Add such symbols.
1106   if (!Config->Relocatable) {
1107     addStartEndSymbols();
1108     for (OutputSection *Sec : OutputSections)
1109       addStartStopSymbols(Sec);
1110   }
1111 
1112   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1113   // It should be okay as no one seems to care about the type.
1114   // Even the author of gold doesn't remember why gold behaves that way.
1115   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1116   if (In<ELFT>::DynSymTab)
1117     addRegular<ELFT>("_DYNAMIC", In<ELFT>::Dynamic, 0);
1118 
1119   // Define __rel[a]_iplt_{start,end} symbols if needed.
1120   addRelIpltSymbols();
1121 
1122   // This responsible for splitting up .eh_frame section into
1123   // pieces. The relocation scan uses those pieces, so this has to be
1124   // earlier.
1125   applySynthetic({In<ELFT>::EhFrame},
1126                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1127 
1128   // Scan relocations. This must be done after every symbol is declared so that
1129   // we can correctly decide if a dynamic relocation is needed.
1130   forEachRelSec(scanRelocations<ELFT>);
1131 
1132   if (In<ELFT>::Plt && !In<ELFT>::Plt->empty())
1133     In<ELFT>::Plt->addSymbols();
1134   if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty())
1135     In<ELFT>::Iplt->addSymbols();
1136 
1137   // Now that we have defined all possible global symbols including linker-
1138   // synthesized ones. Visit all symbols to give the finishing touches.
1139   for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
1140     SymbolBody *Body = S->body();
1141 
1142     if (!includeInSymtab(*Body))
1143       continue;
1144     if (In<ELFT>::SymTab)
1145       In<ELFT>::SymTab->addSymbol(Body);
1146 
1147     if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
1148       In<ELFT>::DynSymTab->addSymbol(Body);
1149       if (auto *SS = dyn_cast<SharedSymbol>(Body))
1150         if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
1151           In<ELFT>::VerNeed->addSymbol(SS);
1152     }
1153   }
1154 
1155   // Do not proceed if there was an undefined symbol.
1156   if (ErrorCount)
1157     return;
1158 
1159   // So far we have added sections from input object files.
1160   // This function adds linker-created Out::* sections.
1161   addPredefinedSections();
1162   removeUnusedSyntheticSections(OutputSections);
1163 
1164   sortSections();
1165 
1166   // This is a bit of a hack. A value of 0 means undef, so we set it
1167   // to 1 t make __ehdr_start defined. The section number is not
1168   // particularly relevant.
1169   Out::ElfHeader->SectionIndex = 1;
1170 
1171   unsigned I = 1;
1172   for (OutputSection *Sec : OutputSections) {
1173     Sec->SectionIndex = I++;
1174     Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->Name);
1175   }
1176 
1177   // Binary and relocatable output does not have PHDRS.
1178   // The headers have to be created before finalize as that can influence the
1179   // image base and the dynamic section on mips includes the image base.
1180   if (!Config->Relocatable && !Config->OFormatBinary) {
1181     Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1182     addPtArmExid(Phdrs);
1183     fixHeaders();
1184   }
1185 
1186   // Dynamic section must be the last one in this list and dynamic
1187   // symbol table section (DynSymTab) must be the first one.
1188   applySynthetic({In<ELFT>::DynSymTab,  In<ELFT>::Bss,      In<ELFT>::BssRelRo,
1189                   In<ELFT>::GnuHashTab, In<ELFT>::HashTab,  In<ELFT>::SymTab,
1190                   In<ELFT>::ShStrTab,   In<ELFT>::StrTab,   In<ELFT>::VerDef,
1191                   In<ELFT>::DynStrTab,  In<ELFT>::GdbIndex, In<ELFT>::Got,
1192                   In<ELFT>::MipsGot,    In<ELFT>::IgotPlt,  In<ELFT>::GotPlt,
1193                   In<ELFT>::RelaDyn,    In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1194                   In<ELFT>::Plt,        In<ELFT>::Iplt,     In<ELFT>::Plt,
1195                   In<ELFT>::EhFrameHdr, In<ELFT>::VerSym,   In<ELFT>::VerNeed,
1196                   In<ELFT>::Dynamic},
1197                  [](SyntheticSection *SS) { SS->finalizeContents(); });
1198 
1199   // Some architectures use small displacements for jump instructions.
1200   // It is linker's responsibility to create thunks containing long
1201   // jump instructions if jump targets are too far. Create thunks.
1202   if (Target->NeedsThunks) {
1203     // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1204     // these
1205     // do not require address information. To support range extension Thunks
1206     // we need to assign addresses so that we can tell if jump instructions
1207     // are out of range. This will need to turn into a loop that converges
1208     // when no more Thunks are added
1209     ThunkCreator<ELFT> TC;
1210     if (TC.createThunks(OutputSections))
1211       applySynthetic({In<ELFT>::MipsGot},
1212                      [](SyntheticSection *SS) { SS->updateAllocSize(); });
1213   }
1214   // Fill other section headers. The dynamic table is finalized
1215   // at the end because some tags like RELSZ depend on result
1216   // of finalizing other sections.
1217   for (OutputSection *Sec : OutputSections)
1218     Sec->finalize<ELFT>();
1219 
1220   // Some sections may require compression. That happens for
1221   // debug sections when --compress-debug-sections option used.
1222   parallelForEach(OutputSections.begin(), OutputSections.end(),
1223                   [](OutputSection *S) { S->maybeCompress<ELFT>(); });
1224 
1225   // createThunks may have added local symbols to the static symbol table
1226   applySynthetic({In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab},
1227                  [](SyntheticSection *SS) { SS->postThunkContents(); });
1228 }
1229 
1230 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1231   // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1232   // We have the terminater synthetic section class. Add that at the end.
1233   auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
1234   if (OS && !OS->Sections.empty() && !Config->Relocatable)
1235     OS->addSection(make<ARMExidxSentinelSection>());
1236 }
1237 
1238 // The linker is expected to define SECNAME_start and SECNAME_end
1239 // symbols for a few sections. This function defines them.
1240 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1241   auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
1242     // These symbols resolve to the image base if the section does not exist.
1243     // A special value -1 indicates end of the section.
1244     if (OS) {
1245       addOptionalRegular<ELFT>(Start, OS, 0);
1246       addOptionalRegular<ELFT>(End, OS, -1);
1247     } else {
1248       if (Config->Pic)
1249         OS = Out::ElfHeader;
1250       addOptionalRegular<ELFT>(Start, OS, 0);
1251       addOptionalRegular<ELFT>(End, OS, 0);
1252     }
1253   };
1254 
1255   Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1256   Define("__init_array_start", "__init_array_end", Out::InitArray);
1257   Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1258 
1259   if (OutputSection *Sec = findSection(".ARM.exidx"))
1260     Define("__exidx_start", "__exidx_end", Sec);
1261 }
1262 
1263 // If a section name is valid as a C identifier (which is rare because of
1264 // the leading '.'), linkers are expected to define __start_<secname> and
1265 // __stop_<secname> symbols. They are at beginning and end of the section,
1266 // respectively. This is not requested by the ELF standard, but GNU ld and
1267 // gold provide the feature, and used by many programs.
1268 template <class ELFT>
1269 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1270   StringRef S = Sec->Name;
1271   if (!isValidCIdentifier(S))
1272     return;
1273   addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1274   addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
1275 }
1276 
1277 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1278   for (OutputSection *Sec : OutputSections)
1279     if (Sec->Name == Name)
1280       return Sec;
1281   return nullptr;
1282 }
1283 
1284 static bool needsPtLoad(OutputSection *Sec) {
1285   if (!(Sec->Flags & SHF_ALLOC))
1286     return false;
1287 
1288   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1289   // responsible for allocating space for them, not the PT_LOAD that
1290   // contains the TLS initialization image.
1291   if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
1292     return false;
1293   return true;
1294 }
1295 
1296 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1297 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1298 // RW. This means that there is no alignment in the RO to RX transition and we
1299 // cannot create a PT_LOAD there.
1300 static uint64_t computeFlags(uint64_t Flags) {
1301   if (Config->Omagic)
1302     return PF_R | PF_W | PF_X;
1303   if (Config->SingleRoRx && !(Flags & PF_W))
1304     return Flags | PF_X;
1305   return Flags;
1306 }
1307 
1308 // Decide which program headers to create and which sections to include in each
1309 // one.
1310 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1311   std::vector<PhdrEntry> Ret;
1312   auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1313     Ret.emplace_back(Type, Flags);
1314     return &Ret.back();
1315   };
1316 
1317   // The first phdr entry is PT_PHDR which describes the program header itself.
1318   AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1319 
1320   // PT_INTERP must be the second entry if exists.
1321   if (OutputSection *Sec = findSection(".interp"))
1322     AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
1323 
1324   // Add the first PT_LOAD segment for regular output sections.
1325   uint64_t Flags = computeFlags(PF_R);
1326   PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1327   for (OutputSection *Sec : OutputSections) {
1328     if (!(Sec->Flags & SHF_ALLOC))
1329       break;
1330     if (!needsPtLoad(Sec))
1331       continue;
1332 
1333     // Segments are contiguous memory regions that has the same attributes
1334     // (e.g. executable or writable). There is one phdr for each segment.
1335     // Therefore, we need to create a new phdr when the next section has
1336     // different flags or is loaded at a discontiguous address using AT linker
1337     // script command.
1338     uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1339     if (Script->hasLMA(Sec->Name) || Flags != NewFlags) {
1340       Load = AddHdr(PT_LOAD, NewFlags);
1341       Flags = NewFlags;
1342     }
1343 
1344     Load->add(Sec);
1345   }
1346 
1347   // Add a TLS segment if any.
1348   PhdrEntry TlsHdr(PT_TLS, PF_R);
1349   for (OutputSection *Sec : OutputSections)
1350     if (Sec->Flags & SHF_TLS)
1351       TlsHdr.add(Sec);
1352   if (TlsHdr.First)
1353     Ret.push_back(std::move(TlsHdr));
1354 
1355   // Add an entry for .dynamic.
1356   if (In<ELFT>::DynSymTab)
1357     AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags())
1358         ->add(In<ELFT>::Dynamic->OutSec);
1359 
1360   // PT_GNU_RELRO includes all sections that should be marked as
1361   // read-only by dynamic linker after proccessing relocations.
1362   PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
1363   for (OutputSection *Sec : OutputSections)
1364     if (needsPtLoad(Sec) && isRelroSection<ELFT>(Sec))
1365       RelRo.add(Sec);
1366   if (RelRo.First)
1367     Ret.push_back(std::move(RelRo));
1368 
1369   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1370   if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1371       In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
1372     AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1373         ->add(In<ELFT>::EhFrameHdr->OutSec);
1374 
1375   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1376   // the dynamic linker fill the segment with random data.
1377   if (OutputSection *Sec = findSection(".openbsd.randomdata"))
1378     AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
1379 
1380   // PT_GNU_STACK is a special section to tell the loader to make the
1381   // pages for the stack non-executable. If you really want an executable
1382   // stack, you can pass -z execstack, but that's not recommended for
1383   // security reasons.
1384   unsigned Perm;
1385   if (Config->ZExecstack)
1386     Perm = PF_R | PF_W | PF_X;
1387   else
1388     Perm = PF_R | PF_W;
1389   AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
1390 
1391   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1392   // is expected to perform W^X violations, such as calling mprotect(2) or
1393   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1394   // OpenBSD.
1395   if (Config->ZWxneeded)
1396     AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1397 
1398   // Create one PT_NOTE per a group of contiguous .note sections.
1399   PhdrEntry *Note = nullptr;
1400   for (OutputSection *Sec : OutputSections) {
1401     if (Sec->Type == SHT_NOTE) {
1402       if (!Note || Script->hasLMA(Sec->Name))
1403         Note = AddHdr(PT_NOTE, PF_R);
1404       Note->add(Sec);
1405     } else {
1406       Note = nullptr;
1407     }
1408   }
1409   return Ret;
1410 }
1411 
1412 template <class ELFT>
1413 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
1414   if (Config->EMachine != EM_ARM)
1415     return;
1416   auto I = std::find_if(
1417       OutputSections.begin(), OutputSections.end(),
1418       [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
1419   if (I == OutputSections.end())
1420     return;
1421 
1422   // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
1423   PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
1424   ARMExidx.add(*I);
1425   Phdrs.push_back(ARMExidx);
1426 }
1427 
1428 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1429 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1430 // linker can set the permissions.
1431 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1432   for (const PhdrEntry &P : Phdrs)
1433     if (P.p_type == PT_LOAD && P.First)
1434       P.First->PageAlign = true;
1435 
1436   for (const PhdrEntry &P : Phdrs) {
1437     if (P.p_type != PT_GNU_RELRO)
1438       continue;
1439     if (P.First)
1440       P.First->PageAlign = true;
1441     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1442     // have to align it to a page.
1443     auto End = OutputSections.end();
1444     auto I = std::find(OutputSections.begin(), End, P.Last);
1445     if (I == End || (I + 1) == End)
1446       continue;
1447     OutputSection *Sec = *(I + 1);
1448     if (needsPtLoad(Sec))
1449       Sec->PageAlign = true;
1450   }
1451 }
1452 
1453 bool elf::allocateHeaders(std::vector<PhdrEntry> &Phdrs,
1454                           ArrayRef<OutputSection *> OutputSections,
1455                           uint64_t Min) {
1456   auto FirstPTLoad =
1457       std::find_if(Phdrs.begin(), Phdrs.end(),
1458                    [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1459   if (FirstPTLoad == Phdrs.end())
1460     return false;
1461 
1462   uint64_t HeaderSize = getHeaderSize();
1463   if (HeaderSize > Min) {
1464     auto PhdrI =
1465         std::find_if(Phdrs.begin(), Phdrs.end(),
1466                      [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
1467     if (PhdrI != Phdrs.end())
1468       Phdrs.erase(PhdrI);
1469     return false;
1470   }
1471   Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
1472 
1473   if (!Script->Opt.HasSections)
1474     Config->ImageBase = Min = std::min(Min, Config->ImageBase);
1475 
1476   Out::ElfHeader->Addr = Min;
1477   Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
1478 
1479   if (Script->hasPhdrsCommands())
1480     return true;
1481 
1482   if (FirstPTLoad->First)
1483     for (OutputSection *Sec : OutputSections)
1484       if (Sec->FirstInPtLoad == FirstPTLoad->First)
1485         Sec->FirstInPtLoad = Out::ElfHeader;
1486   FirstPTLoad->First = Out::ElfHeader;
1487   if (!FirstPTLoad->Last)
1488     FirstPTLoad->Last = Out::ProgramHeaders;
1489   return true;
1490 }
1491 
1492 // We should set file offsets and VAs for elf header and program headers
1493 // sections. These are special, we do not include them into output sections
1494 // list, but have them to simplify the code.
1495 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1496   Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1497   // If the script has SECTIONS, assignAddresses will compute the values.
1498   if (Script->Opt.HasSections)
1499     return;
1500 
1501   // When -T<section> option is specified, lower the base to make room for those
1502   // sections.
1503   uint64_t Min = -1;
1504   if (!Config->SectionStartMap.empty())
1505     for (const auto &P : Config->SectionStartMap)
1506       Min = std::min(Min, P.second);
1507 
1508   AllocateHeader = allocateHeaders(Phdrs, OutputSections, Min);
1509 }
1510 
1511 // Assign VAs (addresses at run-time) to output sections.
1512 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1513   uint64_t VA = Config->ImageBase;
1514   uint64_t ThreadBssOffset = 0;
1515 
1516   if (AllocateHeader)
1517     VA += getHeaderSize();
1518 
1519   for (OutputSection *Sec : OutputSections) {
1520     uint32_t Alignment = Sec->Alignment;
1521     if (Sec->PageAlign)
1522       Alignment = std::max<uint32_t>(Alignment, Config->MaxPageSize);
1523 
1524     auto I = Config->SectionStartMap.find(Sec->Name);
1525     if (I != Config->SectionStartMap.end())
1526       VA = I->second;
1527 
1528     // We only assign VAs to allocated sections.
1529     if (needsPtLoad(Sec)) {
1530       VA = alignTo(VA, Alignment);
1531       Sec->Addr = VA;
1532       VA += Sec->Size;
1533     } else if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) {
1534       uint64_t TVA = VA + ThreadBssOffset;
1535       TVA = alignTo(TVA, Alignment);
1536       Sec->Addr = TVA;
1537       ThreadBssOffset = TVA - VA + Sec->Size;
1538     }
1539   }
1540 }
1541 
1542 // Adjusts the file alignment for a given output section and returns
1543 // its new file offset. The file offset must be the same with its
1544 // virtual address (modulo the page size) so that the loader can load
1545 // executables without any address adjustment.
1546 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) {
1547   OutputSection *First = Sec->FirstInPtLoad;
1548   // If the section is not in a PT_LOAD, we just have to align it.
1549   if (!First)
1550     return alignTo(Off, Sec->Alignment);
1551 
1552   // The first section in a PT_LOAD has to have congruent offset and address
1553   // module the page size.
1554   if (Sec == First)
1555     return alignTo(Off, Config->MaxPageSize, Sec->Addr);
1556 
1557   // If two sections share the same PT_LOAD the file offset is calculated
1558   // using this formula: Off2 = Off1 + (VA2 - VA1).
1559   return First->Offset + Sec->Addr - First->Addr;
1560 }
1561 
1562 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) {
1563   if (Sec->Type == SHT_NOBITS) {
1564     Sec->Offset = Off;
1565     return Off;
1566   }
1567 
1568   Off = getFileAlignment(Off, Sec);
1569   Sec->Offset = Off;
1570   return Off + Sec->Size;
1571 }
1572 
1573 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1574   uint64_t Off = 0;
1575   for (OutputSection *Sec : OutputSections)
1576     if (Sec->Flags & SHF_ALLOC)
1577       Off = setOffset(Sec, Off);
1578   FileSize = alignTo(Off, Config->Wordsize);
1579 }
1580 
1581 // Assign file offsets to output sections.
1582 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1583   uint64_t Off = 0;
1584   Off = setOffset(Out::ElfHeader, Off);
1585   Off = setOffset(Out::ProgramHeaders, Off);
1586 
1587   for (OutputSection *Sec : OutputSections)
1588     Off = setOffset(Sec, Off);
1589 
1590   SectionHeaderOff = alignTo(Off, Config->Wordsize);
1591   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1592 }
1593 
1594 // Finalize the program headers. We call this function after we assign
1595 // file offsets and VAs to all sections.
1596 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1597   for (PhdrEntry &P : Phdrs) {
1598     OutputSection *First = P.First;
1599     OutputSection *Last = P.Last;
1600     if (First) {
1601       P.p_filesz = Last->Offset - First->Offset;
1602       if (Last->Type != SHT_NOBITS)
1603         P.p_filesz += Last->Size;
1604       P.p_memsz = Last->Addr + Last->Size - First->Addr;
1605       P.p_offset = First->Offset;
1606       P.p_vaddr = First->Addr;
1607       if (!P.HasLMA)
1608         P.p_paddr = First->getLMA();
1609     }
1610     if (P.p_type == PT_LOAD)
1611       P.p_align = Config->MaxPageSize;
1612     else if (P.p_type == PT_GNU_RELRO) {
1613       P.p_align = 1;
1614       // The glibc dynamic loader rounds the size down, so we need to round up
1615       // to protect the last page. This is a no-op on FreeBSD which always
1616       // rounds up.
1617       P.p_memsz = alignTo(P.p_memsz, Target->PageSize);
1618     }
1619 
1620     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1621     // so round up the size to make sure the offsets are correct.
1622     if (P.p_type == PT_TLS) {
1623       Out::TlsPhdr = &P;
1624       if (P.p_memsz)
1625         P.p_memsz = alignTo(P.p_memsz, P.p_align);
1626     }
1627   }
1628 }
1629 
1630 // The entry point address is chosen in the following ways.
1631 //
1632 // 1. the '-e' entry command-line option;
1633 // 2. the ENTRY(symbol) command in a linker control script;
1634 // 3. the value of the symbol start, if present;
1635 // 4. the address of the first byte of the .text section, if present;
1636 // 5. the address 0.
1637 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() {
1638   // Case 1, 2 or 3. As a special case, if the symbol is actually
1639   // a number, we'll use that number as an address.
1640   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
1641     return B->getVA();
1642   uint64_t Addr;
1643   if (!Config->Entry.getAsInteger(0, Addr))
1644     return Addr;
1645 
1646   // Case 4
1647   if (OutputSection *Sec = findSection(".text")) {
1648     if (Config->WarnMissingEntry)
1649       warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1650            utohexstr(Sec->Addr));
1651     return Sec->Addr;
1652   }
1653 
1654   // Case 5
1655   if (Config->WarnMissingEntry)
1656     warn("cannot find entry symbol " + Config->Entry +
1657          "; not setting start address");
1658   return 0;
1659 }
1660 
1661 static uint16_t getELFType() {
1662   if (Config->Pic)
1663     return ET_DYN;
1664   if (Config->Relocatable)
1665     return ET_REL;
1666   return ET_EXEC;
1667 }
1668 
1669 // This function is called after we have assigned address and size
1670 // to each section. This function fixes some predefined
1671 // symbol values that depend on section address and size.
1672 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
1673   auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
1674                 uint64_t Value) {
1675     if (S1) {
1676       S1->Section = Sec;
1677       S1->Value = Value;
1678     }
1679     if (S2) {
1680       S2->Section = Sec;
1681       S2->Value = Value;
1682     }
1683   };
1684 
1685   // _etext is the first location after the last read-only loadable segment.
1686   // _edata is the first location after the last read-write loadable segment.
1687   // _end is the first location after the uninitialized data region.
1688   PhdrEntry *Last = nullptr;
1689   PhdrEntry *LastRO = nullptr;
1690   PhdrEntry *LastRW = nullptr;
1691   for (PhdrEntry &P : Phdrs) {
1692     if (P.p_type != PT_LOAD)
1693       continue;
1694     Last = &P;
1695     if (P.p_flags & PF_W)
1696       LastRW = &P;
1697     else
1698       LastRO = &P;
1699   }
1700   if (Last)
1701     Set(ElfSym::End1, ElfSym::End2, Last->First, Last->p_memsz);
1702   if (LastRO)
1703     Set(ElfSym::Etext1, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
1704   if (LastRW)
1705     Set(ElfSym::Edata1, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
1706 
1707   if (ElfSym::Bss)
1708     ElfSym::Bss->Section = findSection(".bss");
1709 
1710   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1711   // be equal to the _gp symbol's value.
1712   if (Config->EMachine == EM_MIPS) {
1713     if (!ElfSym::MipsGp->Value) {
1714       // Find GP-relative section with the lowest address
1715       // and use this address to calculate default _gp value.
1716       uint64_t Gp = -1;
1717       for (const OutputSection *OS : OutputSections)
1718         if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1719           Gp = OS->Addr;
1720       if (Gp != (uint64_t)-1)
1721         ElfSym::MipsGp->Value = Gp + 0x7ff0;
1722     }
1723   }
1724 }
1725 
1726 template <class ELFT> void Writer<ELFT>::writeHeader() {
1727   uint8_t *Buf = Buffer->getBufferStart();
1728   memcpy(Buf, "\177ELF", 4);
1729 
1730   // Write the ELF header.
1731   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1732   EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
1733   EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
1734   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1735   EHdr->e_ident[EI_OSABI] = Config->OSABI;
1736   EHdr->e_type = getELFType();
1737   EHdr->e_machine = Config->EMachine;
1738   EHdr->e_version = EV_CURRENT;
1739   EHdr->e_entry = getEntryAddr();
1740   EHdr->e_shoff = SectionHeaderOff;
1741   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1742   EHdr->e_phnum = Phdrs.size();
1743   EHdr->e_shentsize = sizeof(Elf_Shdr);
1744   EHdr->e_shnum = OutputSections.size() + 1;
1745   EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
1746 
1747   if (Config->EMachine == EM_ARM)
1748     // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1749     // but we don't have any firm guarantees of conformance. Linux AArch64
1750     // kernels (as of 2016) require an EABI version to be set.
1751     EHdr->e_flags = EF_ARM_EABI_VER5;
1752   else if (Config->EMachine == EM_MIPS)
1753     EHdr->e_flags = getMipsEFlags<ELFT>();
1754 
1755   if (!Config->Relocatable) {
1756     EHdr->e_phoff = sizeof(Elf_Ehdr);
1757     EHdr->e_phentsize = sizeof(Elf_Phdr);
1758   }
1759 
1760   // Write the program header table.
1761   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1762   for (PhdrEntry &P : Phdrs) {
1763     HBuf->p_type = P.p_type;
1764     HBuf->p_flags = P.p_flags;
1765     HBuf->p_offset = P.p_offset;
1766     HBuf->p_vaddr = P.p_vaddr;
1767     HBuf->p_paddr = P.p_paddr;
1768     HBuf->p_filesz = P.p_filesz;
1769     HBuf->p_memsz = P.p_memsz;
1770     HBuf->p_align = P.p_align;
1771     ++HBuf;
1772   }
1773 
1774   // Write the section header table. Note that the first table entry is null.
1775   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1776   for (OutputSection *Sec : OutputSections)
1777     Sec->writeHeaderTo<ELFT>(++SHdrs);
1778 }
1779 
1780 // Open a result file.
1781 template <class ELFT> void Writer<ELFT>::openFile() {
1782   if (!Config->Is64 && FileSize > UINT32_MAX) {
1783     error("output file too large: " + Twine(FileSize) + " bytes");
1784     return;
1785   }
1786 
1787   unlinkAsync(Config->OutputFile);
1788   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1789       FileOutputBuffer::create(Config->OutputFile, FileSize,
1790                                FileOutputBuffer::F_executable);
1791 
1792   if (auto EC = BufferOrErr.getError())
1793     error("failed to open " + Config->OutputFile + ": " + EC.message());
1794   else
1795     Buffer = std::move(*BufferOrErr);
1796 }
1797 
1798 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1799   uint8_t *Buf = Buffer->getBufferStart();
1800   for (OutputSection *Sec : OutputSections)
1801     if (Sec->Flags & SHF_ALLOC)
1802       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1803 }
1804 
1805 // Write section contents to a mmap'ed file.
1806 template <class ELFT> void Writer<ELFT>::writeSections() {
1807   uint8_t *Buf = Buffer->getBufferStart();
1808 
1809   // PPC64 needs to process relocations in the .opd section
1810   // before processing relocations in code-containing sections.
1811   Out::Opd = findSection(".opd");
1812   if (Out::Opd) {
1813     Out::OpdBuf = Buf + Out::Opd->Offset;
1814     Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
1815   }
1816 
1817   OutputSection *EhFrameHdr =
1818       In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
1819 
1820   // In -r or -emit-relocs mode, write the relocation sections first as in
1821   // ELf_Rel targets we might find out that we need to modify the relocated
1822   // section while doing it.
1823   for (OutputSection *Sec : OutputSections)
1824     if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
1825       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1826 
1827   for (OutputSection *Sec : OutputSections)
1828     if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
1829         Sec->Type != SHT_RELA)
1830       Sec->writeTo<ELFT>(Buf + Sec->Offset);
1831 
1832   // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1833   // it should be written after .eh_frame is written.
1834   if (EhFrameHdr && !EhFrameHdr->Sections.empty())
1835     EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
1836 }
1837 
1838 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1839   if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
1840     return;
1841 
1842   // Compute a hash of all sections of the output file.
1843   uint8_t *Start = Buffer->getBufferStart();
1844   uint8_t *End = Start + FileSize;
1845   In<ELFT>::BuildId->writeBuildId({Start, End});
1846 }
1847 
1848 template void elf::writeResult<ELF32LE>();
1849 template void elf::writeResult<ELF32BE>();
1850 template void elf::writeResult<ELF64LE>();
1851 template void elf::writeResult<ELF64BE>();
1852 
1853 template bool elf::isRelroSection<ELF32LE>(const OutputSection *);
1854 template bool elf::isRelroSection<ELF32BE>(const OutputSection *);
1855 template bool elf::isRelroSection<ELF64LE>(const OutputSection *);
1856 template bool elf::isRelroSection<ELF64BE>(const OutputSection *);
1857