]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/InputFiles.cpp
9523 Large alloc in zdb can cause trouble
[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 "InputSection.h"
12 #include "LinkerScript.h"
13 #include "SymbolTable.h"
14 #include "Symbols.h"
15 #include "SyntheticSections.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Memory.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/ARMAttributeParser.h"
27 #include "llvm/Support/ARMBuildAttributes.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/TarWriter.h"
30 #include "llvm/Support/raw_ostream.h"
31
32 using namespace llvm;
33 using namespace llvm::ELF;
34 using namespace llvm::object;
35 using namespace llvm::sys;
36 using namespace llvm::sys::fs;
37
38 using namespace lld;
39 using namespace lld::elf;
40
41 std::vector<BinaryFile *> elf::BinaryFiles;
42 std::vector<BitcodeFile *> elf::BitcodeFiles;
43 std::vector<InputFile *> elf::ObjectFiles;
44 std::vector<InputFile *> elf::SharedFiles;
45
46 TarWriter *elf::Tar;
47
48 InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
49
50 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
51   // The --chroot option changes our virtual root directory.
52   // This is useful when you are dealing with files created by --reproduce.
53   if (!Config->Chroot.empty() && Path.startswith("/"))
54     Path = Saver.save(Config->Chroot + Path);
55
56   log(Path);
57
58   auto MBOrErr = MemoryBuffer::getFile(Path);
59   if (auto EC = MBOrErr.getError()) {
60     error("cannot open " + Path + ": " + EC.message());
61     return None;
62   }
63
64   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
65   MemoryBufferRef MBRef = MB->getMemBufferRef();
66   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
67
68   if (Tar)
69     Tar->append(relativeToRoot(Path), MBRef.getBuffer());
70   return MBRef;
71 }
72
73 // Concatenates arguments to construct a string representing an error location.
74 static std::string createFileLineMsg(StringRef Path, unsigned Line) {
75   std::string Filename = path::filename(Path);
76   std::string Lineno = ":" + std::to_string(Line);
77   if (Filename == Path)
78     return Filename + Lineno;
79   return Filename + Lineno + " (" + Path.str() + Lineno + ")";
80 }
81
82 template <class ELFT>
83 static std::string getSrcMsgAux(ObjFile<ELFT> &File, const Symbol &Sym,
84                                 InputSectionBase &Sec, uint64_t Offset) {
85   // In DWARF, functions and variables are stored to different places.
86   // First, lookup a function for a given offset.
87   if (Optional<DILineInfo> Info = File.getDILineInfo(&Sec, Offset))
88     return createFileLineMsg(Info->FileName, Info->Line);
89
90   // If it failed, lookup again as a variable.
91   if (Optional<std::pair<std::string, unsigned>> FileLine =
92           File.getVariableLoc(Sym.getName()))
93     return createFileLineMsg(FileLine->first, FileLine->second);
94
95   // File.SourceFile contains STT_FILE symbol, and that is a last resort.
96   return File.SourceFile;
97 }
98
99 std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec,
100                                  uint64_t Offset) {
101   if (kind() != ObjKind)
102     return "";
103   switch (Config->EKind) {
104   default:
105     llvm_unreachable("Invalid kind");
106   case ELF32LEKind:
107     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset);
108   case ELF32BEKind:
109     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset);
110   case ELF64LEKind:
111     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset);
112   case ELF64BEKind:
113     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset);
114   }
115 }
116
117 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
118   DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(this));
119   const DWARFObject &Obj = Dwarf.getDWARFObj();
120   DwarfLine.reset(new DWARFDebugLine);
121   DWARFDataExtractor LineData(Obj, Obj.getLineSection(), Config->IsLE,
122                               Config->Wordsize);
123
124   // The second parameter is offset in .debug_line section
125   // for compilation unit (CU) of interest. We have only one
126   // CU (object file), so offset is always 0.
127   // FIXME: Provide the associated DWARFUnit if there is one.  DWARF v5
128   // needs it in order to find indirect strings.
129   const DWARFDebugLine::LineTable *LT =
130       DwarfLine->getOrParseLineTable(LineData, 0, nullptr);
131
132   // Return if there is no debug information about CU available.
133   if (!Dwarf.getNumCompileUnits())
134     return;
135
136   // Loop over variable records and insert them to VariableLoc.
137   DWARFCompileUnit *CU = Dwarf.getCompileUnitAtIndex(0);
138   for (const auto &Entry : CU->dies()) {
139     DWARFDie Die(CU, &Entry);
140     // Skip all tags that are not variables.
141     if (Die.getTag() != dwarf::DW_TAG_variable)
142       continue;
143
144     // Skip if a local variable because we don't need them for generating error
145     // messages. In general, only non-local symbols can fail to be linked.
146     if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
147       continue;
148
149     // Get the source filename index for the variable.
150     unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
151     if (!LT->hasFileAtIndex(File))
152       continue;
153
154     // Get the line number on which the variable is declared.
155     unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
156
157     // Get the name of the variable and add the collected information to
158     // VariableLoc. Usually Name is non-empty, but it can be empty if the input
159     // object file lacks some debug info.
160     StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), "");
161     if (!Name.empty())
162       VariableLoc.insert({Name, {File, Line}});
163   }
164 }
165
166 // Returns the pair of file name and line number describing location of data
167 // object (variable, array, etc) definition.
168 template <class ELFT>
169 Optional<std::pair<std::string, unsigned>>
170 ObjFile<ELFT>::getVariableLoc(StringRef Name) {
171   llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
172
173   // There is always only one CU so it's offset is 0.
174   const DWARFDebugLine::LineTable *LT = DwarfLine->getLineTable(0);
175   if (!LT)
176     return None;
177
178   // Return if we have no debug information about data object.
179   auto It = VariableLoc.find(Name);
180   if (It == VariableLoc.end())
181     return None;
182
183   // Take file name string from line table.
184   std::string FileName;
185   if (!LT->getFileNameByIndex(
186           It->second.first /* File */, nullptr,
187           DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
188     return None;
189
190   return std::make_pair(FileName, It->second.second /*Line*/);
191 }
192
193 // Returns source line information for a given offset
194 // using DWARF debug info.
195 template <class ELFT>
196 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
197                                                   uint64_t Offset) {
198   llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
199
200   // The offset to CU is 0.
201   const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
202   if (!Tbl)
203     return None;
204
205   // Use fake address calcuated by adding section file offset and offset in
206   // section. See comments for ObjectInfo class.
207   DILineInfo Info;
208   Tbl->getFileLineInfoForAddress(
209       S->getOffsetInFile() + Offset, nullptr,
210       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
211   if (Info.Line == 0)
212     return None;
213   return Info;
214 }
215
216 // Returns source line information for a given offset
217 // using DWARF debug info.
218 template <class ELFT>
219 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) {
220   if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
221     return Info->FileName + ":" + std::to_string(Info->Line);
222   return "";
223 }
224
225 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
226 std::string lld::toString(const InputFile *F) {
227   if (!F)
228     return "<internal>";
229
230   if (F->ToStringCache.empty()) {
231     if (F->ArchiveName.empty())
232       F->ToStringCache = F->getName();
233     else
234       F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
235   }
236   return F->ToStringCache;
237 }
238
239 template <class ELFT>
240 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
241   if (ELFT::TargetEndianness == support::little)
242     EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
243   else
244     EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
245
246   EMachine = getObj().getHeader()->e_machine;
247   OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
248 }
249
250 template <class ELFT>
251 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
252   return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end());
253 }
254
255 template <class ELFT>
256 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
257   return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this);
258 }
259
260 template <class ELFT>
261 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
262                                    const Elf_Shdr *Symtab) {
263   FirstNonLocal = Symtab->sh_info;
264   ELFSyms = CHECK(getObj().symbols(Symtab), this);
265   if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size())
266     fatal(toString(this) + ": invalid sh_info in symbol table");
267
268   StringTable =
269       CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this);
270 }
271
272 template <class ELFT>
273 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
274     : ELFFileBase<ELFT>(Base::ObjKind, M) {
275   this->ArchiveName = ArchiveName;
276 }
277
278 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
279   if (this->Symbols.empty())
280     return {};
281   return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1);
282 }
283
284 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
285   return makeArrayRef(this->Symbols).slice(this->FirstNonLocal);
286 }
287
288 template <class ELFT>
289 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
290   // Read section and symbol tables.
291   initializeSections(ComdatGroups);
292   initializeSymbols();
293 }
294
295 // Sections with SHT_GROUP and comdat bits define comdat section groups.
296 // They are identified and deduplicated by group name. This function
297 // returns a group name.
298 template <class ELFT>
299 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
300                                               const Elf_Shdr &Sec) {
301   // Group signatures are stored as symbol names in object files.
302   // sh_info contains a symbol index, so we fetch a symbol and read its name.
303   if (this->ELFSyms.empty())
304     this->initSymtab(
305         Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this));
306
307   const Elf_Sym *Sym =
308       CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this);
309   StringRef Signature = CHECK(Sym->getName(this->StringTable), this);
310
311   // As a special case, if a symbol is a section symbol and has no name,
312   // we use a section name as a signature.
313   //
314   // Such SHT_GROUP sections are invalid from the perspective of the ELF
315   // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
316   // older produce such sections as outputs for the -r option, so we need
317   // a bug-compatibility.
318   if (Signature.empty() && Sym->getType() == STT_SECTION)
319     return getSectionName(Sec);
320   return Signature;
321 }
322
323 template <class ELFT>
324 ArrayRef<typename ObjFile<ELFT>::Elf_Word>
325 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
326   const ELFFile<ELFT> &Obj = this->getObj();
327   ArrayRef<Elf_Word> Entries =
328       CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
329   if (Entries.empty() || Entries[0] != GRP_COMDAT)
330     fatal(toString(this) + ": unsupported SHT_GROUP format");
331   return Entries.slice(1);
332 }
333
334 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
335   // We don't merge sections if -O0 (default is -O1). This makes sometimes
336   // the linker significantly faster, although the output will be bigger.
337   if (Config->Optimize == 0)
338     return false;
339
340   // A mergeable section with size 0 is useless because they don't have
341   // any data to merge. A mergeable string section with size 0 can be
342   // argued as invalid because it doesn't end with a null character.
343   // We'll avoid a mess by handling them as if they were non-mergeable.
344   if (Sec.sh_size == 0)
345     return false;
346
347   // Check for sh_entsize. The ELF spec is not clear about the zero
348   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
349   // the section does not hold a table of fixed-size entries". We know
350   // that Rust 1.13 produces a string mergeable section with a zero
351   // sh_entsize. Here we just accept it rather than being picky about it.
352   uint64_t EntSize = Sec.sh_entsize;
353   if (EntSize == 0)
354     return false;
355   if (Sec.sh_size % EntSize)
356     fatal(toString(this) +
357           ": SHF_MERGE section size must be a multiple of sh_entsize");
358
359   uint64_t Flags = Sec.sh_flags;
360   if (!(Flags & SHF_MERGE))
361     return false;
362   if (Flags & SHF_WRITE)
363     fatal(toString(this) + ": writable SHF_MERGE section is not supported");
364
365   return true;
366 }
367
368 template <class ELFT>
369 void ObjFile<ELFT>::initializeSections(
370     DenseSet<CachedHashStringRef> &ComdatGroups) {
371   const ELFFile<ELFT> &Obj = this->getObj();
372
373   ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
374   uint64_t Size = ObjSections.size();
375   this->Sections.resize(Size);
376   this->SectionStringTable =
377       CHECK(Obj.getSectionStringTable(ObjSections), this);
378
379   for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
380     if (this->Sections[I] == &InputSection::Discarded)
381       continue;
382     const Elf_Shdr &Sec = ObjSections[I];
383
384     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
385     // if -r is given, we'll let the final link discard such sections.
386     // This is compatible with GNU.
387     if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
388       this->Sections[I] = &InputSection::Discarded;
389       continue;
390     }
391
392     switch (Sec.sh_type) {
393     case SHT_GROUP: {
394       // De-duplicate section groups by their signatures.
395       StringRef Signature = getShtGroupSignature(ObjSections, Sec);
396       bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
397       this->Sections[I] = &InputSection::Discarded;
398
399       // If it is a new section group, we want to keep group members.
400       // Group leader sections, which contain indices of group members, are
401       // discarded because they are useless beyond this point. The only
402       // exception is the -r option because in order to produce re-linkable
403       // object files, we want to pass through basically everything.
404       if (IsNew) {
405         if (Config->Relocatable)
406           this->Sections[I] = createInputSection(Sec);
407         continue;
408       }
409
410       // Otherwise, discard group members.
411       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
412         if (SecIndex >= Size)
413           fatal(toString(this) +
414                 ": invalid section index in group: " + Twine(SecIndex));
415         this->Sections[SecIndex] = &InputSection::Discarded;
416       }
417       break;
418     }
419     case SHT_SYMTAB:
420       this->initSymtab(ObjSections, &Sec);
421       break;
422     case SHT_SYMTAB_SHNDX:
423       this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
424       break;
425     case SHT_STRTAB:
426     case SHT_NULL:
427       break;
428     default:
429       this->Sections[I] = createInputSection(Sec);
430     }
431
432     // .ARM.exidx sections have a reverse dependency on the InputSection they
433     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
434     if (Sec.sh_flags & SHF_LINK_ORDER) {
435       if (Sec.sh_link >= this->Sections.size())
436         fatal(toString(this) +
437               ": invalid sh_link index: " + Twine(Sec.sh_link));
438       this->Sections[Sec.sh_link]->DependentSections.push_back(
439           cast<InputSection>(this->Sections[I]));
440     }
441   }
442 }
443
444 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
445 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
446 // the input objects have been compiled.
447 static void updateARMVFPArgs(const ARMAttributeParser &Attributes,
448                              const InputFile *F) {
449   if (!Attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
450     // If an ABI tag isn't present then it is implicitly given the value of 0
451     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
452     // including some in glibc that don't use FP args (and should have value 3)
453     // don't have the attribute so we do not consider an implicit value of 0
454     // as a clash.
455     return;
456
457   unsigned VFPArgs = Attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
458   ARMVFPArgKind Arg;
459   switch (VFPArgs) {
460   case ARMBuildAttrs::BaseAAPCS:
461     Arg = ARMVFPArgKind::Base;
462     break;
463   case ARMBuildAttrs::HardFPAAPCS:
464     Arg = ARMVFPArgKind::VFP;
465     break;
466   case ARMBuildAttrs::ToolChainFPPCS:
467     // Tool chain specific convention that conforms to neither AAPCS variant.
468     Arg = ARMVFPArgKind::ToolChain;
469     break;
470   case ARMBuildAttrs::CompatibleFPAAPCS:
471     // Object compatible with all conventions.
472     return;
473   default:
474     error(toString(F) + ": unknown Tag_ABI_VFP_args value: " + Twine(VFPArgs));
475     return;
476   }
477   // Follow ld.bfd and error if there is a mix of calling conventions.
478   if (Config->ARMVFPArgs != Arg && Config->ARMVFPArgs != ARMVFPArgKind::Default)
479     error(toString(F) + ": incompatible Tag_ABI_VFP_args");
480   else
481     Config->ARMVFPArgs = Arg;
482 }
483
484 // The ARM support in lld makes some use of instructions that are not available
485 // on all ARM architectures. Namely:
486 // - Use of BLX instruction for interworking between ARM and Thumb state.
487 // - Use of the extended Thumb branch encoding in relocation.
488 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
489 // The ARM Attributes section contains information about the architecture chosen
490 // at compile time. We follow the convention that if at least one input object
491 // is compiled with an architecture that supports these features then lld is
492 // permitted to use them.
493 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
494   if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
495     return;
496   auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
497   switch (Arch) {
498   case ARMBuildAttrs::Pre_v4:
499   case ARMBuildAttrs::v4:
500   case ARMBuildAttrs::v4T:
501     // Architectures prior to v5 do not support BLX instruction
502     break;
503   case ARMBuildAttrs::v5T:
504   case ARMBuildAttrs::v5TE:
505   case ARMBuildAttrs::v5TEJ:
506   case ARMBuildAttrs::v6:
507   case ARMBuildAttrs::v6KZ:
508   case ARMBuildAttrs::v6K:
509     Config->ARMHasBlx = true;
510     // Architectures used in pre-Cortex processors do not support
511     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
512     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
513     break;
514   default:
515     // All other Architectures have BLX and extended branch encoding
516     Config->ARMHasBlx = true;
517     Config->ARMJ1J2BranchEncoding = true;
518     if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
519       // All Architectures used in Cortex processors with the exception
520       // of v6-M and v6S-M have the MOVT and MOVW instructions.
521       Config->ARMHasMovtMovw = true;
522     break;
523   }
524 }
525
526 template <class ELFT>
527 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
528   uint32_t Idx = Sec.sh_info;
529   if (Idx >= this->Sections.size())
530     fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
531   InputSectionBase *Target = this->Sections[Idx];
532
533   // Strictly speaking, a relocation section must be included in the
534   // group of the section it relocates. However, LLVM 3.3 and earlier
535   // would fail to do so, so we gracefully handle that case.
536   if (Target == &InputSection::Discarded)
537     return nullptr;
538
539   if (!Target)
540     fatal(toString(this) + ": unsupported relocation reference");
541   return Target;
542 }
543
544 // Create a regular InputSection class that has the same contents
545 // as a given section.
546 static InputSection *toRegularSection(MergeInputSection *Sec) {
547   return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
548                             Sec->Data, Sec->Name);
549 }
550
551 template <class ELFT>
552 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
553   StringRef Name = getSectionName(Sec);
554
555   switch (Sec.sh_type) {
556   case SHT_ARM_ATTRIBUTES: {
557     if (Config->EMachine != EM_ARM)
558       break;
559     ARMAttributeParser Attributes;
560     ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
561     Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
562     updateSupportedARMFeatures(Attributes);
563     updateARMVFPArgs(Attributes, this);
564
565     // FIXME: Retain the first attribute section we see. The eglibc ARM
566     // dynamic loaders require the presence of an attribute section for dlopen
567     // to work. In a full implementation we would merge all attribute sections.
568     if (InX::ARMAttributes == nullptr) {
569       InX::ARMAttributes = make<InputSection>(*this, Sec, Name);
570       return InX::ARMAttributes;
571     }
572     return &InputSection::Discarded;
573   }
574   case SHT_RELA:
575   case SHT_REL: {
576     // Find the relocation target section and associate this
577     // section with it. Target can be discarded, for example
578     // if it is a duplicated member of SHT_GROUP section, we
579     // do not create or proccess relocatable sections then.
580     InputSectionBase *Target = getRelocTarget(Sec);
581     if (!Target)
582       return nullptr;
583
584     // This section contains relocation information.
585     // If -r is given, we do not interpret or apply relocation
586     // but just copy relocation sections to output.
587     if (Config->Relocatable)
588       return make<InputSection>(*this, Sec, Name);
589
590     if (Target->FirstRelocation)
591       fatal(toString(this) +
592             ": multiple relocation sections to one section are not supported");
593
594     // Mergeable sections with relocations are tricky because relocations
595     // need to be taken into account when comparing section contents for
596     // merging. It's not worth supporting such mergeable sections because
597     // they are rare and it'd complicates the internal design (we usually
598     // have to determine if two sections are mergeable early in the link
599     // process much before applying relocations). We simply handle mergeable
600     // sections with relocations as non-mergeable.
601     if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
602       Target = toRegularSection(MS);
603       this->Sections[Sec.sh_info] = Target;
604     }
605
606     size_t NumRelocations;
607     if (Sec.sh_type == SHT_RELA) {
608       ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
609       Target->FirstRelocation = Rels.begin();
610       NumRelocations = Rels.size();
611       Target->AreRelocsRela = true;
612     } else {
613       ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
614       Target->FirstRelocation = Rels.begin();
615       NumRelocations = Rels.size();
616       Target->AreRelocsRela = false;
617     }
618     assert(isUInt<31>(NumRelocations));
619     Target->NumRelocations = NumRelocations;
620
621     // Relocation sections processed by the linker are usually removed
622     // from the output, so returning `nullptr` for the normal case.
623     // However, if -emit-relocs is given, we need to leave them in the output.
624     // (Some post link analysis tools need this information.)
625     if (Config->EmitRelocs) {
626       InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
627       // We will not emit relocation section if target was discarded.
628       Target->DependentSections.push_back(RelocSec);
629       return RelocSec;
630     }
631     return nullptr;
632   }
633   }
634
635   // The GNU linker uses .note.GNU-stack section as a marker indicating
636   // that the code in the object file does not expect that the stack is
637   // executable (in terms of NX bit). If all input files have the marker,
638   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
639   // make the stack non-executable. Most object files have this section as
640   // of 2017.
641   //
642   // But making the stack non-executable is a norm today for security
643   // reasons. Failure to do so may result in a serious security issue.
644   // Therefore, we make LLD always add PT_GNU_STACK unless it is
645   // explicitly told to do otherwise (by -z execstack). Because the stack
646   // executable-ness is controlled solely by command line options,
647   // .note.GNU-stack sections are simply ignored.
648   if (Name == ".note.GNU-stack")
649     return &InputSection::Discarded;
650
651   // Split stacks is a feature to support a discontiguous stack. At least
652   // as of 2017, it seems that the feature is not being used widely.
653   // Only GNU gold supports that. We don't. For the details about that,
654   // see https://gcc.gnu.org/wiki/SplitStacks
655   if (Name == ".note.GNU-split-stack") {
656     error(toString(this) +
657           ": object file compiled with -fsplit-stack is not supported");
658     return &InputSection::Discarded;
659   }
660
661   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
662   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
663   // sections. Drop those sections to avoid duplicate symbol errors.
664   // FIXME: This is glibc PR20543, we should remove this hack once that has been
665   // fixed for a while.
666   if (Name.startswith(".gnu.linkonce."))
667     return &InputSection::Discarded;
668
669   // The linker merges EH (exception handling) frames and creates a
670   // .eh_frame_hdr section for runtime. So we handle them with a special
671   // class. For relocatable outputs, they are just passed through.
672   if (Name == ".eh_frame" && !Config->Relocatable)
673     return make<EhInputSection>(*this, Sec, Name);
674
675   if (shouldMerge(Sec))
676     return make<MergeInputSection>(*this, Sec, Name);
677   return make<InputSection>(*this, Sec, Name);
678 }
679
680 template <class ELFT>
681 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
682   return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
683 }
684
685 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
686   this->Symbols.reserve(this->ELFSyms.size());
687   for (const Elf_Sym &Sym : this->ELFSyms)
688     this->Symbols.push_back(createSymbol(&Sym));
689 }
690
691 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
692   int Binding = Sym->getBinding();
693
694   uint32_t SecIdx = this->getSectionIndex(*Sym);
695   if (SecIdx >= this->Sections.size())
696     fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
697
698   InputSectionBase *Sec = this->Sections[SecIdx];
699   uint8_t StOther = Sym->st_other;
700   uint8_t Type = Sym->getType();
701   uint64_t Value = Sym->st_value;
702   uint64_t Size = Sym->st_size;
703
704   if (Binding == STB_LOCAL) {
705     if (Sym->getType() == STT_FILE)
706       SourceFile = CHECK(Sym->getName(this->StringTable), this);
707
708     if (this->StringTable.size() <= Sym->st_name)
709       fatal(toString(this) + ": invalid symbol name offset");
710
711     StringRefZ Name = this->StringTable.data() + Sym->st_name;
712     if (Sym->st_shndx == SHN_UNDEF)
713       return make<Undefined>(this, Name, Binding, StOther, Type);
714
715     return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
716   }
717
718   StringRef Name = CHECK(Sym->getName(this->StringTable), this);
719
720   switch (Sym->st_shndx) {
721   case SHN_UNDEF:
722     return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
723                                       /*CanOmitFromDynSym=*/false, this);
724   case SHN_COMMON:
725     if (Value == 0 || Value >= UINT32_MAX)
726       fatal(toString(this) + ": common symbol '" + Name +
727             "' has invalid alignment: " + Twine(Value));
728     return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
729   }
730
731   switch (Binding) {
732   default:
733     fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
734   case STB_GLOBAL:
735   case STB_WEAK:
736   case STB_GNU_UNIQUE:
737     if (Sec == &InputSection::Discarded)
738       return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
739                                         /*CanOmitFromDynSym=*/false, this);
740     return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
741                               this);
742   }
743 }
744
745 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
746     : InputFile(ArchiveKind, File->getMemoryBufferRef()),
747       File(std::move(File)) {}
748
749 template <class ELFT> void ArchiveFile::parse() {
750   Symbols.reserve(File->getNumberOfSymbols());
751   for (const Archive::Symbol &Sym : File->symbols())
752     Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
753 }
754
755 // Returns a buffer pointing to a member file containing a given symbol.
756 std::pair<MemoryBufferRef, uint64_t>
757 ArchiveFile::getMember(const Archive::Symbol *Sym) {
758   Archive::Child C =
759       CHECK(Sym->getMember(), toString(this) +
760                                   ": could not get the member for symbol " +
761                                   Sym->getName());
762
763   if (!Seen.insert(C.getChildOffset()).second)
764     return {MemoryBufferRef(), 0};
765
766   MemoryBufferRef Ret =
767       CHECK(C.getMemoryBufferRef(),
768             toString(this) +
769                 ": could not get the buffer for the member defining symbol " +
770                 Sym->getName());
771
772   if (C.getParent()->isThin() && Tar)
773     Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
774   if (C.getParent()->isThin())
775     return {Ret, 0};
776   return {Ret, C.getChildOffset()};
777 }
778
779 template <class ELFT>
780 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
781     : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
782       IsNeeded(!Config->AsNeeded) {}
783
784 // Partially parse the shared object file so that we can call
785 // getSoName on this object.
786 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
787   const Elf_Shdr *DynamicSec = nullptr;
788   const ELFFile<ELFT> Obj = this->getObj();
789   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
790
791   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
792   for (const Elf_Shdr &Sec : Sections) {
793     switch (Sec.sh_type) {
794     default:
795       continue;
796     case SHT_DYNSYM:
797       this->initSymtab(Sections, &Sec);
798       break;
799     case SHT_DYNAMIC:
800       DynamicSec = &Sec;
801       break;
802     case SHT_SYMTAB_SHNDX:
803       this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
804       break;
805     case SHT_GNU_versym:
806       this->VersymSec = &Sec;
807       break;
808     case SHT_GNU_verdef:
809       this->VerdefSec = &Sec;
810       break;
811     }
812   }
813
814   if (this->VersymSec && this->ELFSyms.empty())
815     error("SHT_GNU_versym should be associated with symbol table");
816
817   // Search for a DT_SONAME tag to initialize this->SoName.
818   if (!DynamicSec)
819     return;
820   ArrayRef<Elf_Dyn> Arr =
821       CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
822   for (const Elf_Dyn &Dyn : Arr) {
823     if (Dyn.d_tag == DT_SONAME) {
824       uint64_t Val = Dyn.getVal();
825       if (Val >= this->StringTable.size())
826         fatal(toString(this) + ": invalid DT_SONAME entry");
827       SoName = this->StringTable.data() + Val;
828       return;
829     }
830   }
831 }
832
833 // Parse the version definitions in the object file if present. Returns a vector
834 // whose nth element contains a pointer to the Elf_Verdef for version identifier
835 // n. Version identifiers that are not definitions map to nullptr. The array
836 // always has at least length 1.
837 template <class ELFT>
838 std::vector<const typename ELFT::Verdef *>
839 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
840   std::vector<const Elf_Verdef *> Verdefs(1);
841   // We only need to process symbol versions for this DSO if it has both a
842   // versym and a verdef section, which indicates that the DSO contains symbol
843   // version definitions.
844   if (!VersymSec || !VerdefSec)
845     return Verdefs;
846
847   // The location of the first global versym entry.
848   const char *Base = this->MB.getBuffer().data();
849   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
850            this->FirstNonLocal;
851
852   // We cannot determine the largest verdef identifier without inspecting
853   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
854   // sequentially starting from 1, so we predict that the largest identifier
855   // will be VerdefCount.
856   unsigned VerdefCount = VerdefSec->sh_info;
857   Verdefs.resize(VerdefCount + 1);
858
859   // Build the Verdefs array by following the chain of Elf_Verdef objects
860   // from the start of the .gnu.version_d section.
861   const char *Verdef = Base + VerdefSec->sh_offset;
862   for (unsigned I = 0; I != VerdefCount; ++I) {
863     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
864     Verdef += CurVerdef->vd_next;
865     unsigned VerdefIndex = CurVerdef->vd_ndx;
866     if (Verdefs.size() <= VerdefIndex)
867       Verdefs.resize(VerdefIndex + 1);
868     Verdefs[VerdefIndex] = CurVerdef;
869   }
870
871   return Verdefs;
872 }
873
874 // Fully parse the shared object file. This must be called after parseSoName().
875 template <class ELFT> void SharedFile<ELFT>::parseRest() {
876   // Create mapping from version identifiers to Elf_Verdef entries.
877   const Elf_Versym *Versym = nullptr;
878   Verdefs = parseVerdefs(Versym);
879
880   ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
881
882   // Add symbols to the symbol table.
883   Elf_Sym_Range Syms = this->getGlobalELFSyms();
884   for (const Elf_Sym &Sym : Syms) {
885     unsigned VersymIndex = VER_NDX_GLOBAL;
886     if (Versym) {
887       VersymIndex = Versym->vs_index;
888       ++Versym;
889     }
890     bool Hidden = VersymIndex & VERSYM_HIDDEN;
891     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
892
893     StringRef Name = CHECK(Sym.getName(this->StringTable), this);
894     if (Sym.isUndefined()) {
895       Undefs.push_back(Name);
896       continue;
897     }
898
899     if (Sym.getBinding() == STB_LOCAL) {
900       warn("found local symbol '" + Name +
901            "' in global part of symbol table in file " + toString(this));
902       continue;
903     }
904
905     if (Config->EMachine == EM_MIPS) {
906       // FIXME: MIPS BFD linker puts _gp_disp symbol into DSO files
907       // and incorrectly assigns VER_NDX_LOCAL to this section global
908       // symbol. Here is a workaround for this bug.
909       if (Versym && VersymIndex == VER_NDX_LOCAL && Name == "_gp_disp")
910         continue;
911     }
912
913     const Elf_Verdef *Ver = nullptr;
914     if (VersymIndex != VER_NDX_GLOBAL) {
915       if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
916         error("corrupt input file: version definition index " +
917               Twine(VersymIndex) + " for symbol " + Name +
918               " is out of bounds\n>>> defined in " + toString(this));
919         continue;
920       }
921       Ver = Verdefs[VersymIndex];
922     } else {
923       VersymIndex = 0;
924     }
925
926     // We do not usually care about alignments of data in shared object
927     // files because the loader takes care of it. However, if we promote a
928     // DSO symbol to point to .bss due to copy relocation, we need to keep
929     // the original alignment requirements. We infer it here.
930     uint64_t Alignment = 1;
931     if (Sym.st_value)
932       Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
933     if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
934       uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
935       Alignment = std::min(Alignment, SecAlign);
936     }
937     if (Alignment > UINT32_MAX)
938       error(toString(this) + ": alignment too large: " + Name);
939
940     if (!Hidden)
941       Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
942
943     // Also add the symbol with the versioned name to handle undefined symbols
944     // with explicit versions.
945     if (Ver) {
946       StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
947       Name = Saver.save(Name + "@" + VerName);
948       Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
949     }
950   }
951 }
952
953 static ELFKind getBitcodeELFKind(const Triple &T) {
954   if (T.isLittleEndian())
955     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
956   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
957 }
958
959 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
960   switch (T.getArch()) {
961   case Triple::aarch64:
962     return EM_AARCH64;
963   case Triple::arm:
964   case Triple::thumb:
965     return EM_ARM;
966   case Triple::avr:
967     return EM_AVR;
968   case Triple::mips:
969   case Triple::mipsel:
970   case Triple::mips64:
971   case Triple::mips64el:
972     return EM_MIPS;
973   case Triple::ppc:
974     return EM_PPC;
975   case Triple::ppc64:
976     return EM_PPC64;
977   case Triple::x86:
978     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
979   case Triple::x86_64:
980     return EM_X86_64;
981   default:
982     fatal(Path + ": could not infer e_machine from bitcode target triple " +
983           T.str());
984   }
985 }
986
987 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
988                          uint64_t OffsetInArchive)
989     : InputFile(BitcodeKind, MB) {
990   this->ArchiveName = ArchiveName;
991
992   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
993   // (the fully resolved path of the archive) + member name + offset of the
994   // member in the archive.
995   // ThinLTO uses the MemoryBufferRef identifier to access its internal
996   // data structures and if two archives define two members with the same name,
997   // this causes a collision which result in only one of the objects being
998   // taken into consideration at LTO time (which very likely causes undefined
999   // symbols later in the link stage).
1000   MemoryBufferRef MBRef(MB.getBuffer(),
1001                         Saver.save(ArchiveName + MB.getBufferIdentifier() +
1002                                    utostr(OffsetInArchive)));
1003   Obj = CHECK(lto::InputFile::create(MBRef), this);
1004
1005   Triple T(Obj->getTargetTriple());
1006   EKind = getBitcodeELFKind(T);
1007   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
1008 }
1009
1010 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
1011   switch (GvVisibility) {
1012   case GlobalValue::DefaultVisibility:
1013     return STV_DEFAULT;
1014   case GlobalValue::HiddenVisibility:
1015     return STV_HIDDEN;
1016   case GlobalValue::ProtectedVisibility:
1017     return STV_PROTECTED;
1018   }
1019   llvm_unreachable("unknown visibility");
1020 }
1021
1022 template <class ELFT>
1023 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
1024                                    const lto::InputFile::Symbol &ObjSym,
1025                                    BitcodeFile &F) {
1026   StringRef NameRef = Saver.save(ObjSym.getName());
1027   uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1028
1029   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
1030   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
1031   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
1032
1033   int C = ObjSym.getComdatIndex();
1034   if (C != -1 && !KeptComdats[C])
1035     return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
1036                                       CanOmitFromDynSym, &F);
1037
1038   if (ObjSym.isUndefined())
1039     return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
1040                                       CanOmitFromDynSym, &F);
1041
1042   if (ObjSym.isCommon())
1043     return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
1044                              ObjSym.getCommonAlignment(), Binding, Visibility,
1045                              STT_OBJECT, F);
1046
1047   return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
1048                             CanOmitFromDynSym, F);
1049 }
1050
1051 template <class ELFT>
1052 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1053   std::vector<bool> KeptComdats;
1054   for (StringRef S : Obj->getComdatTable())
1055     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1056
1057   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1058     Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1059 }
1060
1061 static ELFKind getELFKind(MemoryBufferRef MB) {
1062   unsigned char Size;
1063   unsigned char Endian;
1064   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1065
1066   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1067     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1068   if (Size != ELFCLASS32 && Size != ELFCLASS64)
1069     fatal(MB.getBufferIdentifier() + ": invalid file class");
1070
1071   size_t BufSize = MB.getBuffer().size();
1072   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1073       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1074     fatal(MB.getBufferIdentifier() + ": file is too short");
1075
1076   if (Size == ELFCLASS32)
1077     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1078   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1079 }
1080
1081 void BinaryFile::parse() {
1082   ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1083   auto *Section = make<InputSection>(nullptr, SHF_ALLOC | SHF_WRITE,
1084                                      SHT_PROGBITS, 8, Data, ".data");
1085   Sections.push_back(Section);
1086
1087   // For each input file foo that is embedded to a result as a binary
1088   // blob, we define _binary_foo_{start,end,size} symbols, so that
1089   // user programs can access blobs by name. Non-alphanumeric
1090   // characters in a filename are replaced with underscore.
1091   std::string S = "_binary_" + MB.getBufferIdentifier().str();
1092   for (size_t I = 0; I < S.size(); ++I)
1093     if (!isAlnum(S[I]))
1094       S[I] = '_';
1095
1096   Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1097                      STB_GLOBAL, Section, nullptr);
1098   Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1099                      Data.size(), 0, STB_GLOBAL, Section, nullptr);
1100   Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1101                      Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1102 }
1103
1104 static bool isBitcode(MemoryBufferRef MB) {
1105   using namespace sys::fs;
1106   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1107 }
1108
1109 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1110                                  uint64_t OffsetInArchive) {
1111   if (isBitcode(MB))
1112     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1113
1114   switch (getELFKind(MB)) {
1115   case ELF32LEKind:
1116     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1117   case ELF32BEKind:
1118     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1119   case ELF64LEKind:
1120     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1121   case ELF64BEKind:
1122     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1123   default:
1124     llvm_unreachable("getELFKind");
1125   }
1126 }
1127
1128 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1129   switch (getELFKind(MB)) {
1130   case ELF32LEKind:
1131     return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1132   case ELF32BEKind:
1133     return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1134   case ELF64LEKind:
1135     return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1136   case ELF64BEKind:
1137     return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1138   default:
1139     llvm_unreachable("getELFKind");
1140   }
1141 }
1142
1143 MemoryBufferRef LazyObjFile::getBuffer() {
1144   if (Seen)
1145     return MemoryBufferRef();
1146   Seen = true;
1147   return MB;
1148 }
1149
1150 InputFile *LazyObjFile::fetch() {
1151   MemoryBufferRef MBRef = getBuffer();
1152   if (MBRef.getBuffer().empty())
1153     return nullptr;
1154   return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1155 }
1156
1157 template <class ELFT> void LazyObjFile::parse() {
1158   for (StringRef Sym : getSymbolNames())
1159     Symtab->addLazyObject<ELFT>(Sym, *this);
1160 }
1161
1162 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1163   typedef typename ELFT::Shdr Elf_Shdr;
1164   typedef typename ELFT::Sym Elf_Sym;
1165   typedef typename ELFT::SymRange Elf_Sym_Range;
1166
1167   ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1168   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1169   for (const Elf_Shdr &Sec : Sections) {
1170     if (Sec.sh_type != SHT_SYMTAB)
1171       continue;
1172
1173     Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1174     uint32_t FirstNonLocal = Sec.sh_info;
1175     StringRef StringTable =
1176         CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1177     std::vector<StringRef> V;
1178
1179     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1180       if (Sym.st_shndx != SHN_UNDEF)
1181         V.push_back(CHECK(Sym.getName(StringTable), this));
1182     return V;
1183   }
1184   return {};
1185 }
1186
1187 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1188   std::unique_ptr<lto::InputFile> Obj =
1189       CHECK(lto::InputFile::create(this->MB), this);
1190   std::vector<StringRef> V;
1191   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1192     if (!Sym.isUndefined())
1193       V.push_back(Saver.save(Sym.getName()));
1194   return V;
1195 }
1196
1197 // Returns a vector of globally-visible defined symbol names.
1198 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1199   if (isBitcode(this->MB))
1200     return getBitcodeSymbols();
1201
1202   switch (getELFKind(this->MB)) {
1203   case ELF32LEKind:
1204     return getElfSymbols<ELF32LE>();
1205   case ELF32BEKind:
1206     return getElfSymbols<ELF32BE>();
1207   case ELF64LEKind:
1208     return getElfSymbols<ELF64LE>();
1209   case ELF64BEKind:
1210     return getElfSymbols<ELF64BE>();
1211   default:
1212     llvm_unreachable("getELFKind");
1213   }
1214 }
1215
1216 template void ArchiveFile::parse<ELF32LE>();
1217 template void ArchiveFile::parse<ELF32BE>();
1218 template void ArchiveFile::parse<ELF64LE>();
1219 template void ArchiveFile::parse<ELF64BE>();
1220
1221 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1222 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1223 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1224 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1225
1226 template void LazyObjFile::parse<ELF32LE>();
1227 template void LazyObjFile::parse<ELF32BE>();
1228 template void LazyObjFile::parse<ELF64LE>();
1229 template void LazyObjFile::parse<ELF64BE>();
1230
1231 template class elf::ELFFileBase<ELF32LE>;
1232 template class elf::ELFFileBase<ELF32BE>;
1233 template class elf::ELFFileBase<ELF64LE>;
1234 template class elf::ELFFileBase<ELF64BE>;
1235
1236 template class elf::ObjFile<ELF32LE>;
1237 template class elf::ObjFile<ELF32BE>;
1238 template class elf::ObjFile<ELF64LE>;
1239 template class elf::ObjFile<ELF64BE>;
1240
1241 template class elf::SharedFile<ELF32LE>;
1242 template class elf::SharedFile<ELF32BE>;
1243 template class elf::SharedFile<ELF64LE>;
1244 template class elf::SharedFile<ELF64BE>;