1 //===- InputFiles.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 "InputFiles.h"
11 #include "Error.h"
12 #include "InputSection.h"
13 #include "LinkerScript.h"
14 #include "Memory.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "SyntheticSections.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/MC/StringTableBuilder.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/TarWriter.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::sys::fs;
34 
35 using namespace lld;
36 using namespace lld::elf;
37 
38 TarWriter *elf::Tar;
39 
40 InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
41 
42 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
43   // The --chroot option changes our virtual root directory.
44   // This is useful when you are dealing with files created by --reproduce.
45   if (!Config->Chroot.empty() && Path.startswith("/"))
46     Path = Saver.save(Config->Chroot + Path);
47 
48   log(Path);
49 
50   auto MBOrErr = MemoryBuffer::getFile(Path);
51   if (auto EC = MBOrErr.getError()) {
52     error("cannot open " + Path + ": " + EC.message());
53     return None;
54   }
55 
56   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
57   MemoryBufferRef MBRef = MB->getMemBufferRef();
58   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
59 
60   if (Tar)
61     Tar->append(relativeToRoot(Path), MBRef.getBuffer());
62   return MBRef;
63 }
64 
65 template <class ELFT> void ObjFile<ELFT>::initializeDwarfLine() {
66   DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(this));
67   const DWARFObject &Obj = Dwarf.getDWARFObj();
68   DwarfLine.reset(new DWARFDebugLine);
69   DWARFDataExtractor LineData(Obj, Obj.getLineSection(), Config->IsLE,
70                               Config->Wordsize);
71 
72   // The second parameter is offset in .debug_line section
73   // for compilation unit (CU) of interest. We have only one
74   // CU (object file), so offset is always 0.
75   DwarfLine->getOrParseLineTable(LineData, 0);
76 }
77 
78 // Returns source line information for a given offset
79 // using DWARF debug info.
80 template <class ELFT>
81 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
82                                                   uint64_t Offset) {
83   llvm::call_once(InitDwarfLine, [this]() { initializeDwarfLine(); });
84 
85   // The offset to CU is 0.
86   const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
87   if (!Tbl)
88     return None;
89 
90   // Use fake address calcuated by adding section file offset and offset in
91   // section. See comments for ObjectInfo class.
92   DILineInfo Info;
93   Tbl->getFileLineInfoForAddress(
94       S->getOffsetInFile() + Offset, nullptr,
95       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
96   if (Info.Line == 0)
97     return None;
98   return Info;
99 }
100 
101 // Returns source line information for a given offset
102 // using DWARF debug info.
103 template <class ELFT>
104 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) {
105   if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
106     return Info->FileName + ":" + std::to_string(Info->Line);
107   return "";
108 }
109 
110 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
111 std::string lld::toString(const InputFile *F) {
112   if (!F)
113     return "<internal>";
114 
115   if (F->ToStringCache.empty()) {
116     if (F->ArchiveName.empty())
117       F->ToStringCache = F->getName();
118     else
119       F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
120   }
121   return F->ToStringCache;
122 }
123 
124 template <class ELFT>
125 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
126   if (ELFT::TargetEndianness == support::little)
127     EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
128   else
129     EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
130 
131   EMachine = getObj().getHeader()->e_machine;
132   OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
133 }
134 
135 template <class ELFT>
136 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
137   return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end());
138 }
139 
140 template <class ELFT>
141 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
142   return check(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX),
143                toString(this));
144 }
145 
146 template <class ELFT>
147 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
148                                    const Elf_Shdr *Symtab) {
149   FirstNonLocal = Symtab->sh_info;
150   ELFSyms = check(getObj().symbols(Symtab), toString(this));
151   if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size())
152     fatal(toString(this) + ": invalid sh_info in symbol table");
153 
154   StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections),
155                       toString(this));
156 }
157 
158 template <class ELFT>
159 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
160     : ELFFileBase<ELFT>(Base::ObjKind, M) {
161   this->ArchiveName = ArchiveName;
162 }
163 
164 template <class ELFT> ArrayRef<SymbolBody *> ObjFile<ELFT>::getLocalSymbols() {
165   if (this->Symbols.empty())
166     return {};
167   return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1);
168 }
169 
170 template <class ELFT>
171 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
172   // Read section and symbol tables.
173   initializeSections(ComdatGroups);
174   initializeSymbols();
175 }
176 
177 // Sections with SHT_GROUP and comdat bits define comdat section groups.
178 // They are identified and deduplicated by group name. This function
179 // returns a group name.
180 template <class ELFT>
181 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
182                                               const Elf_Shdr &Sec) {
183   // Group signatures are stored as symbol names in object files.
184   // sh_info contains a symbol index, so we fetch a symbol and read its name.
185   if (this->ELFSyms.empty())
186     this->initSymtab(
187         Sections,
188         check(object::getSection<ELFT>(Sections, Sec.sh_link), toString(this)));
189 
190   const Elf_Sym *Sym = check(
191       object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), toString(this));
192   StringRef Signature = check(Sym->getName(this->StringTable), toString(this));
193 
194   // As a special case, if a symbol is a section symbol and has no name,
195   // we use a section name as a signature.
196   //
197   // Such SHT_GROUP sections are invalid from the perspective of the ELF
198   // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
199   // older produce such sections as outputs for the -r option, so we need
200   // a bug-compatibility.
201   if (Signature.empty() && Sym->getType() == STT_SECTION)
202     return getSectionName(Sec);
203   return Signature;
204 }
205 
206 template <class ELFT>
207 ArrayRef<typename ObjFile<ELFT>::Elf_Word>
208 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
209   const ELFFile<ELFT> &Obj = this->getObj();
210   ArrayRef<Elf_Word> Entries = check(
211       Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), toString(this));
212   if (Entries.empty() || Entries[0] != GRP_COMDAT)
213     fatal(toString(this) + ": unsupported SHT_GROUP format");
214   return Entries.slice(1);
215 }
216 
217 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
218   // We don't merge sections if -O0 (default is -O1). This makes sometimes
219   // the linker significantly faster, although the output will be bigger.
220   if (Config->Optimize == 0)
221     return false;
222 
223   // Do not merge sections if generating a relocatable object. It makes
224   // the code simpler because we do not need to update relocation addends
225   // to reflect changes introduced by merging. Instead of that we write
226   // such "merge" sections into separate OutputSections and keep SHF_MERGE
227   // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
228   // later during a final linking.
229   if (Config->Relocatable)
230     return false;
231 
232   // A mergeable section with size 0 is useless because they don't have
233   // any data to merge. A mergeable string section with size 0 can be
234   // argued as invalid because it doesn't end with a null character.
235   // We'll avoid a mess by handling them as if they were non-mergeable.
236   if (Sec.sh_size == 0)
237     return false;
238 
239   // Check for sh_entsize. The ELF spec is not clear about the zero
240   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
241   // the section does not hold a table of fixed-size entries". We know
242   // that Rust 1.13 produces a string mergeable section with a zero
243   // sh_entsize. Here we just accept it rather than being picky about it.
244   uint64_t EntSize = Sec.sh_entsize;
245   if (EntSize == 0)
246     return false;
247   if (Sec.sh_size % EntSize)
248     fatal(toString(this) +
249           ": SHF_MERGE section size must be a multiple of sh_entsize");
250 
251   uint64_t Flags = Sec.sh_flags;
252   if (!(Flags & SHF_MERGE))
253     return false;
254   if (Flags & SHF_WRITE)
255     fatal(toString(this) + ": writable SHF_MERGE section is not supported");
256 
257   // Don't try to merge if the alignment is larger than the sh_entsize and this
258   // is not SHF_STRINGS.
259   //
260   // Since this is not a SHF_STRINGS, we would need to pad after every entity.
261   // It would be equivalent for the producer of the .o to just set a larger
262   // sh_entsize.
263   if (Flags & SHF_STRINGS)
264     return true;
265 
266   return Sec.sh_addralign <= EntSize;
267 }
268 
269 template <class ELFT>
270 void ObjFile<ELFT>::initializeSections(
271     DenseSet<CachedHashStringRef> &ComdatGroups) {
272   const ELFFile<ELFT> &Obj = this->getObj();
273 
274   ArrayRef<Elf_Shdr> ObjSections =
275       check(this->getObj().sections(), toString(this));
276   uint64_t Size = ObjSections.size();
277   this->Sections.resize(Size);
278   this->SectionStringTable =
279       check(Obj.getSectionStringTable(ObjSections), toString(this));
280 
281   for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
282     if (this->Sections[I] == &InputSection::Discarded)
283       continue;
284     const Elf_Shdr &Sec = ObjSections[I];
285 
286     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
287     // if -r is given, we'll let the final link discard such sections.
288     // This is compatible with GNU.
289     if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
290       this->Sections[I] = &InputSection::Discarded;
291       continue;
292     }
293 
294     switch (Sec.sh_type) {
295     case SHT_GROUP: {
296       // De-duplicate section groups by their signatures.
297       StringRef Signature = getShtGroupSignature(ObjSections, Sec);
298       bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
299       this->Sections[I] = &InputSection::Discarded;
300 
301       // If it is a new section group, we want to keep group members.
302       // Group leader sections, which contain indices of group members, are
303       // discarded because they are useless beyond this point. The only
304       // exception is the -r option because in order to produce re-linkable
305       // object files, we want to pass through basically everything.
306       if (IsNew) {
307         if (Config->Relocatable)
308           this->Sections[I] = createInputSection(Sec);
309         continue;
310       }
311 
312       // Otherwise, discard group members.
313       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
314         if (SecIndex >= Size)
315           fatal(toString(this) +
316                 ": invalid section index in group: " + Twine(SecIndex));
317         this->Sections[SecIndex] = &InputSection::Discarded;
318       }
319       break;
320     }
321     case SHT_SYMTAB:
322       this->initSymtab(ObjSections, &Sec);
323       break;
324     case SHT_SYMTAB_SHNDX:
325       this->SymtabSHNDX =
326           check(Obj.getSHNDXTable(Sec, ObjSections), toString(this));
327       break;
328     case SHT_STRTAB:
329     case SHT_NULL:
330       break;
331     default:
332       this->Sections[I] = createInputSection(Sec);
333     }
334 
335     // .ARM.exidx sections have a reverse dependency on the InputSection they
336     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
337     if (Sec.sh_flags & SHF_LINK_ORDER) {
338       if (Sec.sh_link >= this->Sections.size())
339         fatal(toString(this) + ": invalid sh_link index: " +
340               Twine(Sec.sh_link));
341       this->Sections[Sec.sh_link]->DependentSections.push_back(
342           this->Sections[I]);
343     }
344   }
345 }
346 
347 template <class ELFT>
348 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
349   uint32_t Idx = Sec.sh_info;
350   if (Idx >= this->Sections.size())
351     fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
352   InputSectionBase *Target = this->Sections[Idx];
353 
354   // Strictly speaking, a relocation section must be included in the
355   // group of the section it relocates. However, LLVM 3.3 and earlier
356   // would fail to do so, so we gracefully handle that case.
357   if (Target == &InputSection::Discarded)
358     return nullptr;
359 
360   if (!Target)
361     fatal(toString(this) + ": unsupported relocation reference");
362   return Target;
363 }
364 
365 // Create a regular InputSection class that has the same contents
366 // as a given section.
367 InputSectionBase *toRegularSection(MergeInputSection *Sec) {
368   auto *Ret = make<InputSection>(Sec->Flags, Sec->Type, Sec->Alignment,
369                                  Sec->Data, Sec->Name);
370   Ret->File = Sec->File;
371   return Ret;
372 }
373 
374 template <class ELFT>
375 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
376   StringRef Name = getSectionName(Sec);
377 
378   switch (Sec.sh_type) {
379   case SHT_ARM_ATTRIBUTES:
380     // FIXME: ARM meta-data section. Retain the first attribute section
381     // we see. The eglibc ARM dynamic loaders require the presence of an
382     // attribute section for dlopen to work.
383     // In a full implementation we would merge all attribute sections.
384     if (InX::ARMAttributes == nullptr) {
385       InX::ARMAttributes = make<InputSection>(this, &Sec, Name);
386       return InX::ARMAttributes;
387     }
388     return &InputSection::Discarded;
389   case SHT_RELA:
390   case SHT_REL: {
391     // Find the relocation target section and associate this
392     // section with it. Target can be discarded, for example
393     // if it is a duplicated member of SHT_GROUP section, we
394     // do not create or proccess relocatable sections then.
395     InputSectionBase *Target = getRelocTarget(Sec);
396     if (!Target)
397       return nullptr;
398 
399     // This section contains relocation information.
400     // If -r is given, we do not interpret or apply relocation
401     // but just copy relocation sections to output.
402     if (Config->Relocatable)
403       return make<InputSection>(this, &Sec, Name);
404 
405     if (Target->FirstRelocation)
406       fatal(toString(this) +
407             ": multiple relocation sections to one section are not supported");
408 
409     // Mergeable sections with relocations are tricky because relocations
410     // need to be taken into account when comparing section contents for
411     // merging. It's not worth supporting such mergeable sections because
412     // they are rare and it'd complicates the internal design (we usually
413     // have to determine if two sections are mergeable early in the link
414     // process much before applying relocations). We simply handle mergeable
415     // sections with relocations as non-mergeable.
416     if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
417       Target = toRegularSection(MS);
418       this->Sections[Sec.sh_info] = Target;
419     }
420 
421     size_t NumRelocations;
422     if (Sec.sh_type == SHT_RELA) {
423       ArrayRef<Elf_Rela> Rels =
424           check(this->getObj().relas(&Sec), toString(this));
425       Target->FirstRelocation = Rels.begin();
426       NumRelocations = Rels.size();
427       Target->AreRelocsRela = true;
428     } else {
429       ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec), toString(this));
430       Target->FirstRelocation = Rels.begin();
431       NumRelocations = Rels.size();
432       Target->AreRelocsRela = false;
433     }
434     assert(isUInt<31>(NumRelocations));
435     Target->NumRelocations = NumRelocations;
436 
437     // Relocation sections processed by the linker are usually removed
438     // from the output, so returning `nullptr` for the normal case.
439     // However, if -emit-relocs is given, we need to leave them in the output.
440     // (Some post link analysis tools need this information.)
441     if (Config->EmitRelocs) {
442       InputSection *RelocSec = make<InputSection>(this, &Sec, Name);
443       // We will not emit relocation section if target was discarded.
444       Target->DependentSections.push_back(RelocSec);
445       return RelocSec;
446     }
447     return nullptr;
448   }
449   }
450 
451   // The GNU linker uses .note.GNU-stack section as a marker indicating
452   // that the code in the object file does not expect that the stack is
453   // executable (in terms of NX bit). If all input files have the marker,
454   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
455   // make the stack non-executable. Most object files have this section as
456   // of 2017.
457   //
458   // But making the stack non-executable is a norm today for security
459   // reasons. Failure to do so may result in a serious security issue.
460   // Therefore, we make LLD always add PT_GNU_STACK unless it is
461   // explicitly told to do otherwise (by -z execstack). Because the stack
462   // executable-ness is controlled solely by command line options,
463   // .note.GNU-stack sections are simply ignored.
464   if (Name == ".note.GNU-stack")
465     return &InputSection::Discarded;
466 
467   // Split stacks is a feature to support a discontiguous stack. At least
468   // as of 2017, it seems that the feature is not being used widely.
469   // Only GNU gold supports that. We don't. For the details about that,
470   // see https://gcc.gnu.org/wiki/SplitStacks
471   if (Name == ".note.GNU-split-stack") {
472     error(toString(this) +
473           ": object file compiled with -fsplit-stack is not supported");
474     return &InputSection::Discarded;
475   }
476 
477   if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
478     return &InputSection::Discarded;
479 
480   // If -gdb-index is given, LLD creates .gdb_index section, and that
481   // section serves the same purpose as .debug_gnu_pub{names,types} sections.
482   // If that's the case, we want to eliminate .debug_gnu_pub{names,types}
483   // because they are redundant and can waste large amount of disk space
484   // (for example, they are about 400 MiB in total for a clang debug build.)
485   // We still create the section and mark it dead so that the gdb index code
486   // can use the InputSection to access the data.
487   if (Config->GdbIndex &&
488       (Name == ".debug_gnu_pubnames" || Name == ".debug_gnu_pubtypes")) {
489     auto *Ret = make<InputSection>(this, &Sec, Name);
490     Script->discard({Ret});
491     return Ret;
492   }
493 
494   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
495   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
496   // sections. Drop those sections to avoid duplicate symbol errors.
497   // FIXME: This is glibc PR20543, we should remove this hack once that has been
498   // fixed for a while.
499   if (Name.startswith(".gnu.linkonce."))
500     return &InputSection::Discarded;
501 
502   // The linker merges EH (exception handling) frames and creates a
503   // .eh_frame_hdr section for runtime. So we handle them with a special
504   // class. For relocatable outputs, they are just passed through.
505   if (Name == ".eh_frame" && !Config->Relocatable)
506     return make<EhInputSection>(this, &Sec, Name);
507 
508   if (shouldMerge(Sec))
509     return make<MergeInputSection>(this, &Sec, Name);
510   return make<InputSection>(this, &Sec, Name);
511 }
512 
513 template <class ELFT>
514 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
515   return check(this->getObj().getSectionName(&Sec, SectionStringTable),
516                toString(this));
517 }
518 
519 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
520   this->Symbols.reserve(this->ELFSyms.size());
521   for (const Elf_Sym &Sym : this->ELFSyms)
522     this->Symbols.push_back(createSymbolBody(&Sym));
523 }
524 
525 template <class ELFT>
526 InputSectionBase *ObjFile<ELFT>::getSection(const Elf_Sym &Sym) const {
527   uint32_t Index = this->getSectionIndex(Sym);
528   if (Index >= this->Sections.size())
529     fatal(toString(this) + ": invalid section index: " + Twine(Index));
530   InputSectionBase *S = this->Sections[Index];
531 
532   // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
533   // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
534   // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
535   // In this case it is fine for section to be null here as we do not
536   // allocate sections of these types.
537   if (!S) {
538     if (Index == 0 || Sym.getType() == STT_SECTION ||
539         Sym.getType() == STT_NOTYPE)
540       return nullptr;
541     fatal(toString(this) + ": invalid section index: " + Twine(Index));
542   }
543 
544   if (S == &InputSection::Discarded)
545     return S;
546   return S->Repl;
547 }
548 
549 template <class ELFT>
550 SymbolBody *ObjFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
551   int Binding = Sym->getBinding();
552   InputSectionBase *Sec = getSection(*Sym);
553 
554   uint8_t StOther = Sym->st_other;
555   uint8_t Type = Sym->getType();
556   uint64_t Value = Sym->st_value;
557   uint64_t Size = Sym->st_size;
558 
559   if (Binding == STB_LOCAL) {
560     if (Sym->getType() == STT_FILE)
561       SourceFile = check(Sym->getName(this->StringTable), toString(this));
562 
563     if (this->StringTable.size() <= Sym->st_name)
564       fatal(toString(this) + ": invalid symbol name offset");
565 
566     StringRefZ Name = this->StringTable.data() + Sym->st_name;
567     if (Sym->st_shndx == SHN_UNDEF)
568       return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type);
569 
570     return make<DefinedRegular>(Name, /*IsLocal=*/true, StOther, Type, Value,
571                                 Size, Sec);
572   }
573 
574   StringRef Name = check(Sym->getName(this->StringTable), toString(this));
575 
576   switch (Sym->st_shndx) {
577   case SHN_UNDEF:
578     return Symtab
579         ->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, StOther, Type,
580                              /*CanOmitFromDynSym=*/false, this)
581         ->body();
582   case SHN_COMMON:
583     if (Value == 0 || Value >= UINT32_MAX)
584       fatal(toString(this) + ": common symbol '" + Name +
585             "' has invalid alignment: " + Twine(Value));
586     return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, this)
587         ->body();
588   }
589 
590   switch (Binding) {
591   default:
592     fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
593   case STB_GLOBAL:
594   case STB_WEAK:
595   case STB_GNU_UNIQUE:
596     if (Sec == &InputSection::Discarded)
597       return Symtab
598           ->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, StOther, Type,
599                                /*CanOmitFromDynSym=*/false, this)
600           ->body();
601     return Symtab
602         ->addRegular<ELFT>(Name, StOther, Type, Value, Size, Binding, Sec, this)
603         ->body();
604   }
605 }
606 
607 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
608     : InputFile(ArchiveKind, File->getMemoryBufferRef()),
609       File(std::move(File)) {}
610 
611 template <class ELFT> void ArchiveFile::parse() {
612   Symbols.reserve(File->getNumberOfSymbols());
613   for (const Archive::Symbol &Sym : File->symbols())
614     Symbols.push_back(Symtab->addLazyArchive<ELFT>(this, Sym)->body());
615 }
616 
617 // Returns a buffer pointing to a member file containing a given symbol.
618 std::pair<MemoryBufferRef, uint64_t>
619 ArchiveFile::getMember(const Archive::Symbol *Sym) {
620   Archive::Child C =
621       check(Sym->getMember(), toString(this) +
622                                   ": could not get the member for symbol " +
623                                   Sym->getName());
624 
625   if (!Seen.insert(C.getChildOffset()).second)
626     return {MemoryBufferRef(), 0};
627 
628   MemoryBufferRef Ret =
629       check(C.getMemoryBufferRef(),
630             toString(this) +
631                 ": could not get the buffer for the member defining symbol " +
632                 Sym->getName());
633 
634   if (C.getParent()->isThin() && Tar)
635     Tar->append(relativeToRoot(check(C.getFullName(), toString(this))),
636                 Ret.getBuffer());
637   if (C.getParent()->isThin())
638     return {Ret, 0};
639   return {Ret, C.getChildOffset()};
640 }
641 
642 template <class ELFT>
643 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
644     : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
645       AsNeeded(Config->AsNeeded) {}
646 
647 template <class ELFT>
648 const typename ELFT::Shdr *
649 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
650   return check(
651       this->getObj().getSection(&Sym, this->ELFSyms, this->SymtabSHNDX),
652       toString(this));
653 }
654 
655 // Partially parse the shared object file so that we can call
656 // getSoName on this object.
657 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
658   const Elf_Shdr *DynamicSec = nullptr;
659   const ELFFile<ELFT> Obj = this->getObj();
660   ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
661 
662   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
663   for (const Elf_Shdr &Sec : Sections) {
664     switch (Sec.sh_type) {
665     default:
666       continue;
667     case SHT_DYNSYM:
668       this->initSymtab(Sections, &Sec);
669       break;
670     case SHT_DYNAMIC:
671       DynamicSec = &Sec;
672       break;
673     case SHT_SYMTAB_SHNDX:
674       this->SymtabSHNDX =
675           check(Obj.getSHNDXTable(Sec, Sections), toString(this));
676       break;
677     case SHT_GNU_versym:
678       this->VersymSec = &Sec;
679       break;
680     case SHT_GNU_verdef:
681       this->VerdefSec = &Sec;
682       break;
683     }
684   }
685 
686   if (this->VersymSec && this->ELFSyms.empty())
687     error("SHT_GNU_versym should be associated with symbol table");
688 
689   // Search for a DT_SONAME tag to initialize this->SoName.
690   if (!DynamicSec)
691     return;
692   ArrayRef<Elf_Dyn> Arr =
693       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
694             toString(this));
695   for (const Elf_Dyn &Dyn : Arr) {
696     if (Dyn.d_tag == DT_SONAME) {
697       uint64_t Val = Dyn.getVal();
698       if (Val >= this->StringTable.size())
699         fatal(toString(this) + ": invalid DT_SONAME entry");
700       SoName = this->StringTable.data() + Val;
701       return;
702     }
703   }
704 }
705 
706 // Parse the version definitions in the object file if present. Returns a vector
707 // whose nth element contains a pointer to the Elf_Verdef for version identifier
708 // n. Version identifiers that are not definitions map to nullptr. The array
709 // always has at least length 1.
710 template <class ELFT>
711 std::vector<const typename ELFT::Verdef *>
712 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
713   std::vector<const Elf_Verdef *> Verdefs(1);
714   // We only need to process symbol versions for this DSO if it has both a
715   // versym and a verdef section, which indicates that the DSO contains symbol
716   // version definitions.
717   if (!VersymSec || !VerdefSec)
718     return Verdefs;
719 
720   // The location of the first global versym entry.
721   const char *Base = this->MB.getBuffer().data();
722   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
723            this->FirstNonLocal;
724 
725   // We cannot determine the largest verdef identifier without inspecting
726   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
727   // sequentially starting from 1, so we predict that the largest identifier
728   // will be VerdefCount.
729   unsigned VerdefCount = VerdefSec->sh_info;
730   Verdefs.resize(VerdefCount + 1);
731 
732   // Build the Verdefs array by following the chain of Elf_Verdef objects
733   // from the start of the .gnu.version_d section.
734   const char *Verdef = Base + VerdefSec->sh_offset;
735   for (unsigned I = 0; I != VerdefCount; ++I) {
736     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
737     Verdef += CurVerdef->vd_next;
738     unsigned VerdefIndex = CurVerdef->vd_ndx;
739     if (Verdefs.size() <= VerdefIndex)
740       Verdefs.resize(VerdefIndex + 1);
741     Verdefs[VerdefIndex] = CurVerdef;
742   }
743 
744   return Verdefs;
745 }
746 
747 // Fully parse the shared object file. This must be called after parseSoName().
748 template <class ELFT> void SharedFile<ELFT>::parseRest() {
749   // Create mapping from version identifiers to Elf_Verdef entries.
750   const Elf_Versym *Versym = nullptr;
751   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
752 
753   Elf_Sym_Range Syms = this->getGlobalELFSyms();
754   for (const Elf_Sym &Sym : Syms) {
755     unsigned VersymIndex = 0;
756     if (Versym) {
757       VersymIndex = Versym->vs_index;
758       ++Versym;
759     }
760     bool Hidden = VersymIndex & VERSYM_HIDDEN;
761     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
762 
763     StringRef Name = check(Sym.getName(this->StringTable), toString(this));
764     if (Sym.isUndefined()) {
765       Undefs.push_back(Name);
766       continue;
767     }
768 
769     // Ignore local symbols.
770     if (Versym && VersymIndex == VER_NDX_LOCAL)
771       continue;
772 
773     const Elf_Verdef *V =
774         VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
775 
776     if (!Hidden)
777       Symtab->addShared(this, Name, Sym, V);
778 
779     // Also add the symbol with the versioned name to handle undefined symbols
780     // with explicit versions.
781     if (V) {
782       StringRef VerName = this->StringTable.data() + V->getAux()->vda_name;
783       Name = Saver.save(Name + "@" + VerName);
784       Symtab->addShared(this, Name, Sym, V);
785     }
786   }
787 }
788 
789 static ELFKind getBitcodeELFKind(const Triple &T) {
790   if (T.isLittleEndian())
791     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
792   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
793 }
794 
795 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
796   switch (T.getArch()) {
797   case Triple::aarch64:
798     return EM_AARCH64;
799   case Triple::arm:
800   case Triple::thumb:
801     return EM_ARM;
802   case Triple::avr:
803     return EM_AVR;
804   case Triple::mips:
805   case Triple::mipsel:
806   case Triple::mips64:
807   case Triple::mips64el:
808     return EM_MIPS;
809   case Triple::ppc:
810     return EM_PPC;
811   case Triple::ppc64:
812     return EM_PPC64;
813   case Triple::x86:
814     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
815   case Triple::x86_64:
816     return EM_X86_64;
817   default:
818     fatal(Path + ": could not infer e_machine from bitcode target triple " +
819           T.str());
820   }
821 }
822 
823 std::vector<BitcodeFile *> BitcodeFile::Instances;
824 
825 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
826                          uint64_t OffsetInArchive)
827     : InputFile(BitcodeKind, MB) {
828   this->ArchiveName = ArchiveName;
829 
830   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
831   // (the fully resolved path of the archive) + member name + offset of the
832   // member in the archive.
833   // ThinLTO uses the MemoryBufferRef identifier to access its internal
834   // data structures and if two archives define two members with the same name,
835   // this causes a collision which result in only one of the objects being
836   // taken into consideration at LTO time (which very likely causes undefined
837   // symbols later in the link stage).
838   MemoryBufferRef MBRef(MB.getBuffer(),
839                         Saver.save(ArchiveName + MB.getBufferIdentifier() +
840                                    utostr(OffsetInArchive)));
841   Obj = check(lto::InputFile::create(MBRef), toString(this));
842 
843   Triple T(Obj->getTargetTriple());
844   EKind = getBitcodeELFKind(T);
845   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
846 }
847 
848 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
849   switch (GvVisibility) {
850   case GlobalValue::DefaultVisibility:
851     return STV_DEFAULT;
852   case GlobalValue::HiddenVisibility:
853     return STV_HIDDEN;
854   case GlobalValue::ProtectedVisibility:
855     return STV_PROTECTED;
856   }
857   llvm_unreachable("unknown visibility");
858 }
859 
860 template <class ELFT>
861 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
862                                    const lto::InputFile::Symbol &ObjSym,
863                                    BitcodeFile *F) {
864   StringRef NameRef = Saver.save(ObjSym.getName());
865   uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
866 
867   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
868   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
869   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
870 
871   int C = ObjSym.getComdatIndex();
872   if (C != -1 && !KeptComdats[C])
873     return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding,
874                                       Visibility, Type, CanOmitFromDynSym, F);
875 
876   if (ObjSym.isUndefined())
877     return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding,
878                                       Visibility, Type, CanOmitFromDynSym, F);
879 
880   if (ObjSym.isCommon())
881     return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
882                              ObjSym.getCommonAlignment(), Binding, Visibility,
883                              STT_OBJECT, F);
884 
885   return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
886                             CanOmitFromDynSym, F);
887 }
888 
889 template <class ELFT>
890 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
891   std::vector<bool> KeptComdats;
892   for (StringRef S : Obj->getComdatTable())
893     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
894 
895   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
896     Symbols.push_back(
897         createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)->body());
898 }
899 
900 static ELFKind getELFKind(MemoryBufferRef MB) {
901   unsigned char Size;
902   unsigned char Endian;
903   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
904 
905   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
906     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
907   if (Size != ELFCLASS32 && Size != ELFCLASS64)
908     fatal(MB.getBufferIdentifier() + ": invalid file class");
909 
910   size_t BufSize = MB.getBuffer().size();
911   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
912       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
913     fatal(MB.getBufferIdentifier() + ": file is too short");
914 
915   if (Size == ELFCLASS32)
916     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
917   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
918 }
919 
920 std::vector<BinaryFile *> BinaryFile::Instances;
921 
922 template <class ELFT> void BinaryFile::parse() {
923   ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
924   auto *Section =
925       make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data");
926   Sections.push_back(Section);
927 
928   // For each input file foo that is embedded to a result as a binary
929   // blob, we define _binary_foo_{start,end,size} symbols, so that
930   // user programs can access blobs by name. Non-alphanumeric
931   // characters in a filename are replaced with underscore.
932   std::string S = "_binary_" + MB.getBufferIdentifier().str();
933   for (size_t I = 0; I < S.size(); ++I)
934     if (!elf::isAlnum(S[I]))
935       S[I] = '_';
936 
937   Symtab->addRegular<ELFT>(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT,
938                            0, 0, STB_GLOBAL, Section, nullptr);
939   Symtab->addRegular<ELFT>(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
940                            Data.size(), 0, STB_GLOBAL, Section, nullptr);
941   Symtab->addRegular<ELFT>(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
942                            Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
943 }
944 
945 static bool isBitcode(MemoryBufferRef MB) {
946   using namespace sys::fs;
947   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
948 }
949 
950 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
951                                  uint64_t OffsetInArchive) {
952   if (isBitcode(MB))
953     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
954 
955   switch (getELFKind(MB)) {
956   case ELF32LEKind:
957     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
958   case ELF32BEKind:
959     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
960   case ELF64LEKind:
961     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
962   case ELF64BEKind:
963     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
964   default:
965     llvm_unreachable("getELFKind");
966   }
967 }
968 
969 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
970   switch (getELFKind(MB)) {
971   case ELF32LEKind:
972     return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
973   case ELF32BEKind:
974     return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
975   case ELF64LEKind:
976     return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
977   case ELF64BEKind:
978     return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
979   default:
980     llvm_unreachable("getELFKind");
981   }
982 }
983 
984 MemoryBufferRef LazyObjFile::getBuffer() {
985   if (Seen)
986     return MemoryBufferRef();
987   Seen = true;
988   return MB;
989 }
990 
991 InputFile *LazyObjFile::fetch() {
992   MemoryBufferRef MBRef = getBuffer();
993   if (MBRef.getBuffer().empty())
994     return nullptr;
995   return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
996 }
997 
998 template <class ELFT> void LazyObjFile::parse() {
999   for (StringRef Sym : getSymbolNames())
1000     Symtab->addLazyObject<ELFT>(Sym, *this);
1001 }
1002 
1003 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1004   typedef typename ELFT::Shdr Elf_Shdr;
1005   typedef typename ELFT::Sym Elf_Sym;
1006   typedef typename ELFT::SymRange Elf_Sym_Range;
1007 
1008   const ELFFile<ELFT> Obj(this->MB.getBuffer());
1009   ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
1010   for (const Elf_Shdr &Sec : Sections) {
1011     if (Sec.sh_type != SHT_SYMTAB)
1012       continue;
1013 
1014     Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this));
1015     uint32_t FirstNonLocal = Sec.sh_info;
1016     StringRef StringTable =
1017         check(Obj.getStringTableForSymtab(Sec, Sections), toString(this));
1018     std::vector<StringRef> V;
1019 
1020     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1021       if (Sym.st_shndx != SHN_UNDEF)
1022         V.push_back(check(Sym.getName(StringTable), toString(this)));
1023     return V;
1024   }
1025   return {};
1026 }
1027 
1028 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1029   std::unique_ptr<lto::InputFile> Obj =
1030       check(lto::InputFile::create(this->MB), toString(this));
1031   std::vector<StringRef> V;
1032   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1033     if (!Sym.isUndefined())
1034       V.push_back(Saver.save(Sym.getName()));
1035   return V;
1036 }
1037 
1038 // Returns a vector of globally-visible defined symbol names.
1039 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1040   if (isBitcode(this->MB))
1041     return getBitcodeSymbols();
1042 
1043   switch (getELFKind(this->MB)) {
1044   case ELF32LEKind:
1045     return getElfSymbols<ELF32LE>();
1046   case ELF32BEKind:
1047     return getElfSymbols<ELF32BE>();
1048   case ELF64LEKind:
1049     return getElfSymbols<ELF64LE>();
1050   case ELF64BEKind:
1051     return getElfSymbols<ELF64BE>();
1052   default:
1053     llvm_unreachable("getELFKind");
1054   }
1055 }
1056 
1057 template void ArchiveFile::parse<ELF32LE>();
1058 template void ArchiveFile::parse<ELF32BE>();
1059 template void ArchiveFile::parse<ELF64LE>();
1060 template void ArchiveFile::parse<ELF64BE>();
1061 
1062 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1063 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1064 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1065 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1066 
1067 template void LazyObjFile::parse<ELF32LE>();
1068 template void LazyObjFile::parse<ELF32BE>();
1069 template void LazyObjFile::parse<ELF64LE>();
1070 template void LazyObjFile::parse<ELF64BE>();
1071 
1072 template class elf::ELFFileBase<ELF32LE>;
1073 template class elf::ELFFileBase<ELF32BE>;
1074 template class elf::ELFFileBase<ELF64LE>;
1075 template class elf::ELFFileBase<ELF64BE>;
1076 
1077 template class elf::ObjFile<ELF32LE>;
1078 template class elf::ObjFile<ELF32BE>;
1079 template class elf::ObjFile<ELF64LE>;
1080 template class elf::ObjFile<ELF64BE>;
1081 
1082 template class elf::SharedFile<ELF32LE>;
1083 template class elf::SharedFile<ELF32BE>;
1084 template class elf::SharedFile<ELF64LE>;
1085 template class elf::SharedFile<ELF64BE>;
1086 
1087 template void BinaryFile::parse<ELF32LE>();
1088 template void BinaryFile::parse<ELF32BE>();
1089 template void BinaryFile::parse<ELF64LE>();
1090 template void BinaryFile::parse<ELF64BE>();
1091