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