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(
620         Symtab->addLazyArchive<ELFT>(Sym.getName(), this, Sym)->body());
621 }
622 
623 // Returns a buffer pointing to a member file containing a given symbol.
624 std::pair<MemoryBufferRef, uint64_t>
625 ArchiveFile::getMember(const Archive::Symbol *Sym) {
626   Archive::Child C =
627       check(Sym->getMember(), toString(this) +
628                                   ": could not get the member for symbol " +
629                                   Sym->getName());
630 
631   if (!Seen.insert(C.getChildOffset()).second)
632     return {MemoryBufferRef(), 0};
633 
634   MemoryBufferRef Ret =
635       check(C.getMemoryBufferRef(),
636             toString(this) +
637                 ": could not get the buffer for the member defining symbol " +
638                 Sym->getName());
639 
640   if (C.getParent()->isThin() && Tar)
641     Tar->append(relativeToRoot(check(C.getFullName(), toString(this))),
642                 Ret.getBuffer());
643   if (C.getParent()->isThin())
644     return {Ret, 0};
645   return {Ret, C.getChildOffset()};
646 }
647 
648 template <class ELFT>
649 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
650     : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
651       AsNeeded(Config->AsNeeded) {}
652 
653 template <class ELFT>
654 const typename ELFT::Shdr *
655 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
656   return check(
657       this->getObj().getSection(&Sym, this->ELFSyms, this->SymtabSHNDX),
658       toString(this));
659 }
660 
661 // Partially parse the shared object file so that we can call
662 // getSoName on this object.
663 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
664   const Elf_Shdr *DynamicSec = nullptr;
665   const ELFFile<ELFT> Obj = this->getObj();
666   ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
667 
668   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
669   for (const Elf_Shdr &Sec : Sections) {
670     switch (Sec.sh_type) {
671     default:
672       continue;
673     case SHT_DYNSYM:
674       this->initSymtab(Sections, &Sec);
675       break;
676     case SHT_DYNAMIC:
677       DynamicSec = &Sec;
678       break;
679     case SHT_SYMTAB_SHNDX:
680       this->SymtabSHNDX =
681           check(Obj.getSHNDXTable(Sec, Sections), toString(this));
682       break;
683     case SHT_GNU_versym:
684       this->VersymSec = &Sec;
685       break;
686     case SHT_GNU_verdef:
687       this->VerdefSec = &Sec;
688       break;
689     }
690   }
691 
692   if (this->VersymSec && this->ELFSyms.empty())
693     error("SHT_GNU_versym should be associated with symbol table");
694 
695   // Search for a DT_SONAME tag to initialize this->SoName.
696   if (!DynamicSec)
697     return;
698   ArrayRef<Elf_Dyn> Arr =
699       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
700             toString(this));
701   for (const Elf_Dyn &Dyn : Arr) {
702     if (Dyn.d_tag == DT_SONAME) {
703       uint64_t Val = Dyn.getVal();
704       if (Val >= this->StringTable.size())
705         fatal(toString(this) + ": invalid DT_SONAME entry");
706       SoName = this->StringTable.data() + Val;
707       return;
708     }
709   }
710 }
711 
712 // Parse the version definitions in the object file if present. Returns a vector
713 // whose nth element contains a pointer to the Elf_Verdef for version identifier
714 // n. Version identifiers that are not definitions map to nullptr. The array
715 // always has at least length 1.
716 template <class ELFT>
717 std::vector<const typename ELFT::Verdef *>
718 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
719   std::vector<const Elf_Verdef *> Verdefs(1);
720   // We only need to process symbol versions for this DSO if it has both a
721   // versym and a verdef section, which indicates that the DSO contains symbol
722   // version definitions.
723   if (!VersymSec || !VerdefSec)
724     return Verdefs;
725 
726   // The location of the first global versym entry.
727   const char *Base = this->MB.getBuffer().data();
728   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
729            this->FirstNonLocal;
730 
731   // We cannot determine the largest verdef identifier without inspecting
732   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
733   // sequentially starting from 1, so we predict that the largest identifier
734   // will be VerdefCount.
735   unsigned VerdefCount = VerdefSec->sh_info;
736   Verdefs.resize(VerdefCount + 1);
737 
738   // Build the Verdefs array by following the chain of Elf_Verdef objects
739   // from the start of the .gnu.version_d section.
740   const char *Verdef = Base + VerdefSec->sh_offset;
741   for (unsigned I = 0; I != VerdefCount; ++I) {
742     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
743     Verdef += CurVerdef->vd_next;
744     unsigned VerdefIndex = CurVerdef->vd_ndx;
745     if (Verdefs.size() <= VerdefIndex)
746       Verdefs.resize(VerdefIndex + 1);
747     Verdefs[VerdefIndex] = CurVerdef;
748   }
749 
750   return Verdefs;
751 }
752 
753 // Fully parse the shared object file. This must be called after parseSoName().
754 template <class ELFT> void SharedFile<ELFT>::parseRest() {
755   // Create mapping from version identifiers to Elf_Verdef entries.
756   const Elf_Versym *Versym = nullptr;
757   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
758 
759   Elf_Sym_Range Syms = this->getGlobalELFSyms();
760   for (const Elf_Sym &Sym : Syms) {
761     unsigned VersymIndex = 0;
762     if (Versym) {
763       VersymIndex = Versym->vs_index;
764       ++Versym;
765     }
766     bool Hidden = VersymIndex & VERSYM_HIDDEN;
767     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
768 
769     StringRef Name = check(Sym.getName(this->StringTable), toString(this));
770     if (Sym.isUndefined()) {
771       Undefs.push_back(Name);
772       continue;
773     }
774 
775     // Ignore local symbols.
776     if (Versym && VersymIndex == VER_NDX_LOCAL)
777       continue;
778 
779     const Elf_Verdef *V =
780         VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
781 
782     if (!Hidden)
783       Symtab->addShared(Name, this, Sym, V);
784 
785     // Also add the symbol with the versioned name to handle undefined symbols
786     // with explicit versions.
787     if (V) {
788       StringRef VerName = this->StringTable.data() + V->getAux()->vda_name;
789       Name = Saver.save(Name + "@" + VerName);
790       Symtab->addShared(Name, this, Sym, V);
791     }
792   }
793 }
794 
795 static ELFKind getBitcodeELFKind(const Triple &T) {
796   if (T.isLittleEndian())
797     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
798   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
799 }
800 
801 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
802   switch (T.getArch()) {
803   case Triple::aarch64:
804     return EM_AARCH64;
805   case Triple::arm:
806   case Triple::thumb:
807     return EM_ARM;
808   case Triple::avr:
809     return EM_AVR;
810   case Triple::mips:
811   case Triple::mipsel:
812   case Triple::mips64:
813   case Triple::mips64el:
814     return EM_MIPS;
815   case Triple::ppc:
816     return EM_PPC;
817   case Triple::ppc64:
818     return EM_PPC64;
819   case Triple::x86:
820     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
821   case Triple::x86_64:
822     return EM_X86_64;
823   default:
824     fatal(Path + ": could not infer e_machine from bitcode target triple " +
825           T.str());
826   }
827 }
828 
829 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
830                          uint64_t OffsetInArchive)
831     : InputFile(BitcodeKind, MB) {
832   this->ArchiveName = ArchiveName;
833 
834   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
835   // (the fully resolved path of the archive) + member name + offset of the
836   // member in the archive.
837   // ThinLTO uses the MemoryBufferRef identifier to access its internal
838   // data structures and if two archives define two members with the same name,
839   // this causes a collision which result in only one of the objects being
840   // taken into consideration at LTO time (which very likely causes undefined
841   // symbols later in the link stage).
842   MemoryBufferRef MBRef(MB.getBuffer(),
843                         Saver.save(ArchiveName + MB.getBufferIdentifier() +
844                                    utostr(OffsetInArchive)));
845   Obj = check(lto::InputFile::create(MBRef), toString(this));
846 
847   Triple T(Obj->getTargetTriple());
848   EKind = getBitcodeELFKind(T);
849   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
850 }
851 
852 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
853   switch (GvVisibility) {
854   case GlobalValue::DefaultVisibility:
855     return STV_DEFAULT;
856   case GlobalValue::HiddenVisibility:
857     return STV_HIDDEN;
858   case GlobalValue::ProtectedVisibility:
859     return STV_PROTECTED;
860   }
861   llvm_unreachable("unknown visibility");
862 }
863 
864 template <class ELFT>
865 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
866                                    const lto::InputFile::Symbol &ObjSym,
867                                    BitcodeFile *F) {
868   StringRef NameRef = Saver.save(ObjSym.getName());
869   uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
870 
871   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
872   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
873   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
874 
875   int C = ObjSym.getComdatIndex();
876   if (C != -1 && !KeptComdats[C])
877     return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding,
878                                       Visibility, Type, CanOmitFromDynSym, F);
879 
880   if (ObjSym.isUndefined())
881     return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding,
882                                       Visibility, Type, CanOmitFromDynSym, F);
883 
884   if (ObjSym.isCommon())
885     return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
886                              ObjSym.getCommonAlignment(), Binding, Visibility,
887                              STT_OBJECT, F);
888 
889   return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
890                             CanOmitFromDynSym, F);
891 }
892 
893 template <class ELFT>
894 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
895   std::vector<bool> KeptComdats;
896   for (StringRef S : Obj->getComdatTable())
897     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
898 
899   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
900     Symbols.push_back(
901         createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)->body());
902 }
903 
904 static ELFKind getELFKind(MemoryBufferRef MB) {
905   unsigned char Size;
906   unsigned char Endian;
907   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
908 
909   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
910     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
911   if (Size != ELFCLASS32 && Size != ELFCLASS64)
912     fatal(MB.getBufferIdentifier() + ": invalid file class");
913 
914   size_t BufSize = MB.getBuffer().size();
915   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
916       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
917     fatal(MB.getBufferIdentifier() + ": file is too short");
918 
919   if (Size == ELFCLASS32)
920     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
921   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
922 }
923 
924 template <class ELFT> void BinaryFile::parse() {
925   ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
926   auto *Section =
927       make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data");
928   Sections.push_back(Section);
929 
930   // For each input file foo that is embedded to a result as a binary
931   // blob, we define _binary_foo_{start,end,size} symbols, so that
932   // user programs can access blobs by name. Non-alphanumeric
933   // characters in a filename are replaced with underscore.
934   std::string S = "_binary_" + MB.getBufferIdentifier().str();
935   for (size_t I = 0; I < S.size(); ++I)
936     if (!elf::isAlnum(S[I]))
937       S[I] = '_';
938 
939   Symtab->addRegular<ELFT>(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT,
940                            0, 0, STB_GLOBAL, Section, nullptr);
941   Symtab->addRegular<ELFT>(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
942                            Data.size(), 0, STB_GLOBAL, Section, nullptr);
943   Symtab->addRegular<ELFT>(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
944                            Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
945 }
946 
947 static bool isBitcode(MemoryBufferRef MB) {
948   using namespace sys::fs;
949   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
950 }
951 
952 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
953                                  uint64_t OffsetInArchive) {
954   if (isBitcode(MB))
955     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
956 
957   switch (getELFKind(MB)) {
958   case ELF32LEKind:
959     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
960   case ELF32BEKind:
961     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
962   case ELF64LEKind:
963     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
964   case ELF64BEKind:
965     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
966   default:
967     llvm_unreachable("getELFKind");
968   }
969 }
970 
971 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
972   switch (getELFKind(MB)) {
973   case ELF32LEKind:
974     return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
975   case ELF32BEKind:
976     return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
977   case ELF64LEKind:
978     return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
979   case ELF64BEKind:
980     return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
981   default:
982     llvm_unreachable("getELFKind");
983   }
984 }
985 
986 MemoryBufferRef LazyObjFile::getBuffer() {
987   if (Seen)
988     return MemoryBufferRef();
989   Seen = true;
990   return MB;
991 }
992 
993 InputFile *LazyObjFile::fetch() {
994   MemoryBufferRef MBRef = getBuffer();
995   if (MBRef.getBuffer().empty())
996     return nullptr;
997   return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
998 }
999 
1000 template <class ELFT> void LazyObjFile::parse() {
1001   for (StringRef Sym : getSymbolNames())
1002     Symtab->addLazyObject<ELFT>(Sym, *this);
1003 }
1004 
1005 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1006   typedef typename ELFT::Shdr Elf_Shdr;
1007   typedef typename ELFT::Sym Elf_Sym;
1008   typedef typename ELFT::SymRange Elf_Sym_Range;
1009 
1010   const ELFFile<ELFT> Obj(this->MB.getBuffer());
1011   ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
1012   for (const Elf_Shdr &Sec : Sections) {
1013     if (Sec.sh_type != SHT_SYMTAB)
1014       continue;
1015 
1016     Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this));
1017     uint32_t FirstNonLocal = Sec.sh_info;
1018     StringRef StringTable =
1019         check(Obj.getStringTableForSymtab(Sec, Sections), toString(this));
1020     std::vector<StringRef> V;
1021 
1022     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1023       if (Sym.st_shndx != SHN_UNDEF)
1024         V.push_back(check(Sym.getName(StringTable), toString(this)));
1025     return V;
1026   }
1027   return {};
1028 }
1029 
1030 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1031   std::unique_ptr<lto::InputFile> Obj =
1032       check(lto::InputFile::create(this->MB), toString(this));
1033   std::vector<StringRef> V;
1034   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1035     if (!Sym.isUndefined())
1036       V.push_back(Saver.save(Sym.getName()));
1037   return V;
1038 }
1039 
1040 // Returns a vector of globally-visible defined symbol names.
1041 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1042   if (isBitcode(this->MB))
1043     return getBitcodeSymbols();
1044 
1045   switch (getELFKind(this->MB)) {
1046   case ELF32LEKind:
1047     return getElfSymbols<ELF32LE>();
1048   case ELF32BEKind:
1049     return getElfSymbols<ELF32BE>();
1050   case ELF64LEKind:
1051     return getElfSymbols<ELF64LE>();
1052   case ELF64BEKind:
1053     return getElfSymbols<ELF64BE>();
1054   default:
1055     llvm_unreachable("getELFKind");
1056   }
1057 }
1058 
1059 template void ArchiveFile::parse<ELF32LE>();
1060 template void ArchiveFile::parse<ELF32BE>();
1061 template void ArchiveFile::parse<ELF64LE>();
1062 template void ArchiveFile::parse<ELF64BE>();
1063 
1064 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1065 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1066 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1067 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1068 
1069 template void LazyObjFile::parse<ELF32LE>();
1070 template void LazyObjFile::parse<ELF32BE>();
1071 template void LazyObjFile::parse<ELF64LE>();
1072 template void LazyObjFile::parse<ELF64BE>();
1073 
1074 template class elf::ELFFileBase<ELF32LE>;
1075 template class elf::ELFFileBase<ELF32BE>;
1076 template class elf::ELFFileBase<ELF64LE>;
1077 template class elf::ELFFileBase<ELF64BE>;
1078 
1079 template class elf::ObjFile<ELF32LE>;
1080 template class elf::ObjFile<ELF32BE>;
1081 template class elf::ObjFile<ELF64LE>;
1082 template class elf::ObjFile<ELF64BE>;
1083 
1084 template class elf::SharedFile<ELF32LE>;
1085 template class elf::SharedFile<ELF32BE>;
1086 template class elf::SharedFile<ELF64LE>;
1087 template class elf::SharedFile<ELF64BE>;
1088 
1089 template void BinaryFile::parse<ELF32LE>();
1090 template void BinaryFile::parse<ELF32BE>();
1091 template void BinaryFile::parse<ELF64LE>();
1092 template void BinaryFile::parse<ELF64BE>();
1093