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           cast<InputSection>(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   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
486   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
487   // sections. Drop those sections to avoid duplicate symbol errors.
488   // FIXME: This is glibc PR20543, we should remove this hack once that has been
489   // fixed for a while.
490   if (Name.startswith(".gnu.linkonce."))
491     return &InputSection::Discarded;
492 
493   // The linker merges EH (exception handling) frames and creates a
494   // .eh_frame_hdr section for runtime. So we handle them with a special
495   // class. For relocatable outputs, they are just passed through.
496   if (Name == ".eh_frame" && !Config->Relocatable)
497     return make<EhInputSection>(this, &Sec, Name);
498 
499   if (shouldMerge(Sec))
500     return make<MergeInputSection>(this, &Sec, Name);
501   return make<InputSection>(this, &Sec, Name);
502 }
503 
504 template <class ELFT>
505 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
506   return check(this->getObj().getSectionName(&Sec, SectionStringTable),
507                toString(this));
508 }
509 
510 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
511   this->Symbols.reserve(this->ELFSyms.size());
512   for (const Elf_Sym &Sym : this->ELFSyms)
513     this->Symbols.push_back(createSymbolBody(&Sym));
514 }
515 
516 template <class ELFT>
517 InputSectionBase *ObjFile<ELFT>::getSection(const Elf_Sym &Sym) const {
518   uint32_t Index = this->getSectionIndex(Sym);
519   if (Index >= this->Sections.size())
520     fatal(toString(this) + ": invalid section index: " + Twine(Index));
521   InputSectionBase *S = this->Sections[Index];
522 
523   // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
524   // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
525   // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
526   // In this case it is fine for section to be null here as we do not
527   // allocate sections of these types.
528   if (!S) {
529     if (Index == 0 || Sym.getType() == STT_SECTION ||
530         Sym.getType() == STT_NOTYPE)
531       return nullptr;
532     fatal(toString(this) + ": invalid section index: " + Twine(Index));
533   }
534 
535   if (S == &InputSection::Discarded)
536     return S;
537   return S->Repl;
538 }
539 
540 template <class ELFT>
541 SymbolBody *ObjFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
542   int Binding = Sym->getBinding();
543   InputSectionBase *Sec = getSection(*Sym);
544 
545   uint8_t StOther = Sym->st_other;
546   uint8_t Type = Sym->getType();
547   uint64_t Value = Sym->st_value;
548   uint64_t Size = Sym->st_size;
549 
550   if (Binding == STB_LOCAL) {
551     if (Sym->getType() == STT_FILE)
552       SourceFile = check(Sym->getName(this->StringTable), toString(this));
553 
554     if (this->StringTable.size() <= Sym->st_name)
555       fatal(toString(this) + ": invalid symbol name offset");
556 
557     StringRefZ Name = this->StringTable.data() + Sym->st_name;
558     if (Sym->st_shndx == SHN_UNDEF)
559       return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type);
560 
561     return make<DefinedRegular>(Name, /*IsLocal=*/true, StOther, Type, Value,
562                                 Size, Sec);
563   }
564 
565   StringRef Name = check(Sym->getName(this->StringTable), toString(this));
566 
567   switch (Sym->st_shndx) {
568   case SHN_UNDEF:
569     return Symtab
570         ->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, StOther, Type,
571                              /*CanOmitFromDynSym=*/false, this)
572         ->body();
573   case SHN_COMMON:
574     if (Value == 0 || Value >= UINT32_MAX)
575       fatal(toString(this) + ": common symbol '" + Name +
576             "' has invalid alignment: " + Twine(Value));
577     return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, this)
578         ->body();
579   }
580 
581   switch (Binding) {
582   default:
583     fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
584   case STB_GLOBAL:
585   case STB_WEAK:
586   case STB_GNU_UNIQUE:
587     if (Sec == &InputSection::Discarded)
588       return Symtab
589           ->addUndefined<ELFT>(Name, /*IsLocal=*/false, Binding, StOther, Type,
590                                /*CanOmitFromDynSym=*/false, this)
591           ->body();
592     return Symtab
593         ->addRegular<ELFT>(Name, StOther, Type, Value, Size, Binding, Sec, this)
594         ->body();
595   }
596 }
597 
598 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
599     : InputFile(ArchiveKind, File->getMemoryBufferRef()),
600       File(std::move(File)) {}
601 
602 template <class ELFT> void ArchiveFile::parse() {
603   Symbols.reserve(File->getNumberOfSymbols());
604   for (const Archive::Symbol &Sym : File->symbols())
605     Symbols.push_back(
606         Symtab->addLazyArchive<ELFT>(Sym.getName(), this, Sym)->body());
607 }
608 
609 // Returns a buffer pointing to a member file containing a given symbol.
610 std::pair<MemoryBufferRef, uint64_t>
611 ArchiveFile::getMember(const Archive::Symbol *Sym) {
612   Archive::Child C =
613       check(Sym->getMember(), toString(this) +
614                                   ": could not get the member for symbol " +
615                                   Sym->getName());
616 
617   if (!Seen.insert(C.getChildOffset()).second)
618     return {MemoryBufferRef(), 0};
619 
620   MemoryBufferRef Ret =
621       check(C.getMemoryBufferRef(),
622             toString(this) +
623                 ": could not get the buffer for the member defining symbol " +
624                 Sym->getName());
625 
626   if (C.getParent()->isThin() && Tar)
627     Tar->append(relativeToRoot(check(C.getFullName(), toString(this))),
628                 Ret.getBuffer());
629   if (C.getParent()->isThin())
630     return {Ret, 0};
631   return {Ret, C.getChildOffset()};
632 }
633 
634 template <class ELFT>
635 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
636     : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
637       AsNeeded(Config->AsNeeded) {}
638 
639 template <class ELFT>
640 const typename ELFT::Shdr *
641 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
642   return check(
643       this->getObj().getSection(&Sym, this->ELFSyms, this->SymtabSHNDX),
644       toString(this));
645 }
646 
647 // Partially parse the shared object file so that we can call
648 // getSoName on this object.
649 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
650   const Elf_Shdr *DynamicSec = nullptr;
651   const ELFFile<ELFT> Obj = this->getObj();
652   ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
653 
654   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
655   for (const Elf_Shdr &Sec : Sections) {
656     switch (Sec.sh_type) {
657     default:
658       continue;
659     case SHT_DYNSYM:
660       this->initSymtab(Sections, &Sec);
661       break;
662     case SHT_DYNAMIC:
663       DynamicSec = &Sec;
664       break;
665     case SHT_SYMTAB_SHNDX:
666       this->SymtabSHNDX =
667           check(Obj.getSHNDXTable(Sec, Sections), toString(this));
668       break;
669     case SHT_GNU_versym:
670       this->VersymSec = &Sec;
671       break;
672     case SHT_GNU_verdef:
673       this->VerdefSec = &Sec;
674       break;
675     }
676   }
677 
678   if (this->VersymSec && this->ELFSyms.empty())
679     error("SHT_GNU_versym should be associated with symbol table");
680 
681   // Search for a DT_SONAME tag to initialize this->SoName.
682   if (!DynamicSec)
683     return;
684   ArrayRef<Elf_Dyn> Arr =
685       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
686             toString(this));
687   for (const Elf_Dyn &Dyn : Arr) {
688     if (Dyn.d_tag == DT_SONAME) {
689       uint64_t Val = Dyn.getVal();
690       if (Val >= this->StringTable.size())
691         fatal(toString(this) + ": invalid DT_SONAME entry");
692       SoName = this->StringTable.data() + Val;
693       return;
694     }
695   }
696 }
697 
698 // Parse the version definitions in the object file if present. Returns a vector
699 // whose nth element contains a pointer to the Elf_Verdef for version identifier
700 // n. Version identifiers that are not definitions map to nullptr. The array
701 // always has at least length 1.
702 template <class ELFT>
703 std::vector<const typename ELFT::Verdef *>
704 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
705   std::vector<const Elf_Verdef *> Verdefs(1);
706   // We only need to process symbol versions for this DSO if it has both a
707   // versym and a verdef section, which indicates that the DSO contains symbol
708   // version definitions.
709   if (!VersymSec || !VerdefSec)
710     return Verdefs;
711 
712   // The location of the first global versym entry.
713   const char *Base = this->MB.getBuffer().data();
714   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
715            this->FirstNonLocal;
716 
717   // We cannot determine the largest verdef identifier without inspecting
718   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
719   // sequentially starting from 1, so we predict that the largest identifier
720   // will be VerdefCount.
721   unsigned VerdefCount = VerdefSec->sh_info;
722   Verdefs.resize(VerdefCount + 1);
723 
724   // Build the Verdefs array by following the chain of Elf_Verdef objects
725   // from the start of the .gnu.version_d section.
726   const char *Verdef = Base + VerdefSec->sh_offset;
727   for (unsigned I = 0; I != VerdefCount; ++I) {
728     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
729     Verdef += CurVerdef->vd_next;
730     unsigned VerdefIndex = CurVerdef->vd_ndx;
731     if (Verdefs.size() <= VerdefIndex)
732       Verdefs.resize(VerdefIndex + 1);
733     Verdefs[VerdefIndex] = CurVerdef;
734   }
735 
736   return Verdefs;
737 }
738 
739 // Fully parse the shared object file. This must be called after parseSoName().
740 template <class ELFT> void SharedFile<ELFT>::parseRest() {
741   // Create mapping from version identifiers to Elf_Verdef entries.
742   const Elf_Versym *Versym = nullptr;
743   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
744 
745   Elf_Sym_Range Syms = this->getGlobalELFSyms();
746   for (const Elf_Sym &Sym : Syms) {
747     unsigned VersymIndex = 0;
748     if (Versym) {
749       VersymIndex = Versym->vs_index;
750       ++Versym;
751     }
752     bool Hidden = VersymIndex & VERSYM_HIDDEN;
753     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
754 
755     StringRef Name = check(Sym.getName(this->StringTable), toString(this));
756     if (Sym.isUndefined()) {
757       Undefs.push_back(Name);
758       continue;
759     }
760 
761     // Ignore local symbols.
762     if (Versym && VersymIndex == VER_NDX_LOCAL)
763       continue;
764     const Elf_Verdef *V = nullptr;
765     if (VersymIndex != VER_NDX_GLOBAL) {
766       if (VersymIndex >= Verdefs.size()) {
767         error("corrupt input file: version definition index " +
768               Twine(VersymIndex) + " for symbol " + Name +
769               " is out of bounds\n>>> defined in " + toString(this));
770         continue;
771       }
772       V = Verdefs[VersymIndex];
773     }
774 
775     if (!Hidden)
776       Symtab->addShared(Name, this, Sym, V);
777 
778     // Also add the symbol with the versioned name to handle undefined symbols
779     // with explicit versions.
780     if (V) {
781       StringRef VerName = this->StringTable.data() + V->getAux()->vda_name;
782       Name = Saver.save(Name + "@" + VerName);
783       Symtab->addShared(Name, this, Sym, V);
784     }
785   }
786 }
787 
788 static ELFKind getBitcodeELFKind(const Triple &T) {
789   if (T.isLittleEndian())
790     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
791   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
792 }
793 
794 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
795   switch (T.getArch()) {
796   case Triple::aarch64:
797     return EM_AARCH64;
798   case Triple::arm:
799   case Triple::thumb:
800     return EM_ARM;
801   case Triple::avr:
802     return EM_AVR;
803   case Triple::mips:
804   case Triple::mipsel:
805   case Triple::mips64:
806   case Triple::mips64el:
807     return EM_MIPS;
808   case Triple::ppc:
809     return EM_PPC;
810   case Triple::ppc64:
811     return EM_PPC64;
812   case Triple::x86:
813     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
814   case Triple::x86_64:
815     return EM_X86_64;
816   default:
817     fatal(Path + ": could not infer e_machine from bitcode target triple " +
818           T.str());
819   }
820 }
821 
822 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
823                          uint64_t OffsetInArchive)
824     : InputFile(BitcodeKind, MB) {
825   this->ArchiveName = ArchiveName;
826 
827   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
828   // (the fully resolved path of the archive) + member name + offset of the
829   // member in the archive.
830   // ThinLTO uses the MemoryBufferRef identifier to access its internal
831   // data structures and if two archives define two members with the same name,
832   // this causes a collision which result in only one of the objects being
833   // taken into consideration at LTO time (which very likely causes undefined
834   // symbols later in the link stage).
835   MemoryBufferRef MBRef(MB.getBuffer(),
836                         Saver.save(ArchiveName + MB.getBufferIdentifier() +
837                                    utostr(OffsetInArchive)));
838   Obj = check(lto::InputFile::create(MBRef), toString(this));
839 
840   Triple T(Obj->getTargetTriple());
841   EKind = getBitcodeELFKind(T);
842   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
843 }
844 
845 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
846   switch (GvVisibility) {
847   case GlobalValue::DefaultVisibility:
848     return STV_DEFAULT;
849   case GlobalValue::HiddenVisibility:
850     return STV_HIDDEN;
851   case GlobalValue::ProtectedVisibility:
852     return STV_PROTECTED;
853   }
854   llvm_unreachable("unknown visibility");
855 }
856 
857 template <class ELFT>
858 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
859                                    const lto::InputFile::Symbol &ObjSym,
860                                    BitcodeFile *F) {
861   StringRef NameRef = Saver.save(ObjSym.getName());
862   uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
863 
864   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
865   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
866   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
867 
868   int C = ObjSym.getComdatIndex();
869   if (C != -1 && !KeptComdats[C])
870     return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding,
871                                       Visibility, Type, CanOmitFromDynSym, F);
872 
873   if (ObjSym.isUndefined())
874     return Symtab->addUndefined<ELFT>(NameRef, /*IsLocal=*/false, Binding,
875                                       Visibility, Type, CanOmitFromDynSym, F);
876 
877   if (ObjSym.isCommon())
878     return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
879                              ObjSym.getCommonAlignment(), Binding, Visibility,
880                              STT_OBJECT, F);
881 
882   return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
883                             CanOmitFromDynSym, F);
884 }
885 
886 template <class ELFT>
887 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
888   std::vector<bool> KeptComdats;
889   for (StringRef S : Obj->getComdatTable())
890     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
891 
892   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
893     Symbols.push_back(
894         createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this)->body());
895 }
896 
897 static ELFKind getELFKind(MemoryBufferRef MB) {
898   unsigned char Size;
899   unsigned char Endian;
900   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
901 
902   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
903     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
904   if (Size != ELFCLASS32 && Size != ELFCLASS64)
905     fatal(MB.getBufferIdentifier() + ": invalid file class");
906 
907   size_t BufSize = MB.getBuffer().size();
908   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
909       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
910     fatal(MB.getBufferIdentifier() + ": file is too short");
911 
912   if (Size == ELFCLASS32)
913     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
914   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
915 }
916 
917 template <class ELFT> void BinaryFile::parse() {
918   ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
919   auto *Section =
920       make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data");
921   Sections.push_back(Section);
922 
923   // For each input file foo that is embedded to a result as a binary
924   // blob, we define _binary_foo_{start,end,size} symbols, so that
925   // user programs can access blobs by name. Non-alphanumeric
926   // characters in a filename are replaced with underscore.
927   std::string S = "_binary_" + MB.getBufferIdentifier().str();
928   for (size_t I = 0; I < S.size(); ++I)
929     if (!isAlnum(S[I]))
930       S[I] = '_';
931 
932   Symtab->addRegular<ELFT>(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT,
933                            0, 0, STB_GLOBAL, Section, nullptr);
934   Symtab->addRegular<ELFT>(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
935                            Data.size(), 0, STB_GLOBAL, Section, nullptr);
936   Symtab->addRegular<ELFT>(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
937                            Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
938 }
939 
940 static bool isBitcode(MemoryBufferRef MB) {
941   using namespace sys::fs;
942   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
943 }
944 
945 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
946                                  uint64_t OffsetInArchive) {
947   if (isBitcode(MB))
948     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
949 
950   switch (getELFKind(MB)) {
951   case ELF32LEKind:
952     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
953   case ELF32BEKind:
954     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
955   case ELF64LEKind:
956     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
957   case ELF64BEKind:
958     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
959   default:
960     llvm_unreachable("getELFKind");
961   }
962 }
963 
964 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
965   switch (getELFKind(MB)) {
966   case ELF32LEKind:
967     return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
968   case ELF32BEKind:
969     return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
970   case ELF64LEKind:
971     return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
972   case ELF64BEKind:
973     return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
974   default:
975     llvm_unreachable("getELFKind");
976   }
977 }
978 
979 MemoryBufferRef LazyObjFile::getBuffer() {
980   if (Seen)
981     return MemoryBufferRef();
982   Seen = true;
983   return MB;
984 }
985 
986 InputFile *LazyObjFile::fetch() {
987   MemoryBufferRef MBRef = getBuffer();
988   if (MBRef.getBuffer().empty())
989     return nullptr;
990   return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
991 }
992 
993 template <class ELFT> void LazyObjFile::parse() {
994   for (StringRef Sym : getSymbolNames())
995     Symtab->addLazyObject<ELFT>(Sym, *this);
996 }
997 
998 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
999   typedef typename ELFT::Shdr Elf_Shdr;
1000   typedef typename ELFT::Sym Elf_Sym;
1001   typedef typename ELFT::SymRange Elf_Sym_Range;
1002 
1003   ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1004   ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
1005   for (const Elf_Shdr &Sec : Sections) {
1006     if (Sec.sh_type != SHT_SYMTAB)
1007       continue;
1008 
1009     Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this));
1010     uint32_t FirstNonLocal = Sec.sh_info;
1011     StringRef StringTable =
1012         check(Obj.getStringTableForSymtab(Sec, Sections), toString(this));
1013     std::vector<StringRef> V;
1014 
1015     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1016       if (Sym.st_shndx != SHN_UNDEF)
1017         V.push_back(check(Sym.getName(StringTable), toString(this)));
1018     return V;
1019   }
1020   return {};
1021 }
1022 
1023 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1024   std::unique_ptr<lto::InputFile> Obj =
1025       check(lto::InputFile::create(this->MB), toString(this));
1026   std::vector<StringRef> V;
1027   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1028     if (!Sym.isUndefined())
1029       V.push_back(Saver.save(Sym.getName()));
1030   return V;
1031 }
1032 
1033 // Returns a vector of globally-visible defined symbol names.
1034 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1035   if (isBitcode(this->MB))
1036     return getBitcodeSymbols();
1037 
1038   switch (getELFKind(this->MB)) {
1039   case ELF32LEKind:
1040     return getElfSymbols<ELF32LE>();
1041   case ELF32BEKind:
1042     return getElfSymbols<ELF32BE>();
1043   case ELF64LEKind:
1044     return getElfSymbols<ELF64LE>();
1045   case ELF64BEKind:
1046     return getElfSymbols<ELF64BE>();
1047   default:
1048     llvm_unreachable("getELFKind");
1049   }
1050 }
1051 
1052 template void ArchiveFile::parse<ELF32LE>();
1053 template void ArchiveFile::parse<ELF32BE>();
1054 template void ArchiveFile::parse<ELF64LE>();
1055 template void ArchiveFile::parse<ELF64BE>();
1056 
1057 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1058 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1059 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1060 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1061 
1062 template void LazyObjFile::parse<ELF32LE>();
1063 template void LazyObjFile::parse<ELF32BE>();
1064 template void LazyObjFile::parse<ELF64LE>();
1065 template void LazyObjFile::parse<ELF64BE>();
1066 
1067 template class elf::ELFFileBase<ELF32LE>;
1068 template class elf::ELFFileBase<ELF32BE>;
1069 template class elf::ELFFileBase<ELF64LE>;
1070 template class elf::ELFFileBase<ELF64BE>;
1071 
1072 template class elf::ObjFile<ELF32LE>;
1073 template class elf::ObjFile<ELF32BE>;
1074 template class elf::ObjFile<ELF64LE>;
1075 template class elf::ObjFile<ELF64BE>;
1076 
1077 template class elf::SharedFile<ELF32LE>;
1078 template class elf::SharedFile<ELF32BE>;
1079 template class elf::SharedFile<ELF64LE>;
1080 template class elf::SharedFile<ELF64BE>;
1081 
1082 template void BinaryFile::parse<ELF32LE>();
1083 template void BinaryFile::parse<ELF32BE>();
1084 template void BinaryFile::parse<ELF64LE>();
1085 template void BinaryFile::parse<ELF64BE>();
1086