xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision 74468a5b)
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 "SymbolTable.h"
15 #include "Target.h"
16 
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Support/Endian.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 using namespace llvm::support::endian;
29 
30 using namespace lld;
31 using namespace lld::elf;
32 
33 namespace {
34 // The writer writes a SymbolTable result to a file.
35 template <class ELFT> class Writer {
36 public:
37   typedef typename ELFT::uint uintX_t;
38   typedef typename ELFT::Shdr Elf_Shdr;
39   typedef typename ELFT::Ehdr Elf_Ehdr;
40   typedef typename ELFT::Phdr Elf_Phdr;
41   typedef typename ELFT::Sym Elf_Sym;
42   typedef typename ELFT::SymRange Elf_Sym_Range;
43   typedef typename ELFT::Rela Elf_Rela;
44   Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
45   void run();
46 
47 private:
48   // This describes a program header entry.
49   // Each contains type, access flags and range of output sections that will be
50   // placed in it.
51   struct Phdr {
52     Phdr(unsigned Type, unsigned Flags) {
53       H.p_type = Type;
54       H.p_flags = Flags;
55     }
56     Elf_Phdr H = {};
57     OutputSectionBase<ELFT> *First = nullptr;
58     OutputSectionBase<ELFT> *Last = nullptr;
59   };
60 
61   void copyLocalSymbols();
62   void addReservedSymbols();
63   void createSections();
64   void addPredefinedSections();
65   bool needsGot();
66 
67   template <class RelTy>
68   void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels);
69 
70   void scanRelocs(InputSection<ELFT> &C);
71   void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec);
72   RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &S,
73                      bool IsWrite, RelExpr Expr, uint32_t Type);
74   template <class RelTy>
75   uintX_t computeAddend(const elf::ObjectFile<ELFT> &File,
76                         const uint8_t *SectionData, const RelTy *End,
77                         const RelTy &RI, RelExpr Expr, SymbolBody &Body);
78   void createPhdrs();
79   void assignAddresses();
80   void assignFileOffsets();
81   void setPhdrs();
82   void fixHeaders();
83   void fixSectionAlignments();
84   void fixAbsoluteSymbols();
85   void openFile();
86   void writeHeader();
87   void writeSections();
88   void writeBuildId();
89   bool isDiscarded(InputSectionBase<ELFT> *IS) const;
90   StringRef getOutputSectionName(InputSectionBase<ELFT> *S) const;
91   bool needsInterpSection() const {
92     return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
93   }
94   bool isOutputDynamic() const {
95     return !Symtab.getSharedFiles().empty() || Config->Pic;
96   }
97   template <class RelTy>
98   void scanRelocsForThunks(const elf::ObjectFile<ELFT> &File,
99                            ArrayRef<RelTy> Rels);
100 
101   void ensureBss();
102   void addCommonSymbols(std::vector<DefinedCommon *> &Syms);
103   void addCopyRelSymbol(SharedSymbol<ELFT> *Sym);
104 
105   std::unique_ptr<llvm::FileOutputBuffer> Buffer;
106 
107   BumpPtrAllocator Alloc;
108   std::vector<OutputSectionBase<ELFT> *> OutputSections;
109   std::vector<std::unique_ptr<OutputSectionBase<ELFT>>> OwningSections;
110 
111   void addRelIpltSymbols();
112   void addStartEndSymbols();
113   void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
114 
115   SymbolTable<ELFT> &Symtab;
116   std::vector<Phdr> Phdrs;
117 
118   uintX_t FileSize;
119   uintX_t SectionHeaderOff;
120 
121   // Flag to force GOT to be in output if we have relocations
122   // that relies on its address.
123   bool HasGotOffRel = false;
124 };
125 } // anonymous namespace
126 
127 template <class ELFT> void elf::writeResult(SymbolTable<ELFT> *Symtab) {
128   typedef typename ELFT::uint uintX_t;
129   typedef typename ELFT::Ehdr Elf_Ehdr;
130 
131   // Create singleton output sections.
132   DynamicSection<ELFT> Dynamic(*Symtab);
133   EhFrameHeader<ELFT> EhFrameHdr;
134   GotSection<ELFT> Got;
135   InterpSection<ELFT> Interp;
136   PltSection<ELFT> Plt;
137   RelocationSection<ELFT> RelaDyn(Config->Rela ? ".rela.dyn" : ".rel.dyn",
138                                   Config->ZCombreloc);
139   StringTableSection<ELFT> DynStrTab(".dynstr", true);
140   StringTableSection<ELFT> ShStrTab(".shstrtab", false);
141   SymbolTableSection<ELFT> DynSymTab(*Symtab, DynStrTab);
142   VersionTableSection<ELFT> VerSym;
143   VersionNeedSection<ELFT> VerNeed;
144 
145   OutputSectionBase<ELFT> ElfHeader("", 0, SHF_ALLOC);
146   ElfHeader.setSize(sizeof(Elf_Ehdr));
147   OutputSectionBase<ELFT> ProgramHeaders("", 0, SHF_ALLOC);
148   ProgramHeaders.updateAlign(sizeof(uintX_t));
149 
150   // Instantiate optional output sections if they are needed.
151   std::unique_ptr<BuildIdSection<ELFT>> BuildId;
152   std::unique_ptr<GnuHashTableSection<ELFT>> GnuHashTab;
153   std::unique_ptr<GotPltSection<ELFT>> GotPlt;
154   std::unique_ptr<HashTableSection<ELFT>> HashTab;
155   std::unique_ptr<RelocationSection<ELFT>> RelaPlt;
156   std::unique_ptr<StringTableSection<ELFT>> StrTab;
157   std::unique_ptr<SymbolTableSection<ELFT>> SymTabSec;
158   std::unique_ptr<OutputSection<ELFT>> MipsRldMap;
159 
160   if (Config->BuildId == BuildIdKind::Fnv1)
161     BuildId.reset(new BuildIdFnv1<ELFT>);
162   else if (Config->BuildId == BuildIdKind::Md5)
163     BuildId.reset(new BuildIdMd5<ELFT>);
164   else if (Config->BuildId == BuildIdKind::Sha1)
165     BuildId.reset(new BuildIdSha1<ELFT>);
166   else if (Config->BuildId == BuildIdKind::Hexstring)
167     BuildId.reset(new BuildIdHexstring<ELFT>);
168 
169   if (Config->GnuHash)
170     GnuHashTab.reset(new GnuHashTableSection<ELFT>);
171   if (Config->SysvHash)
172     HashTab.reset(new HashTableSection<ELFT>);
173   StringRef S = Config->Rela ? ".rela.plt" : ".rel.plt";
174   GotPlt.reset(new GotPltSection<ELFT>);
175   RelaPlt.reset(new RelocationSection<ELFT>(S, false /*Sort*/));
176   if (!Config->StripAll) {
177     StrTab.reset(new StringTableSection<ELFT>(".strtab", false));
178     SymTabSec.reset(new SymbolTableSection<ELFT>(*Symtab, *StrTab));
179   }
180   if (Config->EMachine == EM_MIPS && !Config->Shared) {
181     // This is a MIPS specific section to hold a space within the data segment
182     // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
183     // See "Dynamic section" in Chapter 5 in the following document:
184     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
185     MipsRldMap.reset(new OutputSection<ELFT>(".rld_map", SHT_PROGBITS,
186                                              SHF_ALLOC | SHF_WRITE));
187     MipsRldMap->setSize(sizeof(uintX_t));
188     MipsRldMap->updateAlign(sizeof(uintX_t));
189   }
190 
191   Out<ELFT>::BuildId = BuildId.get();
192   Out<ELFT>::DynStrTab = &DynStrTab;
193   Out<ELFT>::DynSymTab = &DynSymTab;
194   Out<ELFT>::Dynamic = &Dynamic;
195   Out<ELFT>::EhFrameHdr = &EhFrameHdr;
196   Out<ELFT>::GnuHashTab = GnuHashTab.get();
197   Out<ELFT>::Got = &Got;
198   Out<ELFT>::GotPlt = GotPlt.get();
199   Out<ELFT>::HashTab = HashTab.get();
200   Out<ELFT>::Interp = &Interp;
201   Out<ELFT>::Plt = &Plt;
202   Out<ELFT>::RelaDyn = &RelaDyn;
203   Out<ELFT>::RelaPlt = RelaPlt.get();
204   Out<ELFT>::ShStrTab = &ShStrTab;
205   Out<ELFT>::StrTab = StrTab.get();
206   Out<ELFT>::SymTab = SymTabSec.get();
207   Out<ELFT>::VerSym = &VerSym;
208   Out<ELFT>::VerNeed = &VerNeed;
209   Out<ELFT>::Bss = nullptr;
210   Out<ELFT>::MipsRldMap = MipsRldMap.get();
211   Out<ELFT>::Opd = nullptr;
212   Out<ELFT>::OpdBuf = nullptr;
213   Out<ELFT>::TlsPhdr = nullptr;
214   Out<ELFT>::ElfHeader = &ElfHeader;
215   Out<ELFT>::ProgramHeaders = &ProgramHeaders;
216 
217   Writer<ELFT>(*Symtab).run();
218 }
219 
220 // The main function of the writer.
221 template <class ELFT> void Writer<ELFT>::run() {
222   if (!Config->DiscardAll)
223     copyLocalSymbols();
224   addReservedSymbols();
225   createSections();
226   if (HasError)
227     return;
228 
229   if (Config->Relocatable) {
230     assignFileOffsets();
231   } else {
232     createPhdrs();
233     fixHeaders();
234     if (ScriptConfig->DoLayout) {
235       Script<ELFT>::X->assignAddresses(OutputSections);
236     } else {
237       fixSectionAlignments();
238       assignAddresses();
239     }
240     assignFileOffsets();
241     setPhdrs();
242     fixAbsoluteSymbols();
243   }
244 
245   openFile();
246   if (HasError)
247     return;
248   writeHeader();
249   writeSections();
250   writeBuildId();
251   if (HasError)
252     return;
253   check(Buffer->commit());
254 }
255 
256 namespace {
257 template <bool Is64Bits> struct SectionKey {
258   typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
259   StringRef Name;
260   uint32_t Type;
261   uintX_t Flags;
262   uintX_t Alignment;
263 };
264 }
265 namespace llvm {
266 template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
267   static SectionKey<Is64Bits> getEmptyKey() {
268     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0,
269                                 0};
270   }
271   static SectionKey<Is64Bits> getTombstoneKey() {
272     return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
273                                 0, 0};
274   }
275   static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
276     return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
277   }
278   static bool isEqual(const SectionKey<Is64Bits> &LHS,
279                       const SectionKey<Is64Bits> &RHS) {
280     return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
281            LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
282            LHS.Alignment == RHS.Alignment;
283   }
284 };
285 }
286 
287 // Returns the number of relocations processed.
288 template <class ELFT>
289 static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
290                                     InputSectionBase<ELFT> &C,
291                                     typename ELFT::uint Offset,
292                                     typename ELFT::uint Addend, RelExpr Expr) {
293   if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
294     return 0;
295 
296   if (!Body.isTls())
297     return 0;
298 
299   typedef typename ELFT::uint uintX_t;
300   if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
301     // Local-Dynamic relocs can be relaxed to Local-Exec.
302     if (!Config->Shared) {
303       C.Relocations.push_back(
304           {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
305       return 2;
306     }
307     if (Out<ELFT>::Got->addTlsIndex())
308       Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
309                                     Out<ELFT>::Got->getTlsIndexOff(), false,
310                                     nullptr, 0});
311     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
312     return 1;
313   }
314 
315   // Local-Dynamic relocs can be relaxed to Local-Exec.
316   if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
317     C.Relocations.push_back(
318         {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
319     return 1;
320   }
321 
322   if (Target->isTlsGlobalDynamicRel(Type)) {
323     if (Config->Shared) {
324       if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
325         uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
326         Out<ELFT>::RelaDyn->addReloc(
327             {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
328         Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
329                                       Off + (uintX_t)sizeof(uintX_t), false,
330                                       &Body, 0});
331       }
332       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
333       return 1;
334     }
335 
336     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
337     // depending on the symbol being locally defined or not.
338     if (Body.isPreemptible()) {
339       C.Relocations.push_back(
340           {R_RELAX_TLS_GD_TO_IE, Type, Offset, Addend, &Body});
341       if (!Body.isInGot()) {
342         Out<ELFT>::Got->addEntry(Body);
343         Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
344                                       Body.getGotOffset<ELFT>(), false, &Body,
345                                       0});
346       }
347       return 2;
348     }
349     C.Relocations.push_back(
350         {R_RELAX_TLS_GD_TO_LE, Type, Offset, Addend, &Body});
351     return Target->TlsGdToLeSkip;
352   }
353 
354   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
355   // defined.
356   if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
357       !Body.isPreemptible()) {
358     C.Relocations.push_back(
359         {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
360     return 1;
361   }
362   return 0;
363 }
364 
365 // Some targets might require creation of thunks for relocations. Now we
366 // support only MIPS which requires LA25 thunk to call PIC code from non-PIC
367 // one. Scan relocations to find each one requires thunk.
368 template <class ELFT>
369 template <class RelTy>
370 void Writer<ELFT>::scanRelocsForThunks(const elf::ObjectFile<ELFT> &File,
371                                        ArrayRef<RelTy> Rels) {
372   for (const RelTy &RI : Rels) {
373     uint32_t Type = RI.getType(Config->Mips64EL);
374     SymbolBody &Body = File.getRelocTargetSym(RI);
375     if (Body.hasThunk() || !Target->needsThunk(Type, File, Body))
376       continue;
377     auto *D = cast<DefinedRegular<ELFT>>(&Body);
378     auto *S = cast<InputSection<ELFT>>(D->Section);
379     S->addThunk(Body);
380   }
381 }
382 
383 template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
384   return read32<E>(Loc) & 0xffff;
385 }
386 
387 template <class RelTy>
388 static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
389   switch (Rel->getType(Config->Mips64EL)) {
390   case R_MIPS_HI16:
391     return R_MIPS_LO16;
392   case R_MIPS_GOT16:
393     return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
394   case R_MIPS_PCHI16:
395     return R_MIPS_PCLO16;
396   case R_MICROMIPS_HI16:
397     return R_MICROMIPS_LO16;
398   default:
399     return R_MIPS_NONE;
400   }
401 }
402 
403 template <class ELFT, class RelTy>
404 static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
405                                     SymbolBody &Sym, const RelTy *Rel,
406                                     const RelTy *End) {
407   uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
408   uint32_t Type = getMipsPairType(Rel, Sym);
409 
410   // Some MIPS relocations use addend calculated from addend of the relocation
411   // itself and addend of paired relocation. ABI requires to compute such
412   // combined addend in case of REL relocation record format only.
413   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
414   if (RelTy::IsRela || Type == R_MIPS_NONE)
415     return 0;
416 
417   for (const RelTy *RI = Rel; RI != End; ++RI) {
418     if (RI->getType(Config->Mips64EL) != Type)
419       continue;
420     if (RI->getSymbol(Config->Mips64EL) != SymIndex)
421       continue;
422     const endianness E = ELFT::TargetEndianness;
423     return ((read32<E>(BufLoc) & 0xffff) << 16) +
424            readSignedLo16<E>(Buf + RI->r_offset);
425   }
426   unsigned OldType = Rel->getType(Config->Mips64EL);
427   StringRef OldName = getELFRelocationTypeName(Config->EMachine, OldType);
428   StringRef NewName = getELFRelocationTypeName(Config->EMachine, Type);
429   warning("can't find matching " + NewName + " relocation for " + OldName);
430   return 0;
431 }
432 
433 // True if non-preemptable symbol always has the same value regardless of where
434 // the DSO is loaded.
435 template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
436   if (Body.isUndefined())
437     return !Body.isLocal() && Body.symbol()->isWeak();
438   if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
439     return DR->Section == nullptr; // Absolute symbol.
440   return false;
441 }
442 
443 static bool needsPlt(RelExpr Expr) {
444   return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT;
445 }
446 
447 // True if this expression is of the form Sym - X, where X is a position in the
448 // file (PC, or GOT for example).
449 static bool isRelExpr(RelExpr Expr) {
450   return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC;
451 }
452 
453 template <class ELFT>
454 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
455                                      const SymbolBody &Body) {
456   // These expressions always compute a constant
457   if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
458       E == R_MIPS_GOT_LOCAL || E == R_MIPS_GOT_LOCAL_PAGE ||
459       E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
460       E == R_TLSGD || E == R_PPC_PLT_OPD)
461     return true;
462 
463   // These never do, except if the entire file is position dependent or if
464   // only the low bits are used.
465   if (E == R_GOT || E == R_PLT)
466     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
467 
468   if (Body.isPreemptible())
469     return false;
470 
471   if (!Config->Pic)
472     return true;
473 
474   bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
475   bool RelE = isRelExpr(E);
476   if (AbsVal && !RelE)
477     return true;
478   if (!AbsVal && RelE)
479     return true;
480 
481   // Relative relocation to an absolute value. This is normally unrepresentable,
482   // but if the relocation refers to a weak undefined symbol, we allow it to
483   // resolve to the image base. This is a little strange, but it allows us to
484   // link function calls to such symbols. Normally such a call will be guarded
485   // with a comparison, which will load a zero from the GOT.
486   if (AbsVal && RelE) {
487     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
488       return true;
489     StringRef S = getELFRelocationTypeName(Config->EMachine, Type);
490     error("relocation " + S + " cannot refer to absolute symbol " +
491           Body.getName());
492     return true;
493   }
494 
495   return Target->usesOnlyLowPageBits(Type);
496 }
497 
498 static RelExpr toPlt(RelExpr Expr) {
499   if (Expr == R_PPC_OPD)
500     return R_PPC_PLT_OPD;
501   if (Expr == R_PC)
502     return R_PLT_PC;
503   if (Expr == R_ABS)
504     return R_PLT;
505   return Expr;
506 }
507 
508 static RelExpr fromPlt(RelExpr Expr) {
509   // We decided not to use a plt. Optimize a reference to the plt to a
510   // reference to the symbol itself.
511   if (Expr == R_PLT_PC)
512     return R_PC;
513   if (Expr == R_PPC_PLT_OPD)
514     return R_PPC_OPD;
515   if (Expr == R_PLT)
516     return R_ABS;
517   return Expr;
518 }
519 
520 template <class ELFT>
521 RelExpr Writer<ELFT>::adjustExpr(const elf::ObjectFile<ELFT> &File,
522                                  SymbolBody &Body, bool IsWrite, RelExpr Expr,
523                                  uint32_t Type) {
524   if (Target->needsThunk(Type, File, Body))
525     return R_THUNK;
526   bool Preemptible = Body.isPreemptible();
527   if (Body.isGnuIFunc())
528     Expr = toPlt(Expr);
529   else if (needsPlt(Expr) && !Preemptible)
530     Expr = fromPlt(Expr);
531 
532   if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
533     return Expr;
534 
535   // This relocation would require the dynamic linker to write a value to read
536   // only memory. We can hack around it if we are producing an executable and
537   // the refered symbol can be preemepted to refer to the executable.
538   if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
539     StringRef S = getELFRelocationTypeName(Config->EMachine, Type);
540     error("relocation " + S + " cannot be used when making a shared "
541                               "object; recompile with -fPIC.");
542     return Expr;
543   }
544   if (Body.getVisibility() != STV_DEFAULT) {
545     error("Cannot preempt symbol");
546     return Expr;
547   }
548   if (Body.isObject()) {
549     // Produce a copy relocation.
550     auto *B = cast<SharedSymbol<ELFT>>(&Body);
551     if (!B->needsCopy())
552       addCopyRelSymbol(B);
553     return Expr;
554   }
555   if (Body.isFunc()) {
556     // This handles a non PIC program call to function in a shared library. In
557     // an ideal world, we could just report an error saying the relocation can
558     // overflow at runtime. In the real world with glibc, crt1.o has a
559     // R_X86_64_PC32 pointing to libc.so.
560     //
561     // The general idea on how to handle such cases is to create a PLT entry and
562     // use that as the function value.
563     //
564     // For the static linking part, we just return a plt expr and everything
565     // else will use the the PLT entry as the address.
566     //
567     // The remaining problem is making sure pointer equality still works. We
568     // need the help of the dynamic linker for that. We let it know that we have
569     // a direct reference to a so symbol by creating an undefined symbol with a
570     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
571     // the value of the symbol we created. This is true even for got entries, so
572     // pointer equality is maintained. To avoid an infinite loop, the only entry
573     // that points to the real function is a dedicated got entry used by the
574     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
575     // R_386_JMP_SLOT, etc).
576     Body.NeedsCopyOrPltAddr = true;
577     return toPlt(Expr);
578   }
579   error("Symbol is missing type");
580 
581   return Expr;
582 }
583 
584 template <class ELFT>
585 template <class RelTy>
586 typename ELFT::uint
587 Writer<ELFT>::computeAddend(const elf::ObjectFile<ELFT> &File,
588                             const uint8_t *SectionData, const RelTy *End,
589                             const RelTy &RI, RelExpr Expr, SymbolBody &Body) {
590   uint32_t Type = RI.getType(Config->Mips64EL);
591   uintX_t Addend = getAddend<ELFT>(RI);
592   const uint8_t *BufLoc = SectionData + RI.r_offset;
593   if (!RelTy::IsRela)
594     Addend += Target->getImplicitAddend(BufLoc, Type);
595   if (Config->EMachine == EM_MIPS) {
596     Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
597     if (Type == R_MIPS_LO16 && Expr == R_PC)
598       // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
599       // symbol. In that case we should use the following formula for
600       // calculation "AHL + GP - P + 4". Let's add 4 right here.
601       // For details see p. 4-19 at
602       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
603       Addend += 4;
604     if (Expr == R_GOT_OFF)
605       Addend -= MipsGPOffset;
606     if (Expr == R_GOTREL) {
607       Addend -= MipsGPOffset;
608       if (Body.isLocal())
609         Addend += File.getMipsGp0();
610     }
611   }
612   if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
613     Addend += getPPC64TocBase();
614   return Addend;
615 }
616 
617 // The reason we have to do this early scan is as follows
618 // * To mmap the output file, we need to know the size
619 // * For that, we need to know how many dynamic relocs we will have.
620 // It might be possible to avoid this by outputting the file with write:
621 // * Write the allocated output sections, computing addresses.
622 // * Apply relocations, recording which ones require a dynamic reloc.
623 // * Write the dynamic relocations.
624 // * Write the rest of the file.
625 // This would have some drawbacks. For example, we would only know if .rela.dyn
626 // is needed after applying relocations. If it is, it will go after rw and rx
627 // sections. Given that it is ro, we will need an extra PT_LOAD. This
628 // complicates things for the dynamic linker and means we would have to reserve
629 // space for the extra PT_LOAD even if we end up not using it.
630 template <class ELFT>
631 template <class RelTy>
632 void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
633   uintX_t Flags = C.getSectionHdr()->sh_flags;
634   bool IsWrite = Flags & SHF_WRITE;
635 
636   auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
637     Out<ELFT>::RelaDyn->addReloc(Reloc);
638   };
639 
640   const elf::ObjectFile<ELFT> &File = *C.getFile();
641   ArrayRef<uint8_t> SectionData = C.getSectionData();
642   const uint8_t *Buf = SectionData.begin();
643   for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
644     const RelTy &RI = *I;
645     SymbolBody &Body = File.getRelocTargetSym(RI);
646     uint32_t Type = RI.getType(Config->Mips64EL);
647 
648     RelExpr Expr = Target->getRelExpr(Type, Body);
649     // Ignore "hint" relocation because it is for optional code optimization.
650     if (Expr == R_HINT)
651       continue;
652 
653     uintX_t Offset = C.getOffset(RI.r_offset);
654     if (Offset == (uintX_t)-1)
655       continue;
656 
657     bool Preemptible = Body.isPreemptible();
658     Expr = adjustExpr(File, Body, IsWrite, Expr, Type);
659     if (HasError)
660       continue;
661 
662     // This relocation does not require got entry, but it is relative to got and
663     // needs it to be created. Here we request for that.
664     if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
665       HasGotOffRel = true;
666 
667     uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
668 
669     if (unsigned Processed =
670             handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
671       I += (Processed - 1);
672       continue;
673     }
674 
675     if (needsPlt(Expr) || Expr == R_THUNK || refersToGotEntry(Expr) ||
676         !Body.isPreemptible()) {
677       // If the relocation points to something in the file, we can process it.
678       bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
679 
680       // If the output being produced is position independent, the final value
681       // is still not known. In that case we still need some help from the
682       // dynamic linker. We can however do better than just copying the incoming
683       // relocation. We can process some of it and and just ask the dynamic
684       // linker to add the load address.
685       if (!Constant)
686         AddDyn({Target->RelativeRel, C.OutSec, Offset, true, &Body, Addend});
687 
688       // If the produced value is a constant, we just remember to write it
689       // when outputting this section. We also have to do it if the format
690       // uses Elf_Rel, since in that case the written value is the addend.
691       if (Constant || !RelTy::IsRela)
692         C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
693     } else {
694       // We don't know anything about the finaly symbol. Just ask the dynamic
695       // linker to handle the relocation for us.
696       AddDyn({Target->getDynRel(Type), C.OutSec, Offset, false, &Body, Addend});
697       // MIPS ABI turns using of GOT and dynamic relocations inside out.
698       // While regular ABI uses dynamic relocations to fill up GOT entries
699       // MIPS ABI requires dynamic linker to fills up GOT entries using
700       // specially sorted dynamic symbol table. This affects even dynamic
701       // relocations against symbols which do not require GOT entries
702       // creation explicitly, i.e. do not have any GOT-relocations. So if
703       // a preemptible symbol has a dynamic relocation we anyway have
704       // to create a GOT entry for it.
705       // If a non-preemptible symbol has a dynamic relocation against it,
706       // dynamic linker takes it st_value, adds offset and writes down
707       // result of the dynamic relocation. In case of preemptible symbol
708       // dynamic linker performs symbol resolution, writes the symbol value
709       // to the GOT entry and reads the GOT entry when it needs to perform
710       // a dynamic relocation.
711       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
712       if (Config->EMachine == EM_MIPS && !Body.isInGot())
713         Out<ELFT>::Got->addEntry(Body);
714       continue;
715     }
716 
717     if (Expr == R_THUNK)
718       continue;
719 
720     // At this point we are done with the relocated position. Some relocations
721     // also require us to create a got or plt entry.
722 
723     // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
724     if (needsPlt(Expr)) {
725       if (Body.isInPlt())
726         continue;
727       Out<ELFT>::Plt->addEntry(Body);
728 
729       uint32_t Rel;
730       if (Body.isGnuIFunc() && !Preemptible)
731         Rel = Target->IRelativeRel;
732       else
733         Rel = Target->PltRel;
734 
735       Out<ELFT>::GotPlt->addEntry(Body);
736       Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
737                                     Body.getGotPltOffset<ELFT>(), !Preemptible,
738                                     &Body, 0});
739       continue;
740     }
741 
742     if (refersToGotEntry(Expr)) {
743       if (Body.isInGot())
744         continue;
745       Out<ELFT>::Got->addEntry(Body);
746 
747       if (Config->EMachine == EM_MIPS)
748         // MIPS ABI has special rules to process GOT entries
749         // and doesn't require relocation entries for them.
750         // See "Global Offset Table" in Chapter 5 in the following document
751         // for detailed description:
752         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
753         continue;
754 
755       if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
756         uint32_t DynType;
757         if (Body.isTls())
758           DynType = Target->TlsGotRel;
759         else if (Preemptible)
760           DynType = Target->GotRel;
761         else
762           DynType = Target->RelativeRel;
763         AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
764                 !Preemptible, &Body, 0});
765       }
766       continue;
767     }
768   }
769 
770   // Scan relocations for necessary thunks.
771   if (Config->EMachine == EM_MIPS)
772     scanRelocsForThunks(File, Rels);
773 }
774 
775 template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) {
776   // Scan all relocations. Each relocation goes through a series
777   // of tests to determine if it needs special treatment, such as
778   // creating GOT, PLT, copy relocations, etc.
779   // Note that relocations for non-alloc sections are directly
780   // processed by InputSection::relocateNative.
781   if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
782     for (const Elf_Shdr *RelSec : C.RelocSections)
783       scanRelocs(C, *RelSec);
784 }
785 
786 template <class ELFT>
787 void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S,
788                               const Elf_Shdr &RelSec) {
789   ELFFile<ELFT> &EObj = S.getFile()->getObj();
790   if (RelSec.sh_type == SHT_RELA)
791     scanRelocs(S, EObj.relas(&RelSec));
792   else
793     scanRelocs(S, EObj.rels(&RelSec));
794 }
795 
796 template <class ELFT>
797 static void reportUndefined(SymbolTable<ELFT> &Symtab, SymbolBody *Sym) {
798   if (!Config->NoUndefined) {
799     if (Config->Relocatable)
800       return;
801     if (Config->Shared && !Config->ZDefs)
802       if (Sym->symbol()->Visibility == STV_DEFAULT)
803         return;
804   }
805 
806   std::string Msg = "undefined symbol: " + Sym->getName().str();
807   if (InputFile *File = Sym->getSourceFile<ELFT>())
808     Msg += " in " + getFilename(File);
809   if (Config->NoinhibitExec)
810     warning(Msg);
811   else
812     error(Msg);
813 }
814 
815 template <class ELFT>
816 static bool shouldKeepInSymtab(InputSectionBase<ELFT> *Sec, StringRef SymName,
817                                const SymbolBody &B) {
818   if (B.isFile())
819     return false;
820 
821   // We keep sections in symtab for relocatable output.
822   if (B.isSection())
823     return Config->Relocatable;
824 
825   // If sym references a section in a discarded group, don't keep it.
826   if (Sec == &InputSection<ELFT>::Discarded)
827     return false;
828 
829   if (Config->DiscardNone)
830     return true;
831 
832   // In ELF assembly .L symbols are normally discarded by the assembler.
833   // If the assembler fails to do so, the linker discards them if
834   // * --discard-locals is used.
835   // * The symbol is in a SHF_MERGE section, which is normally the reason for
836   //   the assembler keeping the .L symbol.
837   if (!SymName.startswith(".L") && !SymName.empty())
838     return true;
839 
840   if (Config->DiscardLocals)
841     return false;
842 
843   return !(Sec->getSectionHdr()->sh_flags & SHF_MERGE);
844 }
845 
846 template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
847   if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
848     return false;
849 
850   if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
851     // Always include absolute symbols.
852     if (!D->Section)
853       return true;
854     // Exclude symbols pointing to garbage-collected sections.
855     if (!D->Section->Live)
856       return false;
857     if (auto *S = dyn_cast<MergeInputSection<ELFT>>(D->Section))
858       if (!S->getSectionPiece(D->Value)->Live)
859         return false;
860   }
861   return true;
862 }
863 
864 // Local symbols are not in the linker's symbol table. This function scans
865 // each object file's symbol table to copy local symbols to the output.
866 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
867   if (!Out<ELFT>::SymTab)
868     return;
869   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
870        Symtab.getObjectFiles()) {
871     const char *StrTab = F->getStringTable().data();
872     for (SymbolBody *B : F->getLocalSymbols()) {
873       auto *DR = dyn_cast<DefinedRegular<ELFT>>(B);
874       // No reason to keep local undefined symbol in symtab.
875       if (!DR)
876         continue;
877       if (!includeInSymtab<ELFT>(*B))
878         continue;
879       StringRef SymName(StrTab + B->getNameOffset());
880       InputSectionBase<ELFT> *Sec = DR->Section;
881       if (!shouldKeepInSymtab<ELFT>(Sec, SymName, *B))
882         continue;
883       ++Out<ELFT>::SymTab->NumLocals;
884       if (Config->Relocatable)
885         B->DynsymIndex = Out<ELFT>::SymTab->NumLocals;
886       F->KeptLocalSyms.push_back(
887           std::make_pair(DR, Out<ELFT>::SymTab->StrTabSec.addString(SymName)));
888     }
889   }
890 }
891 
892 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
893 // we would like to make sure appear is a specific order to maximize their
894 // coverage by a single signed 16-bit offset from the TOC base pointer.
895 // Conversely, the special .tocbss section should be first among all SHT_NOBITS
896 // sections. This will put it next to the loaded special PPC64 sections (and,
897 // thus, within reach of the TOC base pointer).
898 static int getPPC64SectionRank(StringRef SectionName) {
899   return StringSwitch<int>(SectionName)
900       .Case(".tocbss", 0)
901       .Case(".branch_lt", 2)
902       .Case(".toc", 3)
903       .Case(".toc1", 4)
904       .Case(".opd", 5)
905       .Default(1);
906 }
907 
908 template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) {
909   if (!Config->ZRelro)
910     return false;
911   typename ELFT::uint Flags = Sec->getFlags();
912   if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
913     return false;
914   if (Flags & SHF_TLS)
915     return true;
916   uint32_t Type = Sec->getType();
917   if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
918       Type == SHT_PREINIT_ARRAY)
919     return true;
920   if (Sec == Out<ELFT>::GotPlt)
921     return Config->ZNow;
922   if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got)
923     return true;
924   StringRef S = Sec->getName();
925   return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
926          S == ".eh_frame";
927 }
928 
929 // Output section ordering is determined by this function.
930 template <class ELFT>
931 static bool compareSections(OutputSectionBase<ELFT> *A,
932                             OutputSectionBase<ELFT> *B) {
933   typedef typename ELFT::uint uintX_t;
934 
935   int Comp = Script<ELFT>::X->compareSections(A->getName(), B->getName());
936   if (Comp != 0)
937     return Comp < 0;
938 
939   uintX_t AFlags = A->getFlags();
940   uintX_t BFlags = B->getFlags();
941 
942   // Allocatable sections go first to reduce the total PT_LOAD size and
943   // so debug info doesn't change addresses in actual code.
944   bool AIsAlloc = AFlags & SHF_ALLOC;
945   bool BIsAlloc = BFlags & SHF_ALLOC;
946   if (AIsAlloc != BIsAlloc)
947     return AIsAlloc;
948 
949   // We don't have any special requirements for the relative order of
950   // two non allocatable sections.
951   if (!AIsAlloc)
952     return false;
953 
954   // We want the read only sections first so that they go in the PT_LOAD
955   // covering the program headers at the start of the file.
956   bool AIsWritable = AFlags & SHF_WRITE;
957   bool BIsWritable = BFlags & SHF_WRITE;
958   if (AIsWritable != BIsWritable)
959     return BIsWritable;
960 
961   // For a corresponding reason, put non exec sections first (the program
962   // header PT_LOAD is not executable).
963   bool AIsExec = AFlags & SHF_EXECINSTR;
964   bool BIsExec = BFlags & SHF_EXECINSTR;
965   if (AIsExec != BIsExec)
966     return BIsExec;
967 
968   // If we got here we know that both A and B are in the same PT_LOAD.
969 
970   // The TLS initialization block needs to be a single contiguous block in a R/W
971   // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
972   // sections are placed here as they don't take up virtual address space in the
973   // PT_LOAD.
974   bool AIsTls = AFlags & SHF_TLS;
975   bool BIsTls = BFlags & SHF_TLS;
976   if (AIsTls != BIsTls)
977     return AIsTls;
978 
979   // The next requirement we have is to put nobits sections last. The
980   // reason is that the only thing the dynamic linker will see about
981   // them is a p_memsz that is larger than p_filesz. Seeing that it
982   // zeros the end of the PT_LOAD, so that has to correspond to the
983   // nobits sections.
984   bool AIsNoBits = A->getType() == SHT_NOBITS;
985   bool BIsNoBits = B->getType() == SHT_NOBITS;
986   if (AIsNoBits != BIsNoBits)
987     return BIsNoBits;
988 
989   // We place RelRo section before plain r/w ones.
990   bool AIsRelRo = isRelroSection(A);
991   bool BIsRelRo = isRelroSection(B);
992   if (AIsRelRo != BIsRelRo)
993     return AIsRelRo;
994 
995   // Some architectures have additional ordering restrictions for sections
996   // within the same PT_LOAD.
997   if (Config->EMachine == EM_PPC64)
998     return getPPC64SectionRank(A->getName()) <
999            getPPC64SectionRank(B->getName());
1000 
1001   return false;
1002 }
1003 
1004 // The .bss section does not exist if no input file has a .bss section.
1005 // This function creates one if that's the case.
1006 template <class ELFT> void Writer<ELFT>::ensureBss() {
1007   if (Out<ELFT>::Bss)
1008     return;
1009   Out<ELFT>::Bss =
1010       new OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1011   OwningSections.emplace_back(Out<ELFT>::Bss);
1012   OutputSections.push_back(Out<ELFT>::Bss);
1013 }
1014 
1015 // Until this function is called, common symbols do not belong to any section.
1016 // This function adds them to end of BSS section.
1017 template <class ELFT>
1018 void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) {
1019   if (Syms.empty())
1020     return;
1021 
1022   // Sort the common symbols by alignment as an heuristic to pack them better.
1023   std::stable_sort(Syms.begin(), Syms.end(),
1024                    [](const DefinedCommon *A, const DefinedCommon *B) {
1025                      return A->Alignment > B->Alignment;
1026                    });
1027 
1028   ensureBss();
1029   uintX_t Off = Out<ELFT>::Bss->getSize();
1030   for (DefinedCommon *C : Syms) {
1031     Off = alignTo(Off, C->Alignment);
1032     Out<ELFT>::Bss->updateAlign(C->Alignment);
1033     C->OffsetInBss = Off;
1034     Off += C->Size;
1035   }
1036 
1037   Out<ELFT>::Bss->setSize(Off);
1038 }
1039 
1040 template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
1041   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
1042 
1043   uintX_t SecAlign = SS->File->getSection(SS->Sym)->sh_addralign;
1044   uintX_t SymValue = SS->Sym.st_value;
1045   int TrailingZeros =
1046       std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
1047   return 1 << TrailingZeros;
1048 }
1049 
1050 // Reserve space in .bss for copy relocation.
1051 template <class ELFT>
1052 void Writer<ELFT>::addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
1053   ensureBss();
1054   uintX_t Align = getAlignment(SS);
1055   uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Align);
1056   Out<ELFT>::Bss->setSize(Off + SS->template getSize<ELFT>());
1057   Out<ELFT>::Bss->updateAlign(Align);
1058   uintX_t Shndx = SS->Sym.st_shndx;
1059   uintX_t Value = SS->Sym.st_value;
1060   // Look through the DSO's dynamic symbol table for aliases and create a
1061   // dynamic symbol for each one. This causes the copy relocation to correctly
1062   // interpose any aliases.
1063   for (const Elf_Sym &S : SS->File->getElfSymbols(true)) {
1064     if (S.st_shndx != Shndx || S.st_value != Value)
1065       continue;
1066     auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
1067         Symtab.find(check(S.getName(SS->File->getStringTable()))));
1068     if (!Alias)
1069       continue;
1070     Alias->OffsetInBss = Off;
1071     Alias->NeedsCopyOrPltAddr = true;
1072     Alias->symbol()->IsUsedInRegularObj = true;
1073   }
1074   Out<ELFT>::RelaDyn->addReloc(
1075       {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
1076 }
1077 
1078 template <class ELFT>
1079 StringRef Writer<ELFT>::getOutputSectionName(InputSectionBase<ELFT> *S) const {
1080   StringRef Dest = Script<ELFT>::X->getOutputSection(S);
1081   if (!Dest.empty())
1082     return Dest;
1083 
1084   StringRef Name = S->getSectionName();
1085   for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
1086                       ".init_array.", ".fini_array.", ".ctors.", ".dtors.",
1087                       ".tbss.", ".gcc_except_table.", ".tdata."})
1088     if (Name.startswith(V))
1089       return V.drop_back();
1090   return Name;
1091 }
1092 
1093 template <class ELFT>
1094 void reportDiscarded(InputSectionBase<ELFT> *IS,
1095                      const std::unique_ptr<elf::ObjectFile<ELFT>> &File) {
1096   if (!Config->PrintGcSections || !IS || IS->Live)
1097     return;
1098   llvm::errs() << "removing unused section from '" << IS->getSectionName()
1099                << "' in file '" << File->getName() << "'\n";
1100 }
1101 
1102 template <class ELFT>
1103 bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) const {
1104   return !S || S == &InputSection<ELFT>::Discarded || !S->Live ||
1105          Script<ELFT>::X->isDiscarded(S);
1106 }
1107 
1108 template <class ELFT>
1109 static Symbol *addOptionalSynthetic(SymbolTable<ELFT> &Table, StringRef Name,
1110                                     OutputSectionBase<ELFT> *Sec,
1111                                     typename ELFT::uint Val) {
1112   SymbolBody *S = Table.find(Name);
1113   if (!S)
1114     return nullptr;
1115   if (!S->isUndefined() && !S->isShared())
1116     return S->symbol();
1117   return Table.addSynthetic(Name, Sec, Val);
1118 }
1119 
1120 // The beginning and the ending of .rel[a].plt section are marked
1121 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1122 // executable. The runtime needs these symbols in order to resolve
1123 // all IRELATIVE relocs on startup. For dynamic executables, we don't
1124 // need these symbols, since IRELATIVE relocs are resolved through GOT
1125 // and PLT. For details, see http://www.airs.com/blog/archives/403.
1126 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
1127   if (isOutputDynamic() || !Out<ELFT>::RelaPlt)
1128     return;
1129   StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
1130   addOptionalSynthetic(Symtab, S, Out<ELFT>::RelaPlt, 0);
1131 
1132   S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
1133   addOptionalSynthetic(Symtab, S, Out<ELFT>::RelaPlt,
1134                        DefinedSynthetic<ELFT>::SectionEnd);
1135 }
1136 
1137 // This class knows how to create an output section for a given
1138 // input section. Output section type is determined by various
1139 // factors, including input section's sh_flags, sh_type and
1140 // linker scripts.
1141 namespace {
1142 template <class ELFT> class OutputSectionFactory {
1143   typedef typename ELFT::Shdr Elf_Shdr;
1144   typedef typename ELFT::uint uintX_t;
1145 
1146 public:
1147   std::pair<OutputSectionBase<ELFT> *, bool> create(InputSectionBase<ELFT> *C,
1148                                                     StringRef OutsecName);
1149 
1150   OutputSectionBase<ELFT> *lookup(StringRef Name, uint32_t Type,
1151                                   uintX_t Flags) {
1152     return Map.lookup({Name, Type, Flags, 0});
1153   }
1154 
1155 private:
1156   SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
1157                                        StringRef OutsecName);
1158 
1159   SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map;
1160 };
1161 }
1162 
1163 template <class ELFT>
1164 std::pair<OutputSectionBase<ELFT> *, bool>
1165 OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
1166                                    StringRef OutsecName) {
1167   SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
1168   OutputSectionBase<ELFT> *&Sec = Map[Key];
1169   if (Sec)
1170     return {Sec, false};
1171 
1172   switch (C->SectionKind) {
1173   case InputSectionBase<ELFT>::Regular:
1174     Sec = new OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
1175     break;
1176   case InputSectionBase<ELFT>::EHFrame:
1177     Sec = new EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
1178     break;
1179   case InputSectionBase<ELFT>::Merge:
1180     Sec = new MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags,
1181                                        Key.Alignment);
1182     break;
1183   case InputSectionBase<ELFT>::MipsReginfo:
1184     Sec = new MipsReginfoOutputSection<ELFT>();
1185     break;
1186   case InputSectionBase<ELFT>::MipsOptions:
1187     Sec = new MipsOptionsOutputSection<ELFT>();
1188     break;
1189   }
1190   return {Sec, true};
1191 }
1192 
1193 template <class ELFT>
1194 SectionKey<ELFT::Is64Bits>
1195 OutputSectionFactory<ELFT>::createKey(InputSectionBase<ELFT> *C,
1196                                       StringRef OutsecName) {
1197   const Elf_Shdr *H = C->getSectionHdr();
1198   uintX_t Flags = H->sh_flags & ~SHF_GROUP;
1199 
1200   // For SHF_MERGE we create different output sections for each alignment.
1201   // This makes each output section simple and keeps a single level mapping from
1202   // input to output.
1203   uintX_t Alignment = 0;
1204   if (isa<MergeInputSection<ELFT>>(C))
1205     Alignment = std::max(H->sh_addralign, H->sh_entsize);
1206 
1207   // GNU as can give .eh_frame section type SHT_PROGBITS or SHT_X86_64_UNWIND
1208   // depending on the construct. We want to canonicalize it so that
1209   // there is only one .eh_frame in the end.
1210   uint32_t Type = H->sh_type;
1211   if (Type == SHT_PROGBITS && Config->EMachine == EM_X86_64 &&
1212       isa<EHInputSection<ELFT>>(C))
1213     Type = SHT_X86_64_UNWIND;
1214 
1215   return SectionKey<ELFT::Is64Bits>{OutsecName, Type, Flags, Alignment};
1216 }
1217 
1218 // The linker is expected to define some symbols depending on
1219 // the linking result. This function defines such symbols.
1220 template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
1221   if (Config->EMachine == EM_MIPS) {
1222     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
1223     // so that it points to an absolute address which is relative to GOT.
1224     // See "Global Data Symbols" in Chapter 6 in the following document:
1225     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1226     Symtab.addSynthetic("_gp", Out<ELFT>::Got, MipsGPOffset);
1227 
1228     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
1229     // start of function and 'gp' pointer into GOT.
1230     Symbol *Sym =
1231         addOptionalSynthetic(Symtab, "_gp_disp", Out<ELFT>::Got, MipsGPOffset);
1232     if (Sym)
1233       ElfSym<ELFT>::MipsGpDisp = Sym->body();
1234 
1235     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
1236     // pointer. This symbol is used in the code generated by .cpload pseudo-op
1237     // in case of using -mno-shared option.
1238     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
1239     addOptionalSynthetic(Symtab, "__gnu_local_gp", Out<ELFT>::Got,
1240                          MipsGPOffset);
1241   }
1242 
1243   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
1244   // is magical and is used to produce a R_386_GOTPC relocation.
1245   // The R_386_GOTPC relocation value doesn't actually depend on the
1246   // symbol value, so it could use an index of STN_UNDEF which, according
1247   // to the spec, means the symbol value is 0.
1248   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
1249   // the object file.
1250   // The situation is even stranger on x86_64 where the assembly doesn't
1251   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
1252   // an undefined symbol in the .o files.
1253   // Given that the symbol is effectively unused, we just create a dummy
1254   // hidden one to avoid the undefined symbol error.
1255   if (!Config->Relocatable)
1256     Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_");
1257 
1258   // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
1259   // static linking the linker is required to optimize away any references to
1260   // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
1261   // to avoid the undefined symbol error.
1262   if (!isOutputDynamic())
1263     Symtab.addIgnored("__tls_get_addr");
1264 
1265   auto Define = [this](StringRef S, DefinedRegular<ELFT> *&Sym1,
1266                        DefinedRegular<ELFT> *&Sym2) {
1267     Sym1 = Symtab.addIgnored(S, STV_DEFAULT);
1268 
1269     // The name without the underscore is not a reserved name,
1270     // so it is defined only when there is a reference against it.
1271     assert(S.startswith("_"));
1272     S = S.substr(1);
1273     if (SymbolBody *B = Symtab.find(S))
1274       if (B->isUndefined())
1275         Sym2 = Symtab.addAbsolute(S, STV_DEFAULT);
1276   };
1277 
1278   Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
1279   Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
1280   Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
1281 }
1282 
1283 // Sort input sections by section name suffixes for
1284 // __attribute__((init_priority(N))).
1285 template <class ELFT> static void sortInitFini(OutputSectionBase<ELFT> *S) {
1286   if (S)
1287     reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
1288 }
1289 
1290 // Sort input sections by the special rule for .ctors and .dtors.
1291 template <class ELFT> static void sortCtorsDtors(OutputSectionBase<ELFT> *S) {
1292   if (S)
1293     reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
1294 }
1295 
1296 // Create output section objects and add them to OutputSections.
1297 template <class ELFT> void Writer<ELFT>::createSections() {
1298   // Add .interp first because some loaders want to see that section
1299   // on the first page of the executable file when loaded into memory.
1300   if (needsInterpSection())
1301     OutputSections.push_back(Out<ELFT>::Interp);
1302 
1303   // A core file does not usually contain unmodified segments except
1304   // the first page of the executable. Add the build ID section now
1305   // so that the section is included in the first page.
1306   if (Out<ELFT>::BuildId)
1307     OutputSections.push_back(Out<ELFT>::BuildId);
1308 
1309   // Create output sections for input object file sections.
1310   std::vector<OutputSectionBase<ELFT> *> RegularSections;
1311   OutputSectionFactory<ELFT> Factory;
1312   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
1313        Symtab.getObjectFiles()) {
1314     for (InputSectionBase<ELFT> *C : F->getSections()) {
1315       if (isDiscarded(C)) {
1316         reportDiscarded(C, F);
1317         continue;
1318       }
1319       OutputSectionBase<ELFT> *Sec;
1320       bool IsNew;
1321       std::tie(Sec, IsNew) = Factory.create(C, getOutputSectionName(C));
1322       if (IsNew) {
1323         OwningSections.emplace_back(Sec);
1324         OutputSections.push_back(Sec);
1325         RegularSections.push_back(Sec);
1326       }
1327       Sec->addSection(C);
1328     }
1329   }
1330 
1331   Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>(
1332       Factory.lookup(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE));
1333 
1334   // If we have a .opd section (used under PPC64 for function descriptors),
1335   // store a pointer to it here so that we can use it later when processing
1336   // relocations.
1337   Out<ELFT>::Opd = Factory.lookup(".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC);
1338 
1339   Out<ELFT>::Dynamic->PreInitArraySec = Factory.lookup(
1340       ".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC);
1341   Out<ELFT>::Dynamic->InitArraySec =
1342       Factory.lookup(".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC);
1343   Out<ELFT>::Dynamic->FiniArraySec =
1344       Factory.lookup(".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC);
1345 
1346   // Sort section contents for __attribute__((init_priority(N)).
1347   sortInitFini(Out<ELFT>::Dynamic->InitArraySec);
1348   sortInitFini(Out<ELFT>::Dynamic->FiniArraySec);
1349   sortCtorsDtors(Factory.lookup(".ctors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
1350   sortCtorsDtors(Factory.lookup(".dtors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
1351 
1352   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1353   // symbols for sections, so that the runtime can get the start and end
1354   // addresses of each section by section name. Add such symbols.
1355   if (!Config->Relocatable) {
1356     addStartEndSymbols();
1357     for (OutputSectionBase<ELFT> *Sec : RegularSections)
1358       addStartStopSymbols(Sec);
1359   }
1360 
1361   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1362   // It should be okay as no one seems to care about the type.
1363   // Even the author of gold doesn't remember why gold behaves that way.
1364   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1365   if (isOutputDynamic())
1366     Symtab.addSynthetic("_DYNAMIC", Out<ELFT>::Dynamic, 0);
1367 
1368   // Define __rel[a]_iplt_{start,end} symbols if needed.
1369   addRelIpltSymbols();
1370 
1371   if (Out<ELFT>::EhFrameHdr->Sec)
1372     Out<ELFT>::EhFrameHdr->Sec->finalize();
1373 
1374   // Scan relocations. This must be done after every symbol is declared so that
1375   // we can correctly decide if a dynamic relocation is needed.
1376   // Check size() each time to guard against .bss being created.
1377   for (unsigned I = 0; I < OutputSections.size(); ++I) {
1378     OutputSectionBase<ELFT> *Sec = OutputSections[I];
1379     Sec->forEachInputSection([&](InputSectionBase<ELFT> *S) {
1380       if (auto *IS = dyn_cast<InputSection<ELFT>>(S)) {
1381         // Set OutSecOff so that scanRelocs can use it.
1382         uintX_t Off = alignTo(Sec->getSize(), S->Align);
1383         IS->OutSecOff = Off;
1384 
1385         scanRelocs(*IS);
1386 
1387         // Now that scan relocs possibly changed the size, update the offset.
1388         Sec->setSize(Off + S->getSize());
1389       } else if (auto *EH = dyn_cast<EHInputSection<ELFT>>(S)) {
1390         if (EH->RelocSection)
1391           scanRelocs(*EH, *EH->RelocSection);
1392       }
1393     });
1394   }
1395 
1396   // Now that we have defined all possible symbols including linker-
1397   // synthesized ones. Visit all symbols to give the finishing touches.
1398   std::vector<DefinedCommon *> CommonSymbols;
1399   for (Symbol *S : Symtab.getSymbols()) {
1400     SymbolBody *Body = S->body();
1401 
1402     // Set "used" bit for --as-needed.
1403     if (S->IsUsedInRegularObj && !S->isWeak())
1404       if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1405         SS->File->IsUsed = true;
1406 
1407     // We only report undefined symbols in regular objects. This means that we
1408     // will accept an undefined reference in bitcode if it can be optimized out.
1409     if (S->IsUsedInRegularObj && Body->isUndefined() && !S->isWeak())
1410       reportUndefined<ELFT>(Symtab, Body);
1411 
1412     if (auto *C = dyn_cast<DefinedCommon>(Body))
1413       CommonSymbols.push_back(C);
1414 
1415     if (!includeInSymtab<ELFT>(*Body))
1416       continue;
1417     if (Out<ELFT>::SymTab)
1418       Out<ELFT>::SymTab->addSymbol(Body);
1419 
1420     if (isOutputDynamic() && S->includeInDynsym()) {
1421       Out<ELFT>::DynSymTab->addSymbol(Body);
1422       if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1423         Out<ELFT>::VerNeed->addSymbol(SS);
1424     }
1425   }
1426 
1427   // Do not proceed if there was an undefined symbol.
1428   if (HasError)
1429     return;
1430 
1431   addCommonSymbols(CommonSymbols);
1432 
1433   // So far we have added sections from input object files.
1434   // This function adds linker-created Out<ELFT>::* sections.
1435   addPredefinedSections();
1436 
1437   std::stable_sort(OutputSections.begin(), OutputSections.end(),
1438                    compareSections<ELFT>);
1439 
1440   unsigned I = 1;
1441   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1442     Sec->SectionIndex = I++;
1443     Sec->setSHName(Out<ELFT>::ShStrTab->addString(Sec->getName()));
1444   }
1445 
1446   // Finalizers fix each section's size.
1447   // .dynsym is finalized early since that may fill up .gnu.hash.
1448   if (isOutputDynamic())
1449     Out<ELFT>::DynSymTab->finalize();
1450 
1451   // Fill other section headers. The dynamic table is finalized
1452   // at the end because some tags like RELSZ depend on result
1453   // of finalizing other sections. The dynamic string table is
1454   // finalized once the .dynamic finalizer has added a few last
1455   // strings. See DynamicSection::finalize()
1456   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1457     if (Sec != Out<ELFT>::DynStrTab && Sec != Out<ELFT>::Dynamic)
1458       Sec->finalize();
1459 
1460   if (isOutputDynamic())
1461     Out<ELFT>::Dynamic->finalize();
1462 }
1463 
1464 template <class ELFT> bool Writer<ELFT>::needsGot() {
1465   if (!Out<ELFT>::Got->empty())
1466     return true;
1467 
1468   // We add the .got section to the result for dynamic MIPS target because
1469   // its address and properties are mentioned in the .dynamic section.
1470   if (Config->EMachine == EM_MIPS)
1471     return true;
1472 
1473   // If we have a relocation that is relative to GOT (such as GOTOFFREL),
1474   // we need to emit a GOT even if it's empty.
1475   return HasGotOffRel;
1476 }
1477 
1478 // This function add Out<ELFT>::* sections to OutputSections.
1479 template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
1480   auto Add = [&](OutputSectionBase<ELFT> *C) {
1481     if (C)
1482       OutputSections.push_back(C);
1483   };
1484 
1485   // This order is not the same as the final output order
1486   // because we sort the sections using their attributes below.
1487   Add(Out<ELFT>::SymTab);
1488   Add(Out<ELFT>::ShStrTab);
1489   Add(Out<ELFT>::StrTab);
1490   if (isOutputDynamic()) {
1491     Add(Out<ELFT>::DynSymTab);
1492     if (Out<ELFT>::VerNeed->getNeedNum() != 0) {
1493       Add(Out<ELFT>::VerSym);
1494       Add(Out<ELFT>::VerNeed);
1495     }
1496     Add(Out<ELFT>::GnuHashTab);
1497     Add(Out<ELFT>::HashTab);
1498     Add(Out<ELFT>::Dynamic);
1499     Add(Out<ELFT>::DynStrTab);
1500     if (Out<ELFT>::RelaDyn->hasRelocs())
1501       Add(Out<ELFT>::RelaDyn);
1502     Add(Out<ELFT>::MipsRldMap);
1503   }
1504 
1505   // We always need to add rel[a].plt to output if it has entries.
1506   // Even during static linking it can contain R_[*]_IRELATIVE relocations.
1507   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
1508     Add(Out<ELFT>::RelaPlt);
1509     Out<ELFT>::RelaPlt->Static = !isOutputDynamic();
1510   }
1511 
1512   if (needsGot())
1513     Add(Out<ELFT>::Got);
1514   if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty())
1515     Add(Out<ELFT>::GotPlt);
1516   if (!Out<ELFT>::Plt->empty())
1517     Add(Out<ELFT>::Plt);
1518   if (Out<ELFT>::EhFrameHdr->Live)
1519     Add(Out<ELFT>::EhFrameHdr);
1520 }
1521 
1522 // The linker is expected to define SECNAME_start and SECNAME_end
1523 // symbols for a few sections. This function defines them.
1524 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1525   auto Define = [&](StringRef Start, StringRef End,
1526                     OutputSectionBase<ELFT> *OS) {
1527     if (OS) {
1528       this->Symtab.addSynthetic(Start, OS, 0);
1529       this->Symtab.addSynthetic(End, OS, DefinedSynthetic<ELFT>::SectionEnd);
1530     } else {
1531       addOptionalSynthetic(this->Symtab, Start,
1532                            (OutputSectionBase<ELFT> *)nullptr, 0);
1533       addOptionalSynthetic(this->Symtab, End,
1534                            (OutputSectionBase<ELFT> *)nullptr, 0);
1535     }
1536   };
1537 
1538   Define("__preinit_array_start", "__preinit_array_end",
1539          Out<ELFT>::Dynamic->PreInitArraySec);
1540   Define("__init_array_start", "__init_array_end",
1541          Out<ELFT>::Dynamic->InitArraySec);
1542   Define("__fini_array_start", "__fini_array_end",
1543          Out<ELFT>::Dynamic->FiniArraySec);
1544 }
1545 
1546 // If a section name is valid as a C identifier (which is rare because of
1547 // the leading '.'), linkers are expected to define __start_<secname> and
1548 // __stop_<secname> symbols. They are at beginning and end of the section,
1549 // respectively. This is not requested by the ELF standard, but GNU ld and
1550 // gold provide the feature, and used by many programs.
1551 template <class ELFT>
1552 void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) {
1553   StringRef S = Sec->getName();
1554   if (!isValidCIdentifier(S))
1555     return;
1556   StringSaver Saver(Alloc);
1557   StringRef Start = Saver.save("__start_" + S);
1558   StringRef Stop = Saver.save("__stop_" + S);
1559   if (SymbolBody *B = Symtab.find(Start))
1560     if (B->isUndefined())
1561       Symtab.addSynthetic(Start, Sec, 0);
1562   if (SymbolBody *B = Symtab.find(Stop))
1563     if (B->isUndefined())
1564       Symtab.addSynthetic(Stop, Sec, DefinedSynthetic<ELFT>::SectionEnd);
1565 }
1566 
1567 template <class ELFT> static bool needsPtLoad(OutputSectionBase<ELFT> *Sec) {
1568   if (!(Sec->getFlags() & SHF_ALLOC))
1569     return false;
1570 
1571   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1572   // responsible for allocating space for them, not the PT_LOAD that
1573   // contains the TLS initialization image.
1574   if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS)
1575     return false;
1576   return true;
1577 }
1578 
1579 static uint32_t toPhdrFlags(uint64_t Flags) {
1580   uint32_t Ret = PF_R;
1581   if (Flags & SHF_WRITE)
1582     Ret |= PF_W;
1583   if (Flags & SHF_EXECINSTR)
1584     Ret |= PF_X;
1585   return Ret;
1586 }
1587 
1588 // Decide which program headers to create and which sections to include in each
1589 // one.
1590 template <class ELFT> void Writer<ELFT>::createPhdrs() {
1591   auto AddHdr = [this](unsigned Type, unsigned Flags) {
1592     return &*Phdrs.emplace(Phdrs.end(), Type, Flags);
1593   };
1594 
1595   auto AddSec = [](Phdr &Hdr, OutputSectionBase<ELFT> *Sec) {
1596     Hdr.Last = Sec;
1597     if (!Hdr.First)
1598       Hdr.First = Sec;
1599     Hdr.H.p_align = std::max<uintX_t>(Hdr.H.p_align, Sec->getAlign());
1600   };
1601 
1602   // The first phdr entry is PT_PHDR which describes the program header itself.
1603   Phdr &Hdr = *AddHdr(PT_PHDR, PF_R);
1604   AddSec(Hdr, Out<ELFT>::ProgramHeaders);
1605 
1606   // PT_INTERP must be the second entry if exists.
1607   if (needsInterpSection()) {
1608     Phdr &Hdr = *AddHdr(PT_INTERP, toPhdrFlags(Out<ELFT>::Interp->getFlags()));
1609     AddSec(Hdr, Out<ELFT>::Interp);
1610   }
1611 
1612   // Add the first PT_LOAD segment for regular output sections.
1613   uintX_t Flags = PF_R;
1614   Phdr *Load = AddHdr(PT_LOAD, Flags);
1615   AddSec(*Load, Out<ELFT>::ElfHeader);
1616   AddSec(*Load, Out<ELFT>::ProgramHeaders);
1617 
1618   Phdr TlsHdr(PT_TLS, PF_R);
1619   Phdr RelRo(PT_GNU_RELRO, PF_R);
1620   Phdr Note(PT_NOTE, PF_R);
1621   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1622     if (!(Sec->getFlags() & SHF_ALLOC))
1623       break;
1624 
1625     // If we meet TLS section then we create TLS header
1626     // and put all TLS sections inside for futher use when
1627     // assign addresses.
1628     if (Sec->getFlags() & SHF_TLS)
1629       AddSec(TlsHdr, Sec);
1630 
1631     if (!needsPtLoad<ELFT>(Sec))
1632       continue;
1633 
1634     // If flags changed then we want new load segment.
1635     uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
1636     if (Flags != NewFlags) {
1637       Load = AddHdr(PT_LOAD, NewFlags);
1638       Flags = NewFlags;
1639     }
1640 
1641     AddSec(*Load, Sec);
1642 
1643     if (isRelroSection(Sec))
1644       AddSec(RelRo, Sec);
1645     if (Sec->getType() == SHT_NOTE)
1646       AddSec(Note, Sec);
1647   }
1648 
1649   // Add the TLS segment unless it's empty.
1650   if (TlsHdr.First)
1651     Phdrs.push_back(std::move(TlsHdr));
1652 
1653   // Add an entry for .dynamic.
1654   if (isOutputDynamic()) {
1655     Phdr &H = *AddHdr(PT_DYNAMIC, toPhdrFlags(Out<ELFT>::Dynamic->getFlags()));
1656     AddSec(H, Out<ELFT>::Dynamic);
1657   }
1658 
1659   // PT_GNU_RELRO includes all sections that should be marked as
1660   // read-only by dynamic linker after proccessing relocations.
1661   if (RelRo.First)
1662     Phdrs.push_back(std::move(RelRo));
1663 
1664   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1665   if (Out<ELFT>::EhFrameHdr->Live) {
1666     Phdr &Hdr = *AddHdr(PT_GNU_EH_FRAME,
1667                         toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags()));
1668     AddSec(Hdr, Out<ELFT>::EhFrameHdr);
1669   }
1670 
1671   // PT_GNU_STACK is a special section to tell the loader to make the
1672   // pages for the stack non-executable.
1673   if (!Config->ZExecStack)
1674     AddHdr(PT_GNU_STACK, PF_R | PF_W);
1675 
1676   if (Note.First)
1677     Phdrs.push_back(std::move(Note));
1678 
1679   Out<ELFT>::ProgramHeaders->setSize(sizeof(Elf_Phdr) * Phdrs.size());
1680 }
1681 
1682 // The first section of each PT_LOAD and the first section after PT_GNU_RELRO
1683 // have to be page aligned so that the dynamic linker can set the permissions.
1684 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1685   for (const Phdr &P : Phdrs)
1686     if (P.H.p_type == PT_LOAD)
1687       P.First->PageAlign = true;
1688 
1689   for (const Phdr &P : Phdrs) {
1690     if (P.H.p_type != PT_GNU_RELRO)
1691       continue;
1692     // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1693     // have to align it to a page.
1694     auto End = OutputSections.end();
1695     auto I = std::find(OutputSections.begin(), End, P.Last);
1696     if (I == End || (I + 1) == End)
1697       continue;
1698     OutputSectionBase<ELFT> *Sec = *(I + 1);
1699     if (needsPtLoad(Sec))
1700       Sec->PageAlign = true;
1701   }
1702 }
1703 
1704 // We should set file offsets and VAs for elf header and program headers
1705 // sections. These are special, we do not include them into output sections
1706 // list, but have them to simplify the code.
1707 template <class ELFT> void Writer<ELFT>::fixHeaders() {
1708   uintX_t BaseVA = ScriptConfig->DoLayout ? 0 : Target->getVAStart();
1709   Out<ELFT>::ElfHeader->setVA(BaseVA);
1710   Out<ELFT>::ElfHeader->setFileOffset(0);
1711   uintX_t Off = Out<ELFT>::ElfHeader->getSize();
1712   Out<ELFT>::ProgramHeaders->setVA(Off + BaseVA);
1713   Out<ELFT>::ProgramHeaders->setFileOffset(Off);
1714 }
1715 
1716 // Assign VAs (addresses at run-time) to output sections.
1717 template <class ELFT> void Writer<ELFT>::assignAddresses() {
1718   uintX_t VA = Target->getVAStart() + Out<ELFT>::ElfHeader->getSize() +
1719                Out<ELFT>::ProgramHeaders->getSize();
1720 
1721   uintX_t ThreadBssOffset = 0;
1722   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1723     uintX_t Align = Sec->getAlign();
1724     if (Sec->PageAlign)
1725       Align = std::max<uintX_t>(Align, Target->PageSize);
1726 
1727     // We only assign VAs to allocated sections.
1728     if (needsPtLoad<ELFT>(Sec)) {
1729       VA = alignTo(VA, Align);
1730       Sec->setVA(VA);
1731       VA += Sec->getSize();
1732     } else if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS) {
1733       uintX_t TVA = VA + ThreadBssOffset;
1734       TVA = alignTo(TVA, Align);
1735       Sec->setVA(TVA);
1736       ThreadBssOffset = TVA - VA + Sec->getSize();
1737     }
1738   }
1739 }
1740 
1741 // Adjusts the file alignment for a given output section and returns
1742 // its new file offset. The file offset must be the same with its
1743 // virtual address (modulo the page size) so that the loader can load
1744 // executables without any address adjustment.
1745 template <class ELFT, class uintX_t>
1746 static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase<ELFT> *Sec) {
1747   uintX_t Align = Sec->getAlign();
1748   if (Sec->PageAlign)
1749     Align = std::max<uintX_t>(Align, Target->PageSize);
1750   Off = alignTo(Off, Align);
1751 
1752   // Relocatable output does not have program headers
1753   // and does not need any other offset adjusting.
1754   if (Config->Relocatable || !(Sec->getFlags() & SHF_ALLOC))
1755     return Off;
1756   return alignTo(Off, Target->PageSize, Sec->getVA());
1757 }
1758 
1759 // Assign file offsets to output sections.
1760 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
1761   uintX_t Off =
1762       Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
1763 
1764   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1765     if (Sec->getType() == SHT_NOBITS) {
1766       Sec->setFileOffset(Off);
1767       continue;
1768     }
1769 
1770     Off = getFileAlignment<ELFT>(Off, Sec);
1771     Sec->setFileOffset(Off);
1772     Off += Sec->getSize();
1773   }
1774   SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
1775   FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
1776 }
1777 
1778 // Finalize the program headers. We call this function after we assign
1779 // file offsets and VAs to all sections.
1780 template <class ELFT> void Writer<ELFT>::setPhdrs() {
1781   for (Phdr &P : Phdrs) {
1782     Elf_Phdr &H = P.H;
1783     OutputSectionBase<ELFT> *First = P.First;
1784     OutputSectionBase<ELFT> *Last = P.Last;
1785     if (First) {
1786       H.p_filesz = Last->getFileOff() - First->getFileOff();
1787       if (Last->getType() != SHT_NOBITS)
1788         H.p_filesz += Last->getSize();
1789       H.p_memsz = Last->getVA() + Last->getSize() - First->getVA();
1790       H.p_offset = First->getFileOff();
1791       H.p_vaddr = First->getVA();
1792     }
1793     if (H.p_type == PT_LOAD)
1794       H.p_align = Target->PageSize;
1795     else if (H.p_type == PT_GNU_RELRO)
1796       H.p_align = 1;
1797     H.p_paddr = H.p_vaddr;
1798 
1799     // The TLS pointer goes after PT_TLS. At least glibc will align it,
1800     // so round up the size to make sure the offsets are correct.
1801     if (H.p_type == PT_TLS) {
1802       Out<ELFT>::TlsPhdr = &H;
1803       H.p_memsz = alignTo(H.p_memsz, H.p_align);
1804     }
1805   }
1806 }
1807 
1808 static uint32_t getMipsEFlags(bool Is64Bits) {
1809   // FIXME: In fact ELF flags depends on ELF flags of input object files
1810   // and selected emulation. For now just use hard coded values.
1811   if (Is64Bits)
1812     return EF_MIPS_CPIC | EF_MIPS_PIC | EF_MIPS_ARCH_64R2;
1813 
1814   uint32_t V = EF_MIPS_CPIC | EF_MIPS_ABI_O32 | EF_MIPS_ARCH_32R2;
1815   if (Config->Shared)
1816     V |= EF_MIPS_PIC;
1817   return V;
1818 }
1819 
1820 template <class ELFT> static typename ELFT::uint getEntryAddr() {
1821   if (Symbol *S = Config->EntrySym)
1822     return S->body()->getVA<ELFT>();
1823   if (Config->EntryAddr != uint64_t(-1))
1824     return Config->EntryAddr;
1825   return 0;
1826 }
1827 
1828 template <class ELFT> static uint8_t getELFEncoding() {
1829   if (ELFT::TargetEndianness == llvm::support::little)
1830     return ELFDATA2LSB;
1831   return ELFDATA2MSB;
1832 }
1833 
1834 static uint16_t getELFType() {
1835   if (Config->Pic)
1836     return ET_DYN;
1837   if (Config->Relocatable)
1838     return ET_REL;
1839   return ET_EXEC;
1840 }
1841 
1842 // This function is called after we have assigned address and size
1843 // to each section. This function fixes some predefined absolute
1844 // symbol values that depend on section address and size.
1845 template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
1846   auto Set = [](DefinedRegular<ELFT> *&S1, DefinedRegular<ELFT> *&S2,
1847                 uintX_t V) {
1848     if (S1)
1849       S1->Value = V;
1850     if (S2)
1851       S2->Value = V;
1852   };
1853 
1854   // _etext is the first location after the last read-only loadable segment.
1855   // _edata is the first location after the last read-write loadable segment.
1856   // _end is the first location after the uninitialized data region.
1857   for (Phdr &P : Phdrs) {
1858     Elf_Phdr &H = P.H;
1859     if (H.p_type != PT_LOAD)
1860       continue;
1861     Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, H.p_vaddr + H.p_memsz);
1862 
1863     uintX_t Val = H.p_vaddr + H.p_filesz;
1864     if (H.p_flags & PF_W)
1865       Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, Val);
1866     else
1867       Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, Val);
1868   }
1869 }
1870 
1871 template <class ELFT> void Writer<ELFT>::writeHeader() {
1872   uint8_t *Buf = Buffer->getBufferStart();
1873   memcpy(Buf, "\177ELF", 4);
1874 
1875   auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
1876 
1877   // Write the ELF header.
1878   auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
1879   EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1880   EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
1881   EHdr->e_ident[EI_VERSION] = EV_CURRENT;
1882   EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
1883   EHdr->e_type = getELFType();
1884   EHdr->e_machine = FirstObj.getEMachine();
1885   EHdr->e_version = EV_CURRENT;
1886   EHdr->e_entry = getEntryAddr<ELFT>();
1887   EHdr->e_shoff = SectionHeaderOff;
1888   EHdr->e_ehsize = sizeof(Elf_Ehdr);
1889   EHdr->e_phnum = Phdrs.size();
1890   EHdr->e_shentsize = sizeof(Elf_Shdr);
1891   EHdr->e_shnum = OutputSections.size() + 1;
1892   EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex;
1893 
1894   if (Config->EMachine == EM_MIPS)
1895     EHdr->e_flags = getMipsEFlags(ELFT::Is64Bits);
1896 
1897   if (!Config->Relocatable) {
1898     EHdr->e_phoff = sizeof(Elf_Ehdr);
1899     EHdr->e_phentsize = sizeof(Elf_Phdr);
1900   }
1901 
1902   // Write the program header table.
1903   auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1904   for (Phdr &P : Phdrs)
1905     *HBuf++ = P.H;
1906 
1907   // Write the section header table. Note that the first table entry is null.
1908   auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
1909   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1910     Sec->writeHeaderTo(++SHdrs);
1911 }
1912 
1913 template <class ELFT> void Writer<ELFT>::openFile() {
1914   ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1915       FileOutputBuffer::create(Config->OutputFile, FileSize,
1916                                FileOutputBuffer::F_executable);
1917   if (BufferOrErr)
1918     Buffer = std::move(*BufferOrErr);
1919   else
1920     error(BufferOrErr, "failed to open " + Config->OutputFile);
1921 }
1922 
1923 // Write section contents to a mmap'ed file.
1924 template <class ELFT> void Writer<ELFT>::writeSections() {
1925   uint8_t *Buf = Buffer->getBufferStart();
1926 
1927   // PPC64 needs to process relocations in the .opd section before processing
1928   // relocations in code-containing sections.
1929   if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) {
1930     Out<ELFT>::OpdBuf = Buf + Sec->getFileOff();
1931     Sec->writeTo(Buf + Sec->getFileOff());
1932   }
1933 
1934   for (OutputSectionBase<ELFT> *Sec : OutputSections)
1935     if (Sec != Out<ELFT>::Opd)
1936       Sec->writeTo(Buf + Sec->getFileOff());
1937 }
1938 
1939 template <class ELFT> void Writer<ELFT>::writeBuildId() {
1940   BuildIdSection<ELFT> *S = Out<ELFT>::BuildId;
1941   if (!S)
1942     return;
1943 
1944   // Compute a hash of all sections except .debug_* sections.
1945   // We skip debug sections because they tend to be very large
1946   // and their contents are very likely to be the same as long as
1947   // other sections are the same.
1948   uint8_t *Start = Buffer->getBufferStart();
1949   uint8_t *Last = Start;
1950   std::vector<ArrayRef<uint8_t>> Regions;
1951   for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1952     uint8_t *End = Start + Sec->getFileOff();
1953     if (!Sec->getName().startswith(".debug_"))
1954       Regions.push_back({Last, End});
1955     Last = End;
1956   }
1957   Regions.push_back({Last, Start + FileSize});
1958   S->writeBuildId(Regions);
1959 }
1960 
1961 template void elf::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab);
1962 template void elf::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab);
1963 template void elf::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab);
1964 template void elf::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);
1965