]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Writer.cpp
Merge ^/head r306412 through r306905.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Writer.cpp
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 "LinkerScript.h"
13 #include "OutputSections.h"
14 #include "Relocations.h"
15 #include "Strings.h"
16 #include "SymbolTable.h"
17 #include "Target.h"
18
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/FileOutputBuffer.h"
22 #include "llvm/Support/StringSaver.h"
23 #include "llvm/Support/raw_ostream.h"
24
25 using namespace llvm;
26 using namespace llvm::ELF;
27 using namespace llvm::object;
28
29 using namespace lld;
30 using namespace lld::elf;
31
32 namespace {
33 // The writer writes a SymbolTable result to a file.
34 template <class ELFT> class Writer {
35 public:
36   typedef typename ELFT::uint uintX_t;
37   typedef typename ELFT::Shdr Elf_Shdr;
38   typedef typename ELFT::Ehdr Elf_Ehdr;
39   typedef typename ELFT::Phdr Elf_Phdr;
40   typedef typename ELFT::Sym Elf_Sym;
41   typedef typename ELFT::SymRange Elf_Sym_Range;
42   typedef typename ELFT::Rela Elf_Rela;
43   Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
44   void run();
45
46 private:
47   // This describes a program header entry.
48   // Each contains type, access flags and range of output sections that will be
49   // placed in it.
50   struct Phdr {
51     Phdr(unsigned Type, unsigned Flags) {
52       H.p_type = Type;
53       H.p_flags = Flags;
54     }
55     Elf_Phdr H = {};
56     OutputSectionBase<ELFT> *First = nullptr;
57     OutputSectionBase<ELFT> *Last = nullptr;
58   };
59
60   void copyLocalSymbols();
61   void addReservedSymbols();
62   void createSections();
63   void addPredefinedSections();
64   bool needsGot();
65
66   void createPhdrs();
67   void assignAddresses();
68   void assignFileOffsets();
69   void setPhdrs();
70   void fixHeaders();
71   void fixSectionAlignments();
72   void fixAbsoluteSymbols();
73   void openFile();
74   void writeHeader();
75   void writeSections();
76   void writeBuildId();
77   bool needsInterpSection() const {
78     return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
79   }
80   bool isOutputDynamic() const {
81     return !Symtab.getSharedFiles().empty() || Config->Pic;
82   }
83
84   void addCommonSymbols(std::vector<DefinedCommon *> &Syms);
85
86   std::unique_ptr<FileOutputBuffer> Buffer;
87
88   BumpPtrAllocator Alloc;
89   std::vector<OutputSectionBase<ELFT> *> OutputSections;
90   std::vector<std::unique_ptr<OutputSectionBase<ELFT>>> OwningSections;
91
92   void addRelIpltSymbols();
93   void addStartEndSymbols();
94   void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
95
96   SymbolTable<ELFT> &Symtab;
97   std::vector<Phdr> Phdrs;
98
99   uintX_t FileSize;
100   uintX_t SectionHeaderOff;
101 };
102 } // anonymous namespace
103
104 template <class ELFT>
105 StringRef elf::getOutputSectionName(InputSectionBase<ELFT> *S) {
106   StringRef Dest = Script<ELFT>::X->getOutputSection(S);
107   if (!Dest.empty())
108     return Dest;
109
110   StringRef Name = S->getSectionName();
111   for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
112                       ".init_array.", ".fini_array.", ".ctors.", ".dtors.",
113                       ".tbss.", ".gcc_except_table.", ".tdata."})
114     if (Name.startswith(V))
115       return V.drop_back();
116   return Name;
117 }
118
119 template <class ELFT>
120 void elf::reportDiscarded(InputSectionBase<ELFT> *IS,
121                           const std::unique_ptr<elf::ObjectFile<ELFT>> &File) {
122   if (!Config->PrintGcSections || !IS || IS->Live)
123     return;
124   errs() << "removing unused section from '" << IS->getSectionName()
125          << "' in file '" << File->getName() << "'\n";
126 }
127
128 template <class ELFT> void elf::writeResult(SymbolTable<ELFT> *Symtab) {
129   typedef typename ELFT::uint uintX_t;
130   typedef typename ELFT::Ehdr Elf_Ehdr;
131
132   // Create singleton output sections.
133   OutputSection<ELFT> Bss(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
134   DynamicSection<ELFT> Dynamic;
135   EhOutputSection<ELFT> EhFrame;
136   GotSection<ELFT> Got;
137   InterpSection<ELFT> Interp;
138   PltSection<ELFT> Plt;
139   RelocationSection<ELFT> RelaDyn(Config->Rela ? ".rela.dyn" : ".rel.dyn",
140                                   Config->ZCombreloc);
141   StringTableSection<ELFT> DynStrTab(".dynstr", true);
142   StringTableSection<ELFT> ShStrTab(".shstrtab", false);
143   SymbolTableSection<ELFT> DynSymTab(DynStrTab);
144   VersionTableSection<ELFT> VerSym;
145   VersionNeedSection<ELFT> VerNeed;
146
147   OutputSectionBase<ELFT> ElfHeader("", 0, SHF_ALLOC);
148   ElfHeader.setSize(sizeof(Elf_Ehdr));
149   OutputSectionBase<ELFT> ProgramHeaders("", 0, SHF_ALLOC);
150   ProgramHeaders.updateAlignment(sizeof(uintX_t));
151
152   // Instantiate optional output sections if they are needed.
153   std::unique_ptr<BuildIdSection<ELFT>> BuildId;
154   std::unique_ptr<EhFrameHeader<ELFT>> EhFrameHdr;
155   std::unique_ptr<GnuHashTableSection<ELFT>> GnuHashTab;
156   std::unique_ptr<GotPltSection<ELFT>> GotPlt;
157   std::unique_ptr<HashTableSection<ELFT>> HashTab;
158   std::unique_ptr<RelocationSection<ELFT>> RelaPlt;
159   std::unique_ptr<StringTableSection<ELFT>> StrTab;
160   std::unique_ptr<SymbolTableSection<ELFT>> SymTabSec;
161   std::unique_ptr<OutputSection<ELFT>> MipsRldMap;
162   std::unique_ptr<VersionDefinitionSection<ELFT>> VerDef;
163
164   if (Config->BuildId == BuildIdKind::Fnv1)
165     BuildId.reset(new BuildIdFnv1<ELFT>);
166   else if (Config->BuildId == BuildIdKind::Md5)
167     BuildId.reset(new BuildIdMd5<ELFT>);
168   else if (Config->BuildId == BuildIdKind::Sha1)
169     BuildId.reset(new BuildIdSha1<ELFT>);
170   else if (Config->BuildId == BuildIdKind::Hexstring)
171     BuildId.reset(new BuildIdHexstring<ELFT>);
172
173   if (Config->EhFrameHdr)
174     EhFrameHdr.reset(new EhFrameHeader<ELFT>);
175
176   if (Config->GnuHash)
177     GnuHashTab.reset(new GnuHashTableSection<ELFT>);
178   if (Config->SysvHash)
179     HashTab.reset(new HashTableSection<ELFT>);
180   StringRef S = Config->Rela ? ".rela.plt" : ".rel.plt";
181   GotPlt.reset(new GotPltSection<ELFT>);
182   RelaPlt.reset(new RelocationSection<ELFT>(S, false /*Sort*/));
183   if (!Config->StripAll) {
184     StrTab.reset(new StringTableSection<ELFT>(".strtab", false));
185     SymTabSec.reset(new SymbolTableSection<ELFT>(*StrTab));
186   }
187   if (Config->EMachine == EM_MIPS && !Config->Shared) {
188     // This is a MIPS specific section to hold a space within the data segment
189     // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
190     // See "Dynamic section" in Chapter 5 in the following document:
191     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
192     MipsRldMap.reset(new OutputSection<ELFT>(".rld_map", SHT_PROGBITS,
193                                              SHF_ALLOC | SHF_WRITE));
194     MipsRldMap->setSize(sizeof(uintX_t));
195     MipsRldMap->updateAlignment(sizeof(uintX_t));
196   }
197   if (!Config->VersionDefinitions.empty())
198     VerDef.reset(new VersionDefinitionSection<ELFT>());
199
200   Out<ELFT>::Bss = &Bss;
201   Out<ELFT>::BuildId = BuildId.get();
202   Out<ELFT>::DynStrTab = &DynStrTab;
203   Out<ELFT>::DynSymTab = &DynSymTab;
204   Out<ELFT>::Dynamic = &Dynamic;
205   Out<ELFT>::EhFrame = &EhFrame;
206   Out<ELFT>::EhFrameHdr = EhFrameHdr.get();
207   Out<ELFT>::GnuHashTab = GnuHashTab.get();
208   Out<ELFT>::Got = &Got;
209   Out<ELFT>::GotPlt = GotPlt.get();
210   Out<ELFT>::HashTab = HashTab.get();
211   Out<ELFT>::Interp = &Interp;
212   Out<ELFT>::Plt = &Plt;
213   Out<ELFT>::RelaDyn = &RelaDyn;
214   Out<ELFT>::RelaPlt = RelaPlt.get();
215   Out<ELFT>::ShStrTab = &ShStrTab;
216   Out<ELFT>::StrTab = StrTab.get();
217   Out<ELFT>::SymTab = SymTabSec.get();
218   Out<ELFT>::VerDef = VerDef.get();
219   Out<ELFT>::VerSym = &VerSym;
220   Out<ELFT>::VerNeed = &VerNeed;
221   Out<ELFT>::MipsRldMap = MipsRldMap.get();
222   Out<ELFT>::Opd = nullptr;
223   Out<ELFT>::OpdBuf = nullptr;
224   Out<ELFT>::TlsPhdr = nullptr;
225   Out<ELFT>::ElfHeader = &ElfHeader;
226   Out<ELFT>::ProgramHeaders = &ProgramHeaders;
227
228   Writer<ELFT>(*Symtab).run();
229 }
230
231 // The main function of the writer.
232 template <class ELFT> void Writer<ELFT>::run() {
233   if (!Config->DiscardAll)
234     copyLocalSymbols();
235   addReservedSymbols();
236   createSections();
237   if (HasError)
238     return;
239
240   if (Config->Relocatable) {
241     assignFileOffsets();
242   } else {
243     createPhdrs();
244     fixHeaders();
245     if (ScriptConfig->DoLayout) {
246       Script<ELFT>::X->assignAddresses(OutputSections);
247     } else {
248       fixSectionAlignments();
249       assignAddresses();
250     }
251     assignFileOffsets();
252     setPhdrs();
253     fixAbsoluteSymbols();
254   }
255
256   openFile();
257   if (HasError)
258     return;
259   writeHeader();
260   writeSections();
261   writeBuildId();
262   if (HasError)
263     return;
264   if (auto EC = Buffer->commit())
265     error(EC, "failed to write to the output file");
266 }
267
268 template <class ELFT>
269 static void reportUndefined(SymbolTable<ELFT> &Symtab, SymbolBody *Sym) {
270   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
271     return;
272
273   if (Config->Shared && Sym->symbol()->Visibility == STV_DEFAULT &&
274       Config->UnresolvedSymbols != UnresolvedPolicy::NoUndef)
275     return;
276
277   std::string Msg = "undefined symbol: " + Sym->getName().str();
278   if (Sym->File)
279     Msg += " in " + getFilename(Sym->File);
280   if (Config->UnresolvedSymbols == UnresolvedPolicy::Warn)
281     warning(Msg);
282   else
283     error(Msg);
284 }
285
286 template <class ELFT>
287 static bool shouldKeepInSymtab(InputSectionBase<ELFT> *Sec, StringRef SymName,
288                                const SymbolBody &B) {
289   if (B.isFile())
290     return false;
291
292   // We keep sections in symtab for relocatable output.
293   if (B.isSection())
294     return Config->Relocatable;
295
296   // If sym references a section in a discarded group, don't keep it.
297   if (Sec == &InputSection<ELFT>::Discarded)
298     return false;
299
300   if (Config->DiscardNone)
301     return true;
302
303   // In ELF assembly .L symbols are normally discarded by the assembler.
304   // If the assembler fails to do so, the linker discards them if
305   // * --discard-locals is used.
306   // * The symbol is in a SHF_MERGE section, which is normally the reason for
307   //   the assembler keeping the .L symbol.
308   if (!SymName.startswith(".L") && !SymName.empty())
309     return true;
310
311   if (Config->DiscardLocals)
312     return false;
313
314   return !(Sec->getSectionHdr()->sh_flags & SHF_MERGE);
315 }
316
317 template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
318   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
319     return false;
320
321   if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
322     // Always include absolute symbols.
323     if (!D->Section)
324       return true;
325     // Exclude symbols pointing to garbage-collected sections.
326     if (!D->Section->Live)
327       return false;
328     if (auto *S = dyn_cast<MergeInputSection<ELFT>>(D->Section))
329       if (!S->getSectionPiece(D->Value)->Live)
330         return false;
331   }
332   return true;
333 }
334
335 // Local symbols are not in the linker's symbol table. This function scans
336 // each object file's symbol table to copy local symbols to the output.
337 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
338   if (!Out<ELFT>::SymTab)
339     return;
340   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
341        Symtab.getObjectFiles()) {
342     const char *StrTab = F->getStringTable().data();
343     for (SymbolBody *B : F->getLocalSymbols()) {
344       auto *DR = dyn_cast<DefinedRegular<ELFT>>(B);
345       // No reason to keep local undefined symbol in symtab.
346       if (!DR)
347         continue;
348       if (!includeInSymtab<ELFT>(*B))
349         continue;
350       StringRef SymName(StrTab + B->getNameOffset());
351       InputSectionBase<ELFT> *Sec = DR->Section;
352       if (!shouldKeepInSymtab<ELFT>(Sec, SymName, *B))
353         continue;
354       ++Out<ELFT>::SymTab->NumLocals;
355       if (Config->Relocatable)
356         B->DynsymIndex = Out<ELFT>::SymTab->NumLocals;
357       F->KeptLocalSyms.push_back(
358           std::make_pair(DR, Out<ELFT>::SymTab->StrTabSec.addString(SymName)));
359     }
360   }
361 }
362
363 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
364 // we would like to make sure appear is a specific order to maximize their
365 // coverage by a single signed 16-bit offset from the TOC base pointer.
366 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
367 // sections. This will put it next to the loaded special PPC64 sections (and,
368 // thus, within reach of the TOC base pointer).
369 static int getPPC64SectionRank(StringRef SectionName) {
370   return StringSwitch<int>(SectionName)
371       .Case(".tocbss", 0)
372       .Case(".branch_lt", 2)
373       .Case(".toc", 3)
374       .Case(".toc1", 4)
375       .Case(".opd", 5)
376       .Default(1);
377 }
378
379 template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) {
380   if (!Config->ZRelro)
381     return false;
382   typename ELFT::uint Flags = Sec->getFlags();
383   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
384     return false;
385   if (Flags & SHF_TLS)
386     return true;
387   uint32_t Type = Sec->getType();
388   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
389       Type == SHT_PREINIT_ARRAY)
390     return true;
391   if (Sec == Out<ELFT>::GotPlt)
392     return Config->ZNow;
393   if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got)
394     return true;
395   StringRef S = Sec->getName();
396   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
397          S == ".eh_frame";
398 }
399
400 // Output section ordering is determined by this function.
401 template <class ELFT>
402 static bool compareSections(OutputSectionBase<ELFT> *A,
403                             OutputSectionBase<ELFT> *B) {
404   typedef typename ELFT::uint uintX_t;
405
406   int Comp = Script<ELFT>::X->compareSections(A->getName(), B->getName());
407   if (Comp != 0)
408     return Comp < 0;
409
410   uintX_t AFlags = A->getFlags();
411   uintX_t BFlags = B->getFlags();
412
413   // Allocatable sections go first to reduce the total PT_LOAD size and
414   // so debug info doesn't change addresses in actual code.
415   bool AIsAlloc = AFlags & SHF_ALLOC;
416   bool BIsAlloc = BFlags & SHF_ALLOC;
417   if (AIsAlloc != BIsAlloc)
418     return AIsAlloc;
419
420   // We don't have any special requirements for the relative order of
421   // two non allocatable sections.
422   if (!AIsAlloc)
423     return false;
424
425   // We want the read only sections first so that they go in the PT_LOAD
426   // covering the program headers at the start of the file.
427   bool AIsWritable = AFlags & SHF_WRITE;
428   bool BIsWritable = BFlags & SHF_WRITE;
429   if (AIsWritable != BIsWritable)
430     return BIsWritable;
431
432   // For a corresponding reason, put non exec sections first (the program
433   // header PT_LOAD is not executable).
434   bool AIsExec = AFlags & SHF_EXECINSTR;
435   bool BIsExec = BFlags & SHF_EXECINSTR;
436   if (AIsExec != BIsExec)
437     return BIsExec;
438
439   // If we got here we know that both A and B are in the same PT_LOAD.
440
441   // The TLS initialization block needs to be a single contiguous block in a R/W
442   // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
443   // sections are placed here as they don't take up virtual address space in the
444   // PT_LOAD.
445   bool AIsTls = AFlags & SHF_TLS;
446   bool BIsTls = BFlags & SHF_TLS;
447   if (AIsTls != BIsTls)
448     return AIsTls;
449
450   // The next requirement we have is to put nobits sections last. The
451   // reason is that the only thing the dynamic linker will see about
452   // them is a p_memsz that is larger than p_filesz. Seeing that it
453   // zeros the end of the PT_LOAD, so that has to correspond to the
454   // nobits sections.
455   bool AIsNoBits = A->getType() == SHT_NOBITS;
456   bool BIsNoBits = B->getType() == SHT_NOBITS;
457   if (AIsNoBits != BIsNoBits)
458     return BIsNoBits;
459
460   // We place RelRo section before plain r/w ones.
461   bool AIsRelRo = isRelroSection(A);
462   bool BIsRelRo = isRelroSection(B);
463   if (AIsRelRo != BIsRelRo)
464     return AIsRelRo;
465
466   // Some architectures have additional ordering restrictions for sections
467   // within the same PT_LOAD.
468   if (Config->EMachine == EM_PPC64)
469     return getPPC64SectionRank(A->getName()) <
470            getPPC64SectionRank(B->getName());
471
472   return false;
473 }
474
475 // Until this function is called, common symbols do not belong to any section.
476 // This function adds them to end of BSS section.
477 template <class ELFT>
478 void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) {
479   if (Syms.empty())
480     return;
481
482   // Sort the common symbols by alignment as an heuristic to pack them better.
483   std::stable_sort(Syms.begin(), Syms.end(),
484                    [](const DefinedCommon *A, const DefinedCommon *B) {
485                      return A->Alignment > B->Alignment;
486                    });
487
488   uintX_t Off = Out<ELFT>::Bss->getSize();
489   for (DefinedCommon *C : Syms) {
490     Off = alignTo(Off, C->Alignment);
491     Out<ELFT>::Bss->updateAlignment(C->Alignment);
492     C->OffsetInBss = Off;
493     Off += C->Size;
494   }
495
496   Out<ELFT>::Bss->setSize(Off);
497 }
498
499 template <class ELFT>
500 static Symbol *addOptionalSynthetic(SymbolTable<ELFT> &Table, StringRef Name,
501                                     OutputSectionBase<ELFT> *Sec,
502                                     typename ELFT::uint Val) {
503   SymbolBody *S = Table.find(Name);
504   if (!S)
505     return nullptr;
506   if (!S->isUndefined() && !S->isShared())
507     return S->symbol();
508   return Table.addSynthetic(Name, Sec, Val);
509 }
510
511 // The beginning and the ending of .rel[a].plt section are marked
512 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
513 // executable. The runtime needs these symbols in order to resolve
514 // all IRELATIVE relocs on startup. For dynamic executables, we don't
515 // need these symbols, since IRELATIVE relocs are resolved through GOT
516 // and PLT. For details, see http://www.airs.com/blog/archives/403.
517 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
518   if (isOutputDynamic() || !Out<ELFT>::RelaPlt)
519     return;
520   StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
521   addOptionalSynthetic(Symtab, S, Out<ELFT>::RelaPlt, 0);
522
523   S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
524   addOptionalSynthetic(Symtab, S, Out<ELFT>::RelaPlt,
525                        DefinedSynthetic<ELFT>::SectionEnd);
526 }
527
528 // The linker is expected to define some symbols depending on
529 // the linking result. This function defines such symbols.
530 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
531   if (Config->EMachine == EM_MIPS) {
532     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
533     // so that it points to an absolute address which is relative to GOT.
534     // See "Global Data Symbols" in Chapter 6 in the following document:
535     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
536     Symtab.addSynthetic("_gp", Out<ELFT>::Got, MipsGPOffset);
537
538     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
539     // start of function and 'gp' pointer into GOT.
540     Symbol *Sym =
541         addOptionalSynthetic(Symtab, "_gp_disp", Out<ELFT>::Got, MipsGPOffset);
542     if (Sym)
543       ElfSym<ELFT>::MipsGpDisp = Sym->body();
544
545     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
546     // pointer. This symbol is used in the code generated by .cpload pseudo-op
547     // in case of using -mno-shared option.
548     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
549     addOptionalSynthetic(Symtab, "__gnu_local_gp", Out<ELFT>::Got,
550                          MipsGPOffset);
551   }
552
553   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
554   // is magical and is used to produce a R_386_GOTPC relocation.
555   // The R_386_GOTPC relocation value doesn't actually depend on the
556   // symbol value, so it could use an index of STN_UNDEF which, according
557   // to the spec, means the symbol value is 0.
558   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
559   // the object file.
560   // The situation is even stranger on x86_64 where the assembly doesn't
561   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
562   // an undefined symbol in the .o files.
563   // Given that the symbol is effectively unused, we just create a dummy
564   // hidden one to avoid the undefined symbol error.
565   if (!Config->Relocatable)
566     Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_");
567
568   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
569   // static linking the linker is required to optimize away any references to
570   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
571   // to avoid the undefined symbol error.
572   if (!isOutputDynamic())
573     Symtab.addIgnored("__tls_get_addr");
574
575   auto Define = [this](StringRef S, DefinedRegular<ELFT> *&Sym1,
576                        DefinedRegular<ELFT> *&Sym2) {
577     Sym1 = Symtab.addIgnored(S, STV_DEFAULT);
578
579     // The name without the underscore is not a reserved name,
580     // so it is defined only when there is a reference against it.
581     assert(S.startswith("_"));
582     S = S.substr(1);
583     if (SymbolBody *B = Symtab.find(S))
584       if (B->isUndefined())
585         Sym2 = Symtab.addAbsolute(S, STV_DEFAULT);
586   };
587
588   Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
589   Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
590   Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
591 }
592
593 // Sort input sections by section name suffixes for
594 // __attribute__((init_priority(N))).
595 template <class ELFT> static void sortInitFini(OutputSectionBase<ELFT> *S) {
596   if (S)
597     reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
598 }
599
600 // Sort input sections by the special rule for .ctors and .dtors.
601 template <class ELFT> static void sortCtorsDtors(OutputSectionBase<ELFT> *S) {
602   if (S)
603     reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
604 }
605
606 // Create output section objects and add them to OutputSections.
607 template <class ELFT> void Writer<ELFT>::createSections() {
608   // Create output sections for input object file sections.
609   std::vector<OutputSectionBase<ELFT> *> RegularSections;
610   OutputSectionFactory<ELFT> Factory;
611   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
612        Symtab.getObjectFiles()) {
613     for (InputSectionBase<ELFT> *C : F->getSections()) {
614       if (isDiscarded(C)) {
615         reportDiscarded(C, F);
616         continue;
617       }
618       OutputSectionBase<ELFT> *Sec;
619       bool IsNew;
620       std::tie(Sec, IsNew) = Factory.create(C, getOutputSectionName(C));
621       if (IsNew) {
622         OwningSections.emplace_back(Sec);
623         OutputSections.push_back(Sec);
624         RegularSections.push_back(Sec);
625       }
626       Sec->addSection(C);
627     }
628   }
629
630   // If we have a .opd section (used under PPC64 for function descriptors),
631   // store a pointer to it here so that we can use it later when processing
632   // relocations.
633   Out<ELFT>::Opd = Factory.lookup(".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC);
634
635   Out<ELFT>::Dynamic->PreInitArraySec = Factory.lookup(
636       ".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC);
637   Out<ELFT>::Dynamic->InitArraySec =
638       Factory.lookup(".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC);
639   Out<ELFT>::Dynamic->FiniArraySec =
640       Factory.lookup(".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC);
641
642   // Sort section contents for __attribute__((init_priority(N)).
643   sortInitFini(Out<ELFT>::Dynamic->InitArraySec);
644   sortInitFini(Out<ELFT>::Dynamic->FiniArraySec);
645   sortCtorsDtors(Factory.lookup(".ctors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
646   sortCtorsDtors(Factory.lookup(".dtors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
647
648   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
649   // symbols for sections, so that the runtime can get the start and end
650   // addresses of each section by section name. Add such symbols.
651   if (!Config->Relocatable) {
652     addStartEndSymbols();
653     for (OutputSectionBase<ELFT> *Sec : RegularSections)
654       addStartStopSymbols(Sec);
655   }
656
657   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
658   // It should be okay as no one seems to care about the type.
659   // Even the author of gold doesn't remember why gold behaves that way.
660   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
661   if (isOutputDynamic())
662     Symtab.addSynthetic("_DYNAMIC", Out<ELFT>::Dynamic, 0);
663
664   // Define __rel[a]_iplt_{start,end} symbols if needed.
665   addRelIpltSymbols();
666
667   // Add scripted symbols with zero values now.
668   // Real values will be assigned later
669   Script<ELFT>::X->addScriptedSymbols();
670
671   if (!Out<ELFT>::EhFrame->empty()) {
672     OutputSections.push_back(Out<ELFT>::EhFrame);
673     Out<ELFT>::EhFrame->finalize();
674   }
675
676   // Scan relocations. This must be done after every symbol is declared so that
677   // we can correctly decide if a dynamic relocation is needed.
678   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
679        Symtab.getObjectFiles()) {
680     for (InputSectionBase<ELFT> *C : F->getSections()) {
681       if (isDiscarded(C))
682         continue;
683       if (auto *S = dyn_cast<InputSection<ELFT>>(C)) {
684         scanRelocations(*S);
685         continue;
686       }
687       if (auto *S = dyn_cast<EhInputSection<ELFT>>(C))
688         if (S->RelocSection)
689           scanRelocations(*S, *S->RelocSection);
690     }
691   }
692
693   for (OutputSectionBase<ELFT> *Sec : OutputSections)
694     Sec->assignOffsets();
695
696   // Now that we have defined all possible symbols including linker-
697   // synthesized ones. Visit all symbols to give the finishing touches.
698   std::vector<DefinedCommon *> CommonSymbols;
699   for (Symbol *S : Symtab.getSymbols()) {
700     SymbolBody *Body = S->body();
701
702     // We only report undefined symbols in regular objects. This means that we
703     // will accept an undefined reference in bitcode if it can be optimized out.
704     if (S->IsUsedInRegularObj && Body->isUndefined() && !S->isWeak())
705       reportUndefined<ELFT>(Symtab, Body);
706
707     if (auto *C = dyn_cast<DefinedCommon>(Body))
708       CommonSymbols.push_back(C);
709
710     if (!includeInSymtab<ELFT>(*Body))
711       continue;
712     if (Out<ELFT>::SymTab)
713       Out<ELFT>::SymTab->addSymbol(Body);
714
715     if (isOutputDynamic() && S->includeInDynsym()) {
716       Out<ELFT>::DynSymTab->addSymbol(Body);
717       if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
718         if (SS->file()->isNeeded())
719           Out<ELFT>::VerNeed->addSymbol(SS);
720     }
721   }
722
723   // Do not proceed if there was an undefined symbol.
724   if (HasError)
725     return;
726
727   addCommonSymbols(CommonSymbols);
728
729   // So far we have added sections from input object files.
730   // This function adds linker-created Out<ELFT>::* sections.
731   addPredefinedSections();
732
733   std::stable_sort(OutputSections.begin(), OutputSections.end(),
734                    compareSections<ELFT>);
735
736   unsigned I = 1;
737   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
738     Sec->SectionIndex = I++;
739     Sec->setSHName(Out<ELFT>::ShStrTab->addString(Sec->getName()));
740   }
741
742   // Finalizers fix each section's size.
743   // .dynsym is finalized early since that may fill up .gnu.hash.
744   if (isOutputDynamic())
745     Out<ELFT>::DynSymTab->finalize();
746
747   // Fill other section headers. The dynamic table is finalized
748   // at the end because some tags like RELSZ depend on result
749   // of finalizing other sections. The dynamic string table is
750   // finalized once the .dynamic finalizer has added a few last
751   // strings. See DynamicSection::finalize()
752   for (OutputSectionBase<ELFT> *Sec : OutputSections)
753     if (Sec != Out<ELFT>::DynStrTab && Sec != Out<ELFT>::Dynamic)
754       Sec->finalize();
755
756   if (isOutputDynamic())
757     Out<ELFT>::Dynamic->finalize();
758
759   // Now that all output offsets are fixed. Finalize mergeable sections
760   // to fix their maps from input offsets to output offsets.
761   for (OutputSectionBase<ELFT> *Sec : OutputSections)
762     Sec->finalizePieces();
763 }
764
765 template <class ELFT> bool Writer<ELFT>::needsGot() {
766   if (!Out<ELFT>::Got->empty())
767     return true;
768
769   // We add the .got section to the result for dynamic MIPS target because
770   // its address and properties are mentioned in the .dynamic section.
771   if (Config->EMachine == EM_MIPS)
772     return true;
773
774   // If we have a relocation that is relative to GOT (such as GOTOFFREL),
775   // we need to emit a GOT even if it's empty.
776   return Out<ELFT>::Got->HasGotOffRel;
777 }
778
779 // This function add Out<ELFT>::* sections to OutputSections.
780 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
781   auto Add = [&](OutputSectionBase<ELFT> *C) {
782     if (C)
783       OutputSections.push_back(C);
784   };
785
786   // A core file does not usually contain unmodified segments except
787   // the first page of the executable. Add the build ID section to beginning of
788   // the file so that the section is included in the first page.
789   if (Out<ELFT>::BuildId)
790     OutputSections.insert(OutputSections.begin(), Out<ELFT>::BuildId);
791
792   // Add .interp at first because some loaders want to see that section
793   // on the first page of the executable file when loaded into memory.
794   if (needsInterpSection())
795     OutputSections.insert(OutputSections.begin(), Out<ELFT>::Interp);
796
797   // This order is not the same as the final output order
798   // because we sort the sections using their attributes below.
799   Add(Out<ELFT>::SymTab);
800   Add(Out<ELFT>::ShStrTab);
801   Add(Out<ELFT>::StrTab);
802   if (isOutputDynamic()) {
803     Add(Out<ELFT>::DynSymTab);
804
805     bool HasVerNeed = Out<ELFT>::VerNeed->getNeedNum() != 0;
806     if (Out<ELFT>::VerDef || HasVerNeed)
807       Add(Out<ELFT>::VerSym);
808     Add(Out<ELFT>::VerDef);
809     if (HasVerNeed)
810       Add(Out<ELFT>::VerNeed);
811
812     Add(Out<ELFT>::GnuHashTab);
813     Add(Out<ELFT>::HashTab);
814     Add(Out<ELFT>::Dynamic);
815     Add(Out<ELFT>::DynStrTab);
816     if (Out<ELFT>::RelaDyn->hasRelocs())
817       Add(Out<ELFT>::RelaDyn);
818     Add(Out<ELFT>::MipsRldMap);
819   }
820
821   // We always need to add rel[a].plt to output if it has entries.
822   // Even during static linking it can contain R_[*]_IRELATIVE relocations.
823   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
824     Add(Out<ELFT>::RelaPlt);
825     Out<ELFT>::RelaPlt->Static = !isOutputDynamic();
826   }
827
828   if (needsGot())
829     Add(Out<ELFT>::Got);
830   if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty())
831     Add(Out<ELFT>::GotPlt);
832   if (!Out<ELFT>::Plt->empty())
833     Add(Out<ELFT>::Plt);
834   if (!Out<ELFT>::EhFrame->empty())
835     Add(Out<ELFT>::EhFrameHdr);
836   if (Out<ELFT>::Bss->getSize() > 0)
837     Add(Out<ELFT>::Bss);
838 }
839
840 // The linker is expected to define SECNAME_start and SECNAME_end
841 // symbols for a few sections. This function defines them.
842 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
843   auto Define = [&](StringRef Start, StringRef End,
844                     OutputSectionBase<ELFT> *OS) {
845     if (OS) {
846       this->Symtab.addSynthetic(Start, OS, 0);
847       this->Symtab.addSynthetic(End, OS, DefinedSynthetic<ELFT>::SectionEnd);
848     } else {
849       addOptionalSynthetic(this->Symtab, Start,
850                            (OutputSectionBase<ELFT> *)nullptr, 0);
851       addOptionalSynthetic(this->Symtab, End,
852                            (OutputSectionBase<ELFT> *)nullptr, 0);
853     }
854   };
855
856   Define("__preinit_array_start", "__preinit_array_end",
857          Out<ELFT>::Dynamic->PreInitArraySec);
858   Define("__init_array_start", "__init_array_end",
859          Out<ELFT>::Dynamic->InitArraySec);
860   Define("__fini_array_start", "__fini_array_end",
861          Out<ELFT>::Dynamic->FiniArraySec);
862 }
863
864 // If a section name is valid as a C identifier (which is rare because of
865 // the leading '.'), linkers are expected to define __start_<secname> and
866 // __stop_<secname> symbols. They are at beginning and end of the section,
867 // respectively. This is not requested by the ELF standard, but GNU ld and
868 // gold provide the feature, and used by many programs.
869 template <class ELFT>
870 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) {
871   StringRef S = Sec->getName();
872   if (!isValidCIdentifier(S))
873     return;
874   StringSaver Saver(Alloc);
875   StringRef Start = Saver.save("__start_" + S);
876   StringRef Stop = Saver.save("__stop_" + S);
877   if (SymbolBody *B = Symtab.find(Start))
878     if (B->isUndefined())
879       Symtab.addSynthetic(Start, Sec, 0);
880   if (SymbolBody *B = Symtab.find(Stop))
881     if (B->isUndefined())
882       Symtab.addSynthetic(Stop, Sec, DefinedSynthetic<ELFT>::SectionEnd);
883 }
884
885 template <class ELFT> static bool needsPtLoad(OutputSectionBase<ELFT> *Sec) {
886   if (!(Sec->getFlags() & SHF_ALLOC))
887     return false;
888
889   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
890   // responsible for allocating space for them, not the PT_LOAD that
891   // contains the TLS initialization image.
892   if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS)
893     return false;
894   return true;
895 }
896
897 static uint32_t toPhdrFlags(uint64_t Flags) {
898   uint32_t Ret = PF_R;
899   if (Flags & SHF_WRITE)
900     Ret |= PF_W;
901   if (Flags & SHF_EXECINSTR)
902     Ret |= PF_X;
903   return Ret;
904 }
905
906 // Decide which program headers to create and which sections to include in each
907 // one.
908 template <class ELFT> void Writer<ELFT>::createPhdrs() {
909   auto AddHdr = [this](unsigned Type, unsigned Flags) {
910     return &*Phdrs.emplace(Phdrs.end(), Type, Flags);
911   };
912
913   auto AddSec = [](Phdr &Hdr, OutputSectionBase<ELFT> *Sec) {
914     Hdr.Last = Sec;
915     if (!Hdr.First)
916       Hdr.First = Sec;
917     Hdr.H.p_align = std::max<uintX_t>(Hdr.H.p_align, Sec->getAlignment());
918   };
919
920   // The first phdr entry is PT_PHDR which describes the program header itself.
921   Phdr &Hdr = *AddHdr(PT_PHDR, PF_R);
922   AddSec(Hdr, Out<ELFT>::ProgramHeaders);
923
924   // PT_INTERP must be the second entry if exists.
925   if (needsInterpSection()) {
926     Phdr &Hdr = *AddHdr(PT_INTERP, toPhdrFlags(Out<ELFT>::Interp->getFlags()));
927     AddSec(Hdr, Out<ELFT>::Interp);
928   }
929
930   // Add the first PT_LOAD segment for regular output sections.
931   uintX_t Flags = PF_R;
932   Phdr *Load = AddHdr(PT_LOAD, Flags);
933   AddSec(*Load, Out<ELFT>::ElfHeader);
934   AddSec(*Load, Out<ELFT>::ProgramHeaders);
935
936   Phdr TlsHdr(PT_TLS, PF_R);
937   Phdr RelRo(PT_GNU_RELRO, PF_R);
938   Phdr Note(PT_NOTE, PF_R);
939   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
940     if (!(Sec->getFlags() & SHF_ALLOC))
941       break;
942
943     // If we meet TLS section then we create TLS header
944     // and put all TLS sections inside for futher use when
945     // assign addresses.
946     if (Sec->getFlags() & SHF_TLS)
947       AddSec(TlsHdr, Sec);
948
949     if (!needsPtLoad<ELFT>(Sec))
950       continue;
951
952     // If flags changed then we want new load segment.
953     uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
954     if (Flags != NewFlags) {
955       Load = AddHdr(PT_LOAD, NewFlags);
956       Flags = NewFlags;
957     }
958
959     AddSec(*Load, Sec);
960
961     if (isRelroSection(Sec))
962       AddSec(RelRo, Sec);
963     if (Sec->getType() == SHT_NOTE)
964       AddSec(Note, Sec);
965   }
966
967   // Add the TLS segment unless it's empty.
968   if (TlsHdr.First)
969     Phdrs.push_back(std::move(TlsHdr));
970
971   // Add an entry for .dynamic.
972   if (isOutputDynamic()) {
973     Phdr &H = *AddHdr(PT_DYNAMIC, toPhdrFlags(Out<ELFT>::Dynamic->getFlags()));
974     AddSec(H, Out<ELFT>::Dynamic);
975   }
976
977   // PT_GNU_RELRO includes all sections that should be marked as
978   // read-only by dynamic linker after proccessing relocations.
979   if (RelRo.First)
980     Phdrs.push_back(std::move(RelRo));
981
982   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
983   if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
984     Phdr &Hdr = *AddHdr(PT_GNU_EH_FRAME,
985                         toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags()));
986     AddSec(Hdr, Out<ELFT>::EhFrameHdr);
987   }
988
989   // PT_GNU_STACK is a special section to tell the loader to make the
990   // pages for the stack non-executable.
991   if (!Config->ZExecStack)
992     AddHdr(PT_GNU_STACK, PF_R | PF_W);
993
994   if (Note.First)
995     Phdrs.push_back(std::move(Note));
996
997   Out<ELFT>::ProgramHeaders->setSize(sizeof(Elf_Phdr) * Phdrs.size());
998 }
999
1000 // The first section of each PT_LOAD and the first section after PT_GNU_RELRO
1001 // have to be page aligned so that the dynamic linker can set the permissions.
1002 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1003   for (const Phdr &P : Phdrs)
1004     if (P.H.p_type == PT_LOAD)
1005       P.First->PageAlign = true;
1006
1007   for (const Phdr &P : Phdrs) {
1008     if (P.H.p_type != PT_GNU_RELRO)
1009       continue;
1010     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1011     // have to align it to a page.
1012     auto End = OutputSections.end();
1013     auto I = std::find(OutputSections.begin(), End, P.Last);
1014     if (I == End || (I + 1) == End)
1015       continue;
1016     OutputSectionBase<ELFT> *Sec = *(I + 1);
1017     if (needsPtLoad(Sec))
1018       Sec->PageAlign = true;
1019   }
1020 }
1021
1022 // We should set file offsets and VAs for elf header and program headers
1023 // sections. These are special, we do not include them into output sections
1024 // list, but have them to simplify the code.
1025 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1026   uintX_t BaseVA = ScriptConfig->DoLayout ? 0 : Config->ImageBase;
1027   Out<ELFT>::ElfHeader->setVA(BaseVA);
1028   uintX_t Off = Out<ELFT>::ElfHeader->getSize();
1029   Out<ELFT>::ProgramHeaders->setVA(Off + BaseVA);
1030 }
1031
1032 // Assign VAs (addresses at run-time) to output sections.
1033 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1034   uintX_t VA = Config->ImageBase + Out<ELFT>::ElfHeader->getSize() +
1035                Out<ELFT>::ProgramHeaders->getSize();
1036
1037   uintX_t ThreadBssOffset = 0;
1038   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1039     uintX_t Alignment = Sec->getAlignment();
1040     if (Sec->PageAlign)
1041       Alignment = std::max<uintX_t>(Alignment, Target->PageSize);
1042
1043     // We only assign VAs to allocated sections.
1044     if (needsPtLoad<ELFT>(Sec)) {
1045       VA = alignTo(VA, Alignment);
1046       Sec->setVA(VA);
1047       VA += Sec->getSize();
1048     } else if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS) {
1049       uintX_t TVA = VA + ThreadBssOffset;
1050       TVA = alignTo(TVA, Alignment);
1051       Sec->setVA(TVA);
1052       ThreadBssOffset = TVA - VA + Sec->getSize();
1053     }
1054   }
1055 }
1056
1057 // Adjusts the file alignment for a given output section and returns
1058 // its new file offset. The file offset must be the same with its
1059 // virtual address (modulo the page size) so that the loader can load
1060 // executables without any address adjustment.
1061 template <class ELFT, class uintX_t>
1062 static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase<ELFT> *Sec) {
1063   uintX_t Alignment = Sec->getAlignment();
1064   if (Sec->PageAlign)
1065     Alignment = std::max<uintX_t>(Alignment, Target->PageSize);
1066   Off = alignTo(Off, Alignment);
1067
1068   // Relocatable output does not have program headers
1069   // and does not need any other offset adjusting.
1070   if (Config->Relocatable || !(Sec->getFlags() & SHF_ALLOC))
1071     return Off;
1072   return alignTo(Off, Target->PageSize, Sec->getVA());
1073 }
1074
1075 // Assign file offsets to output sections.
1076 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1077   uintX_t Off = 0;
1078
1079   auto Set = [&](OutputSectionBase<ELFT> *Sec) {
1080     if (Sec->getType() == SHT_NOBITS) {
1081       Sec->setFileOffset(Off);
1082       return;
1083     }
1084
1085     Off = getFileAlignment<ELFT>(Off, Sec);
1086     Sec->setFileOffset(Off);
1087     Off += Sec->getSize();
1088   };
1089
1090   Set(Out<ELFT>::ElfHeader);
1091   Set(Out<ELFT>::ProgramHeaders);
1092   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1093     Set(Sec);
1094
1095   SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
1096   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1097 }
1098
1099 // Finalize the program headers. We call this function after we assign
1100 // file offsets and VAs to all sections.
1101 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1102   for (Phdr &P : Phdrs) {
1103     Elf_Phdr &H = P.H;
1104     OutputSectionBase<ELFT> *First = P.First;
1105     OutputSectionBase<ELFT> *Last = P.Last;
1106     if (First) {
1107       H.p_filesz = Last->getFileOff() - First->getFileOff();
1108       if (Last->getType() != SHT_NOBITS)
1109         H.p_filesz += Last->getSize();
1110       H.p_memsz = Last->getVA() + Last->getSize() - First->getVA();
1111       H.p_offset = First->getFileOff();
1112       H.p_vaddr = First->getVA();
1113     }
1114     if (H.p_type == PT_LOAD)
1115       H.p_align = Target->PageSize;
1116     else if (H.p_type == PT_GNU_RELRO)
1117       H.p_align = 1;
1118     H.p_paddr = H.p_vaddr;
1119
1120     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1121     // so round up the size to make sure the offsets are correct.
1122     if (H.p_type == PT_TLS) {
1123       Out<ELFT>::TlsPhdr = &H;
1124       H.p_memsz = alignTo(H.p_memsz, H.p_align);
1125     }
1126   }
1127 }
1128
1129 static uint32_t getMipsEFlags(bool Is64Bits) {
1130   // FIXME: In fact ELF flags depends on ELF flags of input object files
1131   // and selected emulation. For now just use hard coded values.
1132   if (Is64Bits)
1133     return EF_MIPS_CPIC | EF_MIPS_PIC | EF_MIPS_ARCH_64R2;
1134
1135   uint32_t V = EF_MIPS_CPIC | EF_MIPS_ABI_O32 | EF_MIPS_ARCH_32R2;
1136   if (Config->Shared)
1137     V |= EF_MIPS_PIC;
1138   return V;
1139 }
1140
1141 template <class ELFT> static typename ELFT::uint getEntryAddr() {
1142   if (Symbol *S = Config->EntrySym)
1143     return S->body()->getVA<ELFT>();
1144   if (Config->EntryAddr != uint64_t(-1))
1145     return Config->EntryAddr;
1146   return 0;
1147 }
1148
1149 template <class ELFT> static uint8_t getELFEncoding() {
1150   if (ELFT::TargetEndianness == llvm::support::little)
1151     return ELFDATA2LSB;
1152   return ELFDATA2MSB;
1153 }
1154
1155 static uint16_t getELFType() {
1156   if (Config->Pic)
1157     return ET_DYN;
1158   if (Config->Relocatable)
1159     return ET_REL;
1160   return ET_EXEC;
1161 }
1162
1163 // This function is called after we have assigned address and size
1164 // to each section. This function fixes some predefined absolute
1165 // symbol values that depend on section address and size.
1166 template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
1167   auto Set = [](DefinedRegular<ELFT> *S1, DefinedRegular<ELFT> *S2, uintX_t V) {
1168     if (S1)
1169       S1->Value = V;
1170     if (S2)
1171       S2->Value = V;
1172   };
1173
1174   // _etext is the first location after the last read-only loadable segment.
1175   // _edata is the first location after the last read-write loadable segment.
1176   // _end is the first location after the uninitialized data region.
1177   for (Phdr &P : Phdrs) {
1178     Elf_Phdr &H = P.H;
1179     if (H.p_type != PT_LOAD)
1180       continue;
1181     Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, H.p_vaddr + H.p_memsz);
1182
1183     uintX_t Val = H.p_vaddr + H.p_filesz;
1184     if (H.p_flags & PF_W)
1185       Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, Val);
1186     else
1187       Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, Val);
1188   }
1189 }
1190
1191 template <class ELFT> void Writer<ELFT>::writeHeader() {
1192   uint8_t *Buf = Buffer->getBufferStart();
1193   memcpy(Buf, "\177ELF", 4);
1194
1195   auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
1196
1197   // Write the ELF header.
1198   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1199   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1200   EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1201   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1202   EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
1203   EHdr->e_type = getELFType();
1204   EHdr->e_machine = FirstObj.EMachine;
1205   EHdr->e_version = EV_CURRENT;
1206   EHdr->e_entry = getEntryAddr<ELFT>();
1207   EHdr->e_shoff = SectionHeaderOff;
1208   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1209   EHdr->e_phnum = Phdrs.size();
1210   EHdr->e_shentsize = sizeof(Elf_Shdr);
1211   EHdr->e_shnum = OutputSections.size() + 1;
1212   EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex;
1213
1214   if (Config->EMachine == EM_MIPS)
1215     EHdr->e_flags = getMipsEFlags(ELFT::Is64Bits);
1216
1217   if (!Config->Relocatable) {
1218     EHdr->e_phoff = sizeof(Elf_Ehdr);
1219     EHdr->e_phentsize = sizeof(Elf_Phdr);
1220   }
1221
1222   // Write the program header table.
1223   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1224   for (Phdr &P : Phdrs)
1225     *HBuf++ = P.H;
1226
1227   // Write the section header table. Note that the first table entry is null.
1228   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1229   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1230     Sec->writeHeaderTo(++SHdrs);
1231 }
1232
1233 template <class ELFT> void Writer<ELFT>::openFile() {
1234   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1235       FileOutputBuffer::create(Config->OutputFile, FileSize,
1236                                FileOutputBuffer::F_executable);
1237   if (auto EC = BufferOrErr.getError())
1238     error(EC, "failed to open " + Config->OutputFile);
1239   else
1240     Buffer = std::move(*BufferOrErr);
1241 }
1242
1243 // Write section contents to a mmap'ed file.
1244 template <class ELFT> void Writer<ELFT>::writeSections() {
1245   uint8_t *Buf = Buffer->getBufferStart();
1246
1247   // PPC64 needs to process relocations in the .opd section before processing
1248   // relocations in code-containing sections.
1249   if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) {
1250     Out<ELFT>::OpdBuf = Buf + Sec->getFileOff();
1251     Sec->writeTo(Buf + Sec->getFileOff());
1252   }
1253
1254   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1255     if (Sec != Out<ELFT>::Opd)
1256       Sec->writeTo(Buf + Sec->getFileOff());
1257 }
1258
1259 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1260   if (!Out<ELFT>::BuildId)
1261     return;
1262
1263   // Compute a hash of all sections except .debug_* sections.
1264   // We skip debug sections because they tend to be very large
1265   // and their contents are very likely to be the same as long as
1266   // other sections are the same.
1267   uint8_t *Start = Buffer->getBufferStart();
1268   uint8_t *Last = Start;
1269   std::vector<ArrayRef<uint8_t>> Regions;
1270   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1271     uint8_t *End = Start + Sec->getFileOff();
1272     if (!Sec->getName().startswith(".debug_"))
1273       Regions.push_back({Last, End});
1274     Last = End;
1275   }
1276   Regions.push_back({Last, Start + FileSize});
1277   Out<ELFT>::BuildId->writeBuildId(Regions);
1278 }
1279
1280 template void elf::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab);
1281 template void elf::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab);
1282 template void elf::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab);
1283 template void elf::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);