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