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