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