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