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