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