1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "InputFiles.h"
10 #include "Driver.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/DWARF.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Memory.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/Analysis.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/Endian.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/TarWriter.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace llvm;
34 using namespace llvm::ELF;
35 using namespace llvm::object;
36 using namespace llvm::sys;
37 using namespace llvm::sys::fs;
38 using namespace llvm::support::endian;
39 using namespace lld;
40 using namespace lld::elf;
41 
42 bool InputFile::isInGroup;
43 uint32_t InputFile::nextGroupId;
44 
45 std::vector<ArchiveFile *> elf::archiveFiles;
46 std::vector<BinaryFile *> elf::binaryFiles;
47 std::vector<BitcodeFile *> elf::bitcodeFiles;
48 std::vector<LazyObjFile *> elf::lazyObjFiles;
49 std::vector<InputFile *> elf::objectFiles;
50 std::vector<SharedFile *> elf::sharedFiles;
51 
52 std::unique_ptr<TarWriter> elf::tar;
53 
54 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
55 std::string lld::toString(const InputFile *f) {
56   if (!f)
57     return "<internal>";
58 
59   if (f->toStringCache.empty()) {
60     if (f->archiveName.empty())
61       f->toStringCache = std::string(f->getName());
62     else
63       f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str();
64   }
65   return f->toStringCache;
66 }
67 
68 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
69   unsigned char size;
70   unsigned char endian;
71   std::tie(size, endian) = getElfArchType(mb.getBuffer());
72 
73   auto report = [&](StringRef msg) {
74     StringRef filename = mb.getBufferIdentifier();
75     if (archiveName.empty())
76       fatal(filename + ": " + msg);
77     else
78       fatal(archiveName + "(" + filename + "): " + msg);
79   };
80 
81   if (!mb.getBuffer().startswith(ElfMagic))
82     report("not an ELF file");
83   if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
84     report("corrupted ELF file: invalid data encoding");
85   if (size != ELFCLASS32 && size != ELFCLASS64)
86     report("corrupted ELF file: invalid file class");
87 
88   size_t bufSize = mb.getBuffer().size();
89   if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
90       (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
91     report("corrupted ELF file: file is too short");
92 
93   if (size == ELFCLASS32)
94     return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
95   return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
96 }
97 
98 InputFile::InputFile(Kind k, MemoryBufferRef m)
99     : mb(m), groupId(nextGroupId), fileKind(k) {
100   // All files within the same --{start,end}-group get the same group ID.
101   // Otherwise, a new file will get a new group ID.
102   if (!isInGroup)
103     ++nextGroupId;
104 }
105 
106 Optional<MemoryBufferRef> elf::readFile(StringRef path) {
107   // The --chroot option changes our virtual root directory.
108   // This is useful when you are dealing with files created by --reproduce.
109   if (!config->chroot.empty() && path.startswith("/"))
110     path = saver.save(config->chroot + path);
111 
112   log(path);
113 
114   auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
115   if (auto ec = mbOrErr.getError()) {
116     error("cannot open " + path + ": " + ec.message());
117     return None;
118   }
119 
120   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
121   MemoryBufferRef mbref = mb->getMemBufferRef();
122   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
123 
124   if (tar)
125     tar->append(relativeToRoot(path), mbref.getBuffer());
126   return mbref;
127 }
128 
129 // All input object files must be for the same architecture
130 // (e.g. it does not make sense to link x86 object files with
131 // MIPS object files.) This function checks for that error.
132 static bool isCompatible(InputFile *file) {
133   if (!file->isElf() && !isa<BitcodeFile>(file))
134     return true;
135 
136   if (file->ekind == config->ekind && file->emachine == config->emachine) {
137     if (config->emachine != EM_MIPS)
138       return true;
139     if (isMipsN32Abi(file) == config->mipsN32Abi)
140       return true;
141   }
142 
143   StringRef target =
144       !config->bfdname.empty() ? config->bfdname : config->emulation;
145   if (!target.empty()) {
146     error(toString(file) + " is incompatible with " + target);
147     return false;
148   }
149 
150   InputFile *existing;
151   if (!objectFiles.empty())
152     existing = objectFiles[0];
153   else if (!sharedFiles.empty())
154     existing = sharedFiles[0];
155   else if (!bitcodeFiles.empty())
156     existing = bitcodeFiles[0];
157   else
158     llvm_unreachable("Must have -m, OUTPUT_FORMAT or existing input file to "
159                      "determine target emulation");
160 
161   error(toString(file) + " is incompatible with " + toString(existing));
162   return false;
163 }
164 
165 template <class ELFT> static void doParseFile(InputFile *file) {
166   if (!isCompatible(file))
167     return;
168 
169   // Binary file
170   if (auto *f = dyn_cast<BinaryFile>(file)) {
171     binaryFiles.push_back(f);
172     f->parse();
173     return;
174   }
175 
176   // .a file
177   if (auto *f = dyn_cast<ArchiveFile>(file)) {
178     archiveFiles.push_back(f);
179     f->parse();
180     return;
181   }
182 
183   // Lazy object file
184   if (auto *f = dyn_cast<LazyObjFile>(file)) {
185     lazyObjFiles.push_back(f);
186     f->parse<ELFT>();
187     return;
188   }
189 
190   if (config->trace)
191     message(toString(file));
192 
193   // .so file
194   if (auto *f = dyn_cast<SharedFile>(file)) {
195     f->parse<ELFT>();
196     return;
197   }
198 
199   // LLVM bitcode file
200   if (auto *f = dyn_cast<BitcodeFile>(file)) {
201     bitcodeFiles.push_back(f);
202     f->parse<ELFT>();
203     return;
204   }
205 
206   // Regular object file
207   objectFiles.push_back(file);
208   cast<ObjFile<ELFT>>(file)->parse();
209 }
210 
211 // Add symbols in File to the symbol table.
212 void elf::parseFile(InputFile *file) {
213   switch (config->ekind) {
214   case ELF32LEKind:
215     doParseFile<ELF32LE>(file);
216     return;
217   case ELF32BEKind:
218     doParseFile<ELF32BE>(file);
219     return;
220   case ELF64LEKind:
221     doParseFile<ELF64LE>(file);
222     return;
223   case ELF64BEKind:
224     doParseFile<ELF64BE>(file);
225     return;
226   default:
227     llvm_unreachable("unknown ELFT");
228   }
229 }
230 
231 // Concatenates arguments to construct a string representing an error location.
232 static std::string createFileLineMsg(StringRef path, unsigned line) {
233   std::string filename = std::string(path::filename(path));
234   std::string lineno = ":" + std::to_string(line);
235   if (filename == path)
236     return filename + lineno;
237   return filename + lineno + " (" + path.str() + lineno + ")";
238 }
239 
240 template <class ELFT>
241 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
242                                 InputSectionBase &sec, uint64_t offset) {
243   // In DWARF, functions and variables are stored to different places.
244   // First, lookup a function for a given offset.
245   if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
246     return createFileLineMsg(info->FileName, info->Line);
247 
248   // If it failed, lookup again as a variable.
249   if (Optional<std::pair<std::string, unsigned>> fileLine =
250           file.getVariableLoc(sym.getName()))
251     return createFileLineMsg(fileLine->first, fileLine->second);
252 
253   // File.sourceFile contains STT_FILE symbol, and that is a last resort.
254   return std::string(file.sourceFile);
255 }
256 
257 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
258                                  uint64_t offset) {
259   if (kind() != ObjKind)
260     return "";
261   switch (config->ekind) {
262   default:
263     llvm_unreachable("Invalid kind");
264   case ELF32LEKind:
265     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
266   case ELF32BEKind:
267     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
268   case ELF64LEKind:
269     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
270   case ELF64BEKind:
271     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
272   }
273 }
274 
275 template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
276   llvm::call_once(initDwarf, [this]() {
277     dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
278         std::make_unique<LLDDwarfObj<ELFT>>(this), "",
279         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
280         [&](Error warning) {
281           warn(getName() + ": " + toString(std::move(warning)));
282         }));
283   });
284 
285   return dwarf.get();
286 }
287 
288 // Returns the pair of file name and line number describing location of data
289 // object (variable, array, etc) definition.
290 template <class ELFT>
291 Optional<std::pair<std::string, unsigned>>
292 ObjFile<ELFT>::getVariableLoc(StringRef name) {
293   return getDwarf()->getVariableLoc(name);
294 }
295 
296 // Returns source line information for a given offset
297 // using DWARF debug info.
298 template <class ELFT>
299 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
300                                                   uint64_t offset) {
301   // Detect SectionIndex for specified section.
302   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
303   ArrayRef<InputSectionBase *> sections = s->file->getSections();
304   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
305     if (s == sections[curIndex]) {
306       sectionIndex = curIndex;
307       break;
308     }
309   }
310 
311   return getDwarf()->getDILineInfo(offset, sectionIndex);
312 }
313 
314 ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
315   ekind = getELFKind(mb, "");
316 
317   switch (ekind) {
318   case ELF32LEKind:
319     init<ELF32LE>();
320     break;
321   case ELF32BEKind:
322     init<ELF32BE>();
323     break;
324   case ELF64LEKind:
325     init<ELF64LE>();
326     break;
327   case ELF64BEKind:
328     init<ELF64BE>();
329     break;
330   default:
331     llvm_unreachable("getELFKind");
332   }
333 }
334 
335 template <typename Elf_Shdr>
336 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
337   for (const Elf_Shdr &sec : sections)
338     if (sec.sh_type == type)
339       return &sec;
340   return nullptr;
341 }
342 
343 template <class ELFT> void ELFFileBase::init() {
344   using Elf_Shdr = typename ELFT::Shdr;
345   using Elf_Sym = typename ELFT::Sym;
346 
347   // Initialize trivial attributes.
348   const ELFFile<ELFT> &obj = getObj<ELFT>();
349   emachine = obj.getHeader()->e_machine;
350   osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
351   abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
352 
353   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
354 
355   // Find a symbol table.
356   bool isDSO =
357       (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
358   const Elf_Shdr *symtabSec =
359       findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
360 
361   if (!symtabSec)
362     return;
363 
364   // Initialize members corresponding to a symbol table.
365   firstGlobal = symtabSec->sh_info;
366 
367   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
368   if (firstGlobal == 0 || firstGlobal > eSyms.size())
369     fatal(toString(this) + ": invalid sh_info in symbol table");
370 
371   elfSyms = reinterpret_cast<const void *>(eSyms.data());
372   numELFSyms = eSyms.size();
373   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
374 }
375 
376 template <class ELFT>
377 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
378   return CHECK(
379       this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
380       this);
381 }
382 
383 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
384   if (this->symbols.empty())
385     return {};
386   return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
387 }
388 
389 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
390   return makeArrayRef(this->symbols).slice(this->firstGlobal);
391 }
392 
393 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
394   // Read a section table. justSymbols is usually false.
395   if (this->justSymbols)
396     initializeJustSymbols();
397   else
398     initializeSections(ignoreComdats);
399 
400   // Read a symbol table.
401   initializeSymbols();
402 }
403 
404 // Sections with SHT_GROUP and comdat bits define comdat section groups.
405 // They are identified and deduplicated by group name. This function
406 // returns a group name.
407 template <class ELFT>
408 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
409                                               const Elf_Shdr &sec) {
410   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
411   if (sec.sh_info >= symbols.size())
412     fatal(toString(this) + ": invalid symbol index");
413   const typename ELFT::Sym &sym = symbols[sec.sh_info];
414   StringRef signature = CHECK(sym.getName(this->stringTable), this);
415 
416   // As a special case, if a symbol is a section symbol and has no name,
417   // we use a section name as a signature.
418   //
419   // Such SHT_GROUP sections are invalid from the perspective of the ELF
420   // standard, but GNU gold 1.14 (the newest version as of July 2017) or
421   // older produce such sections as outputs for the -r option, so we need
422   // a bug-compatibility.
423   if (signature.empty() && sym.getType() == STT_SECTION)
424     return getSectionName(sec);
425   return signature;
426 }
427 
428 template <class ELFT>
429 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
430   if (!(sec.sh_flags & SHF_MERGE))
431     return false;
432 
433   // On a regular link we don't merge sections if -O0 (default is -O1). This
434   // sometimes makes the linker significantly faster, although the output will
435   // be bigger.
436   //
437   // Doing the same for -r would create a problem as it would combine sections
438   // with different sh_entsize. One option would be to just copy every SHF_MERGE
439   // section as is to the output. While this would produce a valid ELF file with
440   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
441   // they see two .debug_str. We could have separate logic for combining
442   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
443   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
444   // logic for -r.
445   if (config->optimize == 0 && !config->relocatable)
446     return false;
447 
448   // A mergeable section with size 0 is useless because they don't have
449   // any data to merge. A mergeable string section with size 0 can be
450   // argued as invalid because it doesn't end with a null character.
451   // We'll avoid a mess by handling them as if they were non-mergeable.
452   if (sec.sh_size == 0)
453     return false;
454 
455   // Check for sh_entsize. The ELF spec is not clear about the zero
456   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
457   // the section does not hold a table of fixed-size entries". We know
458   // that Rust 1.13 produces a string mergeable section with a zero
459   // sh_entsize. Here we just accept it rather than being picky about it.
460   uint64_t entSize = sec.sh_entsize;
461   if (entSize == 0)
462     return false;
463   if (sec.sh_size % entSize)
464     fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
465           Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
466           Twine(entSize) + ")");
467 
468   if (sec.sh_flags & SHF_WRITE)
469     fatal(toString(this) + ":(" + name +
470           "): writable SHF_MERGE section is not supported");
471 
472   return true;
473 }
474 
475 // This is for --just-symbols.
476 //
477 // --just-symbols is a very minor feature that allows you to link your
478 // output against other existing program, so that if you load both your
479 // program and the other program into memory, your output can refer the
480 // other program's symbols.
481 //
482 // When the option is given, we link "just symbols". The section table is
483 // initialized with null pointers.
484 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
485   ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
486   this->sections.resize(sections.size());
487 }
488 
489 // An ELF object file may contain a `.deplibs` section. If it exists, the
490 // section contains a list of library specifiers such as `m` for libm. This
491 // function resolves a given name by finding the first matching library checking
492 // the various ways that a library can be specified to LLD. This ELF extension
493 // is a form of autolinking and is called `dependent libraries`. It is currently
494 // unique to LLVM and lld.
495 static void addDependentLibrary(StringRef specifier, const InputFile *f) {
496   if (!config->dependentLibraries)
497     return;
498   if (fs::exists(specifier))
499     driver->addFile(specifier, /*withLOption=*/false);
500   else if (Optional<std::string> s = findFromSearchPaths(specifier))
501     driver->addFile(*s, /*withLOption=*/true);
502   else if (Optional<std::string> s = searchLibraryBaseName(specifier))
503     driver->addFile(*s, /*withLOption=*/true);
504   else
505     error(toString(f) +
506           ": unable to find library from dependent library specifier: " +
507           specifier);
508 }
509 
510 // Record the membership of a section group so that in the garbage collection
511 // pass, section group members are kept or discarded as a unit.
512 template <class ELFT>
513 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
514                                ArrayRef<typename ELFT::Word> entries) {
515   bool hasAlloc = false;
516   for (uint32_t index : entries.slice(1)) {
517     if (index >= sections.size())
518       return;
519     if (InputSectionBase *s = sections[index])
520       if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
521         hasAlloc = true;
522   }
523 
524   // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
525   // collection. See the comment in markLive(). This rule retains .debug_types
526   // and .rela.debug_types.
527   if (!hasAlloc)
528     return;
529 
530   // Connect the members in a circular doubly-linked list via
531   // nextInSectionGroup.
532   InputSectionBase *head;
533   InputSectionBase *prev = nullptr;
534   for (uint32_t index : entries.slice(1)) {
535     InputSectionBase *s = sections[index];
536     if (!s || s == &InputSection::discarded)
537       continue;
538     if (prev)
539       prev->nextInSectionGroup = s;
540     else
541       head = s;
542     prev = s;
543   }
544   if (prev)
545     prev->nextInSectionGroup = head;
546 }
547 
548 template <class ELFT>
549 void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
550   const ELFFile<ELFT> &obj = this->getObj();
551 
552   ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
553   uint64_t size = objSections.size();
554   this->sections.resize(size);
555   this->sectionStringTable =
556       CHECK(obj.getSectionStringTable(objSections), this);
557 
558   std::vector<ArrayRef<Elf_Word>> selectedGroups;
559 
560   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
561     if (this->sections[i] == &InputSection::discarded)
562       continue;
563     const Elf_Shdr &sec = objSections[i];
564 
565     if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
566       cgProfile =
567           check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
568 
569     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
570     // if -r is given, we'll let the final link discard such sections.
571     // This is compatible with GNU.
572     if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
573       if (sec.sh_type == SHT_LLVM_ADDRSIG) {
574         // We ignore the address-significance table if we know that the object
575         // file was created by objcopy or ld -r. This is because these tools
576         // will reorder the symbols in the symbol table, invalidating the data
577         // in the address-significance table, which refers to symbols by index.
578         if (sec.sh_link != 0)
579           this->addrsigSec = &sec;
580         else if (config->icf == ICFLevel::Safe)
581           warn(toString(this) + ": --icf=safe is incompatible with object "
582                                 "files created using objcopy or ld -r");
583       }
584       this->sections[i] = &InputSection::discarded;
585       continue;
586     }
587 
588     switch (sec.sh_type) {
589     case SHT_GROUP: {
590       // De-duplicate section groups by their signatures.
591       StringRef signature = getShtGroupSignature(objSections, sec);
592       this->sections[i] = &InputSection::discarded;
593 
594 
595       ArrayRef<Elf_Word> entries =
596           CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
597       if (entries.empty())
598         fatal(toString(this) + ": empty SHT_GROUP");
599 
600       // The first word of a SHT_GROUP section contains flags. Currently,
601       // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
602       // An group with the empty flag doesn't define anything; such sections
603       // are just skipped.
604       if (entries[0] == 0)
605         continue;
606 
607       if (entries[0] != GRP_COMDAT)
608         fatal(toString(this) + ": unsupported SHT_GROUP format");
609 
610       bool isNew =
611           ignoreComdats ||
612           symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
613               .second;
614       if (isNew) {
615         if (config->relocatable)
616           this->sections[i] = createInputSection(sec);
617         selectedGroups.push_back(entries);
618         continue;
619       }
620 
621       // Otherwise, discard group members.
622       for (uint32_t secIndex : entries.slice(1)) {
623         if (secIndex >= size)
624           fatal(toString(this) +
625                 ": invalid section index in group: " + Twine(secIndex));
626         this->sections[secIndex] = &InputSection::discarded;
627       }
628       break;
629     }
630     case SHT_SYMTAB_SHNDX:
631       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
632       break;
633     case SHT_SYMTAB:
634     case SHT_STRTAB:
635     case SHT_NULL:
636       break;
637     default:
638       this->sections[i] = createInputSection(sec);
639     }
640   }
641 
642   // This block handles SHF_LINK_ORDER.
643   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
644     if (this->sections[i] == &InputSection::discarded)
645       continue;
646     const Elf_Shdr &sec = objSections[i];
647     if (!(sec.sh_flags & SHF_LINK_ORDER))
648       continue;
649 
650     // .ARM.exidx sections have a reverse dependency on the InputSection they
651     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
652     InputSectionBase *linkSec = nullptr;
653     if (sec.sh_link < this->sections.size())
654       linkSec = this->sections[sec.sh_link];
655     if (!linkSec)
656       fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
657 
658     InputSection *isec = cast<InputSection>(this->sections[i]);
659     linkSec->dependentSections.push_back(isec);
660     if (!isa<InputSection>(linkSec))
661       error("a section " + isec->name +
662             " with SHF_LINK_ORDER should not refer a non-regular section: " +
663             toString(linkSec));
664   }
665 
666   for (ArrayRef<Elf_Word> entries : selectedGroups)
667     handleSectionGroup<ELFT>(this->sections, entries);
668 }
669 
670 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
671 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
672 // the input objects have been compiled.
673 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
674                              const InputFile *f) {
675   Optional<unsigned> attr =
676       attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
677   if (!attr.hasValue())
678     // If an ABI tag isn't present then it is implicitly given the value of 0
679     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
680     // including some in glibc that don't use FP args (and should have value 3)
681     // don't have the attribute so we do not consider an implicit value of 0
682     // as a clash.
683     return;
684 
685   unsigned vfpArgs = attr.getValue();
686   ARMVFPArgKind arg;
687   switch (vfpArgs) {
688   case ARMBuildAttrs::BaseAAPCS:
689     arg = ARMVFPArgKind::Base;
690     break;
691   case ARMBuildAttrs::HardFPAAPCS:
692     arg = ARMVFPArgKind::VFP;
693     break;
694   case ARMBuildAttrs::ToolChainFPPCS:
695     // Tool chain specific convention that conforms to neither AAPCS variant.
696     arg = ARMVFPArgKind::ToolChain;
697     break;
698   case ARMBuildAttrs::CompatibleFPAAPCS:
699     // Object compatible with all conventions.
700     return;
701   default:
702     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
703     return;
704   }
705   // Follow ld.bfd and error if there is a mix of calling conventions.
706   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
707     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
708   else
709     config->armVFPArgs = arg;
710 }
711 
712 // The ARM support in lld makes some use of instructions that are not available
713 // on all ARM architectures. Namely:
714 // - Use of BLX instruction for interworking between ARM and Thumb state.
715 // - Use of the extended Thumb branch encoding in relocation.
716 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
717 // The ARM Attributes section contains information about the architecture chosen
718 // at compile time. We follow the convention that if at least one input object
719 // is compiled with an architecture that supports these features then lld is
720 // permitted to use them.
721 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
722   Optional<unsigned> attr =
723       attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
724   if (!attr.hasValue())
725     return;
726   auto arch = attr.getValue();
727   switch (arch) {
728   case ARMBuildAttrs::Pre_v4:
729   case ARMBuildAttrs::v4:
730   case ARMBuildAttrs::v4T:
731     // Architectures prior to v5 do not support BLX instruction
732     break;
733   case ARMBuildAttrs::v5T:
734   case ARMBuildAttrs::v5TE:
735   case ARMBuildAttrs::v5TEJ:
736   case ARMBuildAttrs::v6:
737   case ARMBuildAttrs::v6KZ:
738   case ARMBuildAttrs::v6K:
739     config->armHasBlx = true;
740     // Architectures used in pre-Cortex processors do not support
741     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
742     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
743     break;
744   default:
745     // All other Architectures have BLX and extended branch encoding
746     config->armHasBlx = true;
747     config->armJ1J2BranchEncoding = true;
748     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
749       // All Architectures used in Cortex processors with the exception
750       // of v6-M and v6S-M have the MOVT and MOVW instructions.
751       config->armHasMovtMovw = true;
752     break;
753   }
754 }
755 
756 // If a source file is compiled with x86 hardware-assisted call flow control
757 // enabled, the generated object file contains feature flags indicating that
758 // fact. This function reads the feature flags and returns it.
759 //
760 // Essentially we want to read a single 32-bit value in this function, but this
761 // function is rather complicated because the value is buried deep inside a
762 // .note.gnu.property section.
763 //
764 // The section consists of one or more NOTE records. Each NOTE record consists
765 // of zero or more type-length-value fields. We want to find a field of a
766 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
767 // the ABI is unnecessarily complicated.
768 template <class ELFT>
769 static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
770   using Elf_Nhdr = typename ELFT::Nhdr;
771   using Elf_Note = typename ELFT::Note;
772 
773   uint32_t featuresSet = 0;
774   while (!data.empty()) {
775     // Read one NOTE record.
776     if (data.size() < sizeof(Elf_Nhdr))
777       fatal(toString(obj) + ": .note.gnu.property: section too short");
778 
779     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
780     if (data.size() < nhdr->getSize())
781       fatal(toString(obj) + ": .note.gnu.property: section too short");
782 
783     Elf_Note note(*nhdr);
784     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
785       data = data.slice(nhdr->getSize());
786       continue;
787     }
788 
789     uint32_t featureAndType = config->emachine == EM_AARCH64
790                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
791                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
792 
793     // Read a body of a NOTE record, which consists of type-length-value fields.
794     ArrayRef<uint8_t> desc = note.getDesc();
795     while (!desc.empty()) {
796       if (desc.size() < 8)
797         fatal(toString(obj) + ": .note.gnu.property: section too short");
798 
799       uint32_t type = read32le(desc.data());
800       uint32_t size = read32le(desc.data() + 4);
801 
802       if (type == featureAndType) {
803         // We found a FEATURE_1_AND field. There may be more than one of these
804         // in a .note.gnu.property section, for a relocatable object we
805         // accumulate the bits set.
806         featuresSet |= read32le(desc.data() + 8);
807       }
808 
809       // On 64-bit, a payload may be followed by a 4-byte padding to make its
810       // size a multiple of 8.
811       if (ELFT::Is64Bits)
812         size = alignTo(size, 8);
813 
814       desc = desc.slice(size + 8); // +8 for Type and Size
815     }
816 
817     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
818     data = data.slice(nhdr->getSize());
819   }
820 
821   return featuresSet;
822 }
823 
824 template <class ELFT>
825 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
826   uint32_t idx = sec.sh_info;
827   if (idx >= this->sections.size())
828     fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
829   InputSectionBase *target = this->sections[idx];
830 
831   // Strictly speaking, a relocation section must be included in the
832   // group of the section it relocates. However, LLVM 3.3 and earlier
833   // would fail to do so, so we gracefully handle that case.
834   if (target == &InputSection::discarded)
835     return nullptr;
836 
837   if (!target)
838     fatal(toString(this) + ": unsupported relocation reference");
839   return target;
840 }
841 
842 // Create a regular InputSection class that has the same contents
843 // as a given section.
844 static InputSection *toRegularSection(MergeInputSection *sec) {
845   return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
846                             sec->data(), sec->name);
847 }
848 
849 template <class ELFT>
850 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
851   StringRef name = getSectionName(sec);
852 
853   switch (sec.sh_type) {
854   case SHT_ARM_ATTRIBUTES: {
855     if (config->emachine != EM_ARM)
856       break;
857     ARMAttributeParser attributes;
858     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
859     if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
860                                                  ? support::little
861                                                  : support::big)) {
862       auto *isec = make<InputSection>(*this, sec, name);
863       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
864       break;
865     }
866     updateSupportedARMFeatures(attributes);
867     updateARMVFPArgs(attributes, this);
868 
869     // FIXME: Retain the first attribute section we see. The eglibc ARM
870     // dynamic loaders require the presence of an attribute section for dlopen
871     // to work. In a full implementation we would merge all attribute sections.
872     if (in.armAttributes == nullptr) {
873       in.armAttributes = make<InputSection>(*this, sec, name);
874       return in.armAttributes;
875     }
876     return &InputSection::discarded;
877   }
878   case SHT_LLVM_DEPENDENT_LIBRARIES: {
879     if (config->relocatable)
880       break;
881     ArrayRef<char> data =
882         CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
883     if (!data.empty() && data.back() != '\0') {
884       error(toString(this) +
885             ": corrupted dependent libraries section (unterminated string): " +
886             name);
887       return &InputSection::discarded;
888     }
889     for (const char *d = data.begin(), *e = data.end(); d < e;) {
890       StringRef s(d);
891       addDependentLibrary(s, this);
892       d += s.size() + 1;
893     }
894     return &InputSection::discarded;
895   }
896   case SHT_RELA:
897   case SHT_REL: {
898     // Find a relocation target section and associate this section with that.
899     // Target may have been discarded if it is in a different section group
900     // and the group is discarded, even though it's a violation of the
901     // spec. We handle that situation gracefully by discarding dangling
902     // relocation sections.
903     InputSectionBase *target = getRelocTarget(sec);
904     if (!target)
905       return nullptr;
906 
907     // ELF spec allows mergeable sections with relocations, but they are
908     // rare, and it is in practice hard to merge such sections by contents,
909     // because applying relocations at end of linking changes section
910     // contents. So, we simply handle such sections as non-mergeable ones.
911     // Degrading like this is acceptable because section merging is optional.
912     if (auto *ms = dyn_cast<MergeInputSection>(target)) {
913       target = toRegularSection(ms);
914       this->sections[sec.sh_info] = target;
915     }
916 
917     // This section contains relocation information.
918     // If -r is given, we do not interpret or apply relocation
919     // but just copy relocation sections to output.
920     if (config->relocatable) {
921       InputSection *relocSec = make<InputSection>(*this, sec, name);
922       // We want to add a dependency to target, similar like we do for
923       // -emit-relocs below. This is useful for the case when linker script
924       // contains the "/DISCARD/". It is perhaps uncommon to use a script with
925       // -r, but we faced it in the Linux kernel and have to handle such case
926       // and not to crash.
927       target->dependentSections.push_back(relocSec);
928       return relocSec;
929     }
930 
931     if (target->firstRelocation)
932       fatal(toString(this) +
933             ": multiple relocation sections to one section are not supported");
934 
935     if (sec.sh_type == SHT_RELA) {
936       ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
937       target->firstRelocation = rels.begin();
938       target->numRelocations = rels.size();
939       target->areRelocsRela = true;
940     } else {
941       ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
942       target->firstRelocation = rels.begin();
943       target->numRelocations = rels.size();
944       target->areRelocsRela = false;
945     }
946     assert(isUInt<31>(target->numRelocations));
947 
948     // Relocation sections processed by the linker are usually removed
949     // from the output, so returning `nullptr` for the normal case.
950     // However, if -emit-relocs is given, we need to leave them in the output.
951     // (Some post link analysis tools need this information.)
952     if (config->emitRelocs) {
953       InputSection *relocSec = make<InputSection>(*this, sec, name);
954       // We will not emit relocation section if target was discarded.
955       target->dependentSections.push_back(relocSec);
956       return relocSec;
957     }
958     return nullptr;
959   }
960   }
961 
962   // The GNU linker uses .note.GNU-stack section as a marker indicating
963   // that the code in the object file does not expect that the stack is
964   // executable (in terms of NX bit). If all input files have the marker,
965   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
966   // make the stack non-executable. Most object files have this section as
967   // of 2017.
968   //
969   // But making the stack non-executable is a norm today for security
970   // reasons. Failure to do so may result in a serious security issue.
971   // Therefore, we make LLD always add PT_GNU_STACK unless it is
972   // explicitly told to do otherwise (by -z execstack). Because the stack
973   // executable-ness is controlled solely by command line options,
974   // .note.GNU-stack sections are simply ignored.
975   if (name == ".note.GNU-stack")
976     return &InputSection::discarded;
977 
978   // Object files that use processor features such as Intel Control-Flow
979   // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
980   // .note.gnu.property section containing a bitfield of feature bits like the
981   // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
982   //
983   // Since we merge bitmaps from multiple object files to create a new
984   // .note.gnu.property containing a single AND'ed bitmap, we discard an input
985   // file's .note.gnu.property section.
986   if (name == ".note.gnu.property") {
987     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
988     this->andFeatures = readAndFeatures(this, contents);
989     return &InputSection::discarded;
990   }
991 
992   // Split stacks is a feature to support a discontiguous stack,
993   // commonly used in the programming language Go. For the details,
994   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
995   // for split stack will include a .note.GNU-split-stack section.
996   if (name == ".note.GNU-split-stack") {
997     if (config->relocatable) {
998       error("cannot mix split-stack and non-split-stack in a relocatable link");
999       return &InputSection::discarded;
1000     }
1001     this->splitStack = true;
1002     return &InputSection::discarded;
1003   }
1004 
1005   // An object file cmpiled for split stack, but where some of the
1006   // functions were compiled with the no_split_stack_attribute will
1007   // include a .note.GNU-no-split-stack section.
1008   if (name == ".note.GNU-no-split-stack") {
1009     this->someNoSplitStack = true;
1010     return &InputSection::discarded;
1011   }
1012 
1013   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1014   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1015   // sections. Drop those sections to avoid duplicate symbol errors.
1016   // FIXME: This is glibc PR20543, we should remove this hack once that has been
1017   // fixed for a while.
1018   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1019       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1020     return &InputSection::discarded;
1021 
1022   // If we are creating a new .build-id section, strip existing .build-id
1023   // sections so that the output won't have more than one .build-id.
1024   // This is not usually a problem because input object files normally don't
1025   // have .build-id sections, but you can create such files by
1026   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1027   if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
1028     return &InputSection::discarded;
1029 
1030   // The linker merges EH (exception handling) frames and creates a
1031   // .eh_frame_hdr section for runtime. So we handle them with a special
1032   // class. For relocatable outputs, they are just passed through.
1033   if (name == ".eh_frame" && !config->relocatable)
1034     return make<EhInputSection>(*this, sec, name);
1035 
1036   if (shouldMerge(sec, name))
1037     return make<MergeInputSection>(*this, sec, name);
1038   return make<InputSection>(*this, sec, name);
1039 }
1040 
1041 template <class ELFT>
1042 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1043   return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1044 }
1045 
1046 // Initialize this->Symbols. this->Symbols is a parallel array as
1047 // its corresponding ELF symbol table.
1048 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1049   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1050   this->symbols.resize(eSyms.size());
1051 
1052   // Fill in InputFile::symbols. Some entries have been initialized
1053   // because of LazyObjFile.
1054   for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
1055     if (this->symbols[i])
1056       continue;
1057     const Elf_Sym &eSym = eSyms[i];
1058     uint32_t secIdx = getSectionIndex(eSym);
1059     if (secIdx >= this->sections.size())
1060       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1061     if (eSym.getBinding() != STB_LOCAL) {
1062       if (i < firstGlobal)
1063         error(toString(this) + ": non-local symbol (" + Twine(i) +
1064               ") found at index < .symtab's sh_info (" + Twine(firstGlobal) +
1065               ")");
1066       this->symbols[i] =
1067           symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1068       continue;
1069     }
1070 
1071     // Handle local symbols. Local symbols are not added to the symbol
1072     // table because they are not visible from other object files. We
1073     // allocate symbol instances and add their pointers to symbols.
1074     if (i >= firstGlobal)
1075       errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) +
1076                   ") found at index >= .symtab's sh_info (" +
1077                   Twine(firstGlobal) + ")");
1078 
1079     InputSectionBase *sec = this->sections[secIdx];
1080     uint8_t type = eSym.getType();
1081     if (type == STT_FILE)
1082       sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083     if (this->stringTable.size() <= eSym.st_name)
1084       fatal(toString(this) + ": invalid symbol name offset");
1085     StringRefZ name = this->stringTable.data() + eSym.st_name;
1086 
1087     if (eSym.st_shndx == SHN_UNDEF)
1088       this->symbols[i] =
1089           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type);
1090     else if (sec == &InputSection::discarded)
1091       this->symbols[i] =
1092           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type,
1093                           /*discardedSecIdx=*/secIdx);
1094     else
1095       this->symbols[i] = make<Defined>(this, name, STB_LOCAL, eSym.st_other,
1096                                        type, eSym.st_value, eSym.st_size, sec);
1097   }
1098 
1099   // Symbol resolution of non-local symbols.
1100   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1101     const Elf_Sym &eSym = eSyms[i];
1102     uint8_t binding = eSym.getBinding();
1103     if (binding == STB_LOCAL)
1104       continue; // Errored above.
1105 
1106     uint32_t secIdx = getSectionIndex(eSym);
1107     InputSectionBase *sec = this->sections[secIdx];
1108     uint8_t stOther = eSym.st_other;
1109     uint8_t type = eSym.getType();
1110     uint64_t value = eSym.st_value;
1111     uint64_t size = eSym.st_size;
1112     StringRefZ name = this->stringTable.data() + eSym.st_name;
1113 
1114     // Handle global undefined symbols.
1115     if (eSym.st_shndx == SHN_UNDEF) {
1116       this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1117       this->symbols[i]->referenced = true;
1118       continue;
1119     }
1120 
1121     // Handle global common symbols.
1122     if (eSym.st_shndx == SHN_COMMON) {
1123       if (value == 0 || value >= UINT32_MAX)
1124         fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1125               "' has invalid alignment: " + Twine(value));
1126       this->symbols[i]->resolve(
1127           CommonSymbol{this, name, binding, stOther, type, value, size});
1128       continue;
1129     }
1130 
1131     // If a defined symbol is in a discarded section, handle it as if it
1132     // were an undefined symbol. Such symbol doesn't comply with the
1133     // standard, but in practice, a .eh_frame often directly refer
1134     // COMDAT member sections, and if a comdat group is discarded, some
1135     // defined symbol in a .eh_frame becomes dangling symbols.
1136     if (sec == &InputSection::discarded) {
1137       Undefined und{this, name, binding, stOther, type, secIdx};
1138       Symbol *sym = this->symbols[i];
1139       // !ArchiveFile::parsed or LazyObjFile::fetched means that the file
1140       // containing this object has not finished processing, i.e. this symbol is
1141       // a result of a lazy symbol fetch. We should demote the lazy symbol to an
1142       // Undefined so that any relocations outside of the group to it will
1143       // trigger a discarded section error.
1144       if ((sym->symbolKind == Symbol::LazyArchiveKind &&
1145            !cast<ArchiveFile>(sym->file)->parsed) ||
1146           (sym->symbolKind == Symbol::LazyObjectKind &&
1147            cast<LazyObjFile>(sym->file)->fetched))
1148         sym->replace(und);
1149       else
1150         sym->resolve(und);
1151       continue;
1152     }
1153 
1154     // Handle global defined symbols.
1155     if (binding == STB_GLOBAL || binding == STB_WEAK ||
1156         binding == STB_GNU_UNIQUE) {
1157       this->symbols[i]->resolve(
1158           Defined{this, name, binding, stOther, type, value, size, sec});
1159       continue;
1160     }
1161 
1162     fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1163   }
1164 }
1165 
1166 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
1167     : InputFile(ArchiveKind, file->getMemoryBufferRef()),
1168       file(std::move(file)) {}
1169 
1170 void ArchiveFile::parse() {
1171   for (const Archive::Symbol &sym : file->symbols())
1172     symtab->addSymbol(LazyArchive{*this, sym});
1173 
1174   // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this
1175   // archive has been processed.
1176   parsed = true;
1177 }
1178 
1179 // Returns a buffer pointing to a member file containing a given symbol.
1180 void ArchiveFile::fetch(const Archive::Symbol &sym) {
1181   Archive::Child c =
1182       CHECK(sym.getMember(), toString(this) +
1183                                  ": could not get the member for symbol " +
1184                                  toELFString(sym));
1185 
1186   if (!seen.insert(c.getChildOffset()).second)
1187     return;
1188 
1189   MemoryBufferRef mb =
1190       CHECK(c.getMemoryBufferRef(),
1191             toString(this) +
1192                 ": could not get the buffer for the member defining symbol " +
1193                 toELFString(sym));
1194 
1195   if (tar && c.getParent()->isThin())
1196     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
1197 
1198   InputFile *file = createObjectFile(mb, getName(), c.getChildOffset());
1199   file->groupId = groupId;
1200   parseFile(file);
1201 }
1202 
1203 size_t ArchiveFile::getMemberCount() const {
1204   size_t count = 0;
1205   Error err = Error::success();
1206   for (const Archive::Child &c : file->children(err)) {
1207     (void)c;
1208     ++count;
1209   }
1210   // This function is used by --print-archive-stats=, where an error does not
1211   // really matter.
1212   consumeError(std::move(err));
1213   return count;
1214 }
1215 
1216 unsigned SharedFile::vernauxNum;
1217 
1218 // Parse the version definitions in the object file if present, and return a
1219 // vector whose nth element contains a pointer to the Elf_Verdef for version
1220 // identifier n. Version identifiers that are not definitions map to nullptr.
1221 template <typename ELFT>
1222 static std::vector<const void *> parseVerdefs(const uint8_t *base,
1223                                               const typename ELFT::Shdr *sec) {
1224   if (!sec)
1225     return {};
1226 
1227   // We cannot determine the largest verdef identifier without inspecting
1228   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1229   // sequentially starting from 1, so we predict that the largest identifier
1230   // will be verdefCount.
1231   unsigned verdefCount = sec->sh_info;
1232   std::vector<const void *> verdefs(verdefCount + 1);
1233 
1234   // Build the Verdefs array by following the chain of Elf_Verdef objects
1235   // from the start of the .gnu.version_d section.
1236   const uint8_t *verdef = base + sec->sh_offset;
1237   for (unsigned i = 0; i != verdefCount; ++i) {
1238     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1239     verdef += curVerdef->vd_next;
1240     unsigned verdefIndex = curVerdef->vd_ndx;
1241     verdefs.resize(verdefIndex + 1);
1242     verdefs[verdefIndex] = curVerdef;
1243   }
1244   return verdefs;
1245 }
1246 
1247 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1248 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1249 // implement sophisticated error checking like in llvm-readobj because the value
1250 // of such diagnostics is low.
1251 template <typename ELFT>
1252 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1253                                                const typename ELFT::Shdr *sec) {
1254   if (!sec)
1255     return {};
1256   std::vector<uint32_t> verneeds;
1257   ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(sec), this);
1258   const uint8_t *verneedBuf = data.begin();
1259   for (unsigned i = 0; i != sec->sh_info; ++i) {
1260     if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
1261       fatal(toString(this) + " has an invalid Verneed");
1262     auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1263     const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1264     for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1265       if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
1266         fatal(toString(this) + " has an invalid Vernaux");
1267       auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1268       if (aux->vna_name >= this->stringTable.size())
1269         fatal(toString(this) + " has a Vernaux with an invalid vna_name");
1270       uint16_t version = aux->vna_other & VERSYM_VERSION;
1271       if (version >= verneeds.size())
1272         verneeds.resize(version + 1);
1273       verneeds[version] = aux->vna_name;
1274       vernauxBuf += aux->vna_next;
1275     }
1276     verneedBuf += vn->vn_next;
1277   }
1278   return verneeds;
1279 }
1280 
1281 // We do not usually care about alignments of data in shared object
1282 // files because the loader takes care of it. However, if we promote a
1283 // DSO symbol to point to .bss due to copy relocation, we need to keep
1284 // the original alignment requirements. We infer it in this function.
1285 template <typename ELFT>
1286 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1287                              const typename ELFT::Sym &sym) {
1288   uint64_t ret = UINT64_MAX;
1289   if (sym.st_value)
1290     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1291   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1292     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1293   return (ret > UINT32_MAX) ? 0 : ret;
1294 }
1295 
1296 // Fully parse the shared object file.
1297 //
1298 // This function parses symbol versions. If a DSO has version information,
1299 // the file has a ".gnu.version_d" section which contains symbol version
1300 // definitions. Each symbol is associated to one version through a table in
1301 // ".gnu.version" section. That table is a parallel array for the symbol
1302 // table, and each table entry contains an index in ".gnu.version_d".
1303 //
1304 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1305 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1306 // ".gnu.version_d".
1307 //
1308 // The file format for symbol versioning is perhaps a bit more complicated
1309 // than necessary, but you can easily understand the code if you wrap your
1310 // head around the data structure described above.
1311 template <class ELFT> void SharedFile::parse() {
1312   using Elf_Dyn = typename ELFT::Dyn;
1313   using Elf_Shdr = typename ELFT::Shdr;
1314   using Elf_Sym = typename ELFT::Sym;
1315   using Elf_Verdef = typename ELFT::Verdef;
1316   using Elf_Versym = typename ELFT::Versym;
1317 
1318   ArrayRef<Elf_Dyn> dynamicTags;
1319   const ELFFile<ELFT> obj = this->getObj<ELFT>();
1320   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1321 
1322   const Elf_Shdr *versymSec = nullptr;
1323   const Elf_Shdr *verdefSec = nullptr;
1324   const Elf_Shdr *verneedSec = nullptr;
1325 
1326   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1327   for (const Elf_Shdr &sec : sections) {
1328     switch (sec.sh_type) {
1329     default:
1330       continue;
1331     case SHT_DYNAMIC:
1332       dynamicTags =
1333           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1334       break;
1335     case SHT_GNU_versym:
1336       versymSec = &sec;
1337       break;
1338     case SHT_GNU_verdef:
1339       verdefSec = &sec;
1340       break;
1341     case SHT_GNU_verneed:
1342       verneedSec = &sec;
1343       break;
1344     }
1345   }
1346 
1347   if (versymSec && numELFSyms == 0) {
1348     error("SHT_GNU_versym should be associated with symbol table");
1349     return;
1350   }
1351 
1352   // Search for a DT_SONAME tag to initialize this->soName.
1353   for (const Elf_Dyn &dyn : dynamicTags) {
1354     if (dyn.d_tag == DT_NEEDED) {
1355       uint64_t val = dyn.getVal();
1356       if (val >= this->stringTable.size())
1357         fatal(toString(this) + ": invalid DT_NEEDED entry");
1358       dtNeeded.push_back(this->stringTable.data() + val);
1359     } else if (dyn.d_tag == DT_SONAME) {
1360       uint64_t val = dyn.getVal();
1361       if (val >= this->stringTable.size())
1362         fatal(toString(this) + ": invalid DT_SONAME entry");
1363       soName = this->stringTable.data() + val;
1364     }
1365   }
1366 
1367   // DSOs are uniquified not by filename but by soname.
1368   DenseMap<StringRef, SharedFile *>::iterator it;
1369   bool wasInserted;
1370   std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1371 
1372   // If a DSO appears more than once on the command line with and without
1373   // --as-needed, --no-as-needed takes precedence over --as-needed because a
1374   // user can add an extra DSO with --no-as-needed to force it to be added to
1375   // the dependency list.
1376   it->second->isNeeded |= isNeeded;
1377   if (!wasInserted)
1378     return;
1379 
1380   sharedFiles.push_back(this);
1381 
1382   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1383   std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1384 
1385   // Parse ".gnu.version" section which is a parallel array for the symbol
1386   // table. If a given file doesn't have a ".gnu.version" section, we use
1387   // VER_NDX_GLOBAL.
1388   size_t size = numELFSyms - firstGlobal;
1389   std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1390   if (versymSec) {
1391     ArrayRef<Elf_Versym> versym =
1392         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1393               this)
1394             .slice(firstGlobal);
1395     for (size_t i = 0; i < size; ++i)
1396       versyms[i] = versym[i].vs_index;
1397   }
1398 
1399   // System libraries can have a lot of symbols with versions. Using a
1400   // fixed buffer for computing the versions name (foo@ver) can save a
1401   // lot of allocations.
1402   SmallString<0> versionedNameBuffer;
1403 
1404   // Add symbols to the symbol table.
1405   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1406   for (size_t i = 0; i < syms.size(); ++i) {
1407     const Elf_Sym &sym = syms[i];
1408 
1409     // ELF spec requires that all local symbols precede weak or global
1410     // symbols in each symbol table, and the index of first non-local symbol
1411     // is stored to sh_info. If a local symbol appears after some non-local
1412     // symbol, that's a violation of the spec.
1413     StringRef name = CHECK(sym.getName(this->stringTable), this);
1414     if (sym.getBinding() == STB_LOCAL) {
1415       warn("found local symbol '" + name +
1416            "' in global part of symbol table in file " + toString(this));
1417       continue;
1418     }
1419 
1420     uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
1421     if (sym.isUndefined()) {
1422       // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1423       // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1424       if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
1425         if (idx >= verneeds.size()) {
1426           error("corrupt input file: version need index " + Twine(idx) +
1427                 " for symbol " + name + " is out of bounds\n>>> defined in " +
1428                 toString(this));
1429           continue;
1430         }
1431         StringRef verName = this->stringTable.data() + verneeds[idx];
1432         versionedNameBuffer.clear();
1433         name =
1434             saver.save((name + "@" + verName).toStringRef(versionedNameBuffer));
1435       }
1436       Symbol *s = symtab->addSymbol(
1437           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1438       s->exportDynamic = true;
1439       continue;
1440     }
1441 
1442     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1443     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1444     // workaround for this bug.
1445     if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
1446         name == "_gp_disp")
1447       continue;
1448 
1449     uint32_t alignment = getAlignment<ELFT>(sections, sym);
1450     if (!(versyms[i] & VERSYM_HIDDEN)) {
1451       symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1452                                      sym.st_other, sym.getType(), sym.st_value,
1453                                      sym.st_size, alignment, idx});
1454     }
1455 
1456     // Also add the symbol with the versioned name to handle undefined symbols
1457     // with explicit versions.
1458     if (idx == VER_NDX_GLOBAL)
1459       continue;
1460 
1461     if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1462       error("corrupt input file: version definition index " + Twine(idx) +
1463             " for symbol " + name + " is out of bounds\n>>> defined in " +
1464             toString(this));
1465       continue;
1466     }
1467 
1468     StringRef verName =
1469         this->stringTable.data() +
1470         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1471     versionedNameBuffer.clear();
1472     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1473     symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1474                                    sym.st_other, sym.getType(), sym.st_value,
1475                                    sym.st_size, alignment, idx});
1476   }
1477 }
1478 
1479 static ELFKind getBitcodeELFKind(const Triple &t) {
1480   if (t.isLittleEndian())
1481     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1482   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1483 }
1484 
1485 static uint8_t getBitcodeMachineKind(StringRef path, const Triple &t) {
1486   switch (t.getArch()) {
1487   case Triple::aarch64:
1488     return EM_AARCH64;
1489   case Triple::amdgcn:
1490   case Triple::r600:
1491     return EM_AMDGPU;
1492   case Triple::arm:
1493   case Triple::thumb:
1494     return EM_ARM;
1495   case Triple::avr:
1496     return EM_AVR;
1497   case Triple::mips:
1498   case Triple::mipsel:
1499   case Triple::mips64:
1500   case Triple::mips64el:
1501     return EM_MIPS;
1502   case Triple::msp430:
1503     return EM_MSP430;
1504   case Triple::ppc:
1505     return EM_PPC;
1506   case Triple::ppc64:
1507   case Triple::ppc64le:
1508     return EM_PPC64;
1509   case Triple::riscv32:
1510   case Triple::riscv64:
1511     return EM_RISCV;
1512   case Triple::x86:
1513     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1514   case Triple::x86_64:
1515     return EM_X86_64;
1516   default:
1517     error(path + ": could not infer e_machine from bitcode target triple " +
1518           t.str());
1519     return EM_NONE;
1520   }
1521 }
1522 
1523 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1524                          uint64_t offsetInArchive)
1525     : InputFile(BitcodeKind, mb) {
1526   this->archiveName = std::string(archiveName);
1527 
1528   std::string path = mb.getBufferIdentifier().str();
1529   if (config->thinLTOIndexOnly)
1530     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
1531 
1532   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1533   // name. If two archives define two members with the same name, this
1534   // causes a collision which result in only one of the objects being taken
1535   // into consideration at LTO time (which very likely causes undefined
1536   // symbols later in the link stage). So we append file offset to make
1537   // filename unique.
1538   StringRef name =
1539       archiveName.empty()
1540           ? saver.save(path)
1541           : saver.save(archiveName + "(" + path::filename(path) + " at " +
1542                        utostr(offsetInArchive) + ")");
1543   MemoryBufferRef mbref(mb.getBuffer(), name);
1544 
1545   obj = CHECK(lto::InputFile::create(mbref), this);
1546 
1547   Triple t(obj->getTargetTriple());
1548   ekind = getBitcodeELFKind(t);
1549   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1550 }
1551 
1552 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1553   switch (gvVisibility) {
1554   case GlobalValue::DefaultVisibility:
1555     return STV_DEFAULT;
1556   case GlobalValue::HiddenVisibility:
1557     return STV_HIDDEN;
1558   case GlobalValue::ProtectedVisibility:
1559     return STV_PROTECTED;
1560   }
1561   llvm_unreachable("unknown visibility");
1562 }
1563 
1564 template <class ELFT>
1565 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
1566                                    const lto::InputFile::Symbol &objSym,
1567                                    BitcodeFile &f) {
1568   StringRef name = saver.save(objSym.getName());
1569   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1570   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1571   uint8_t visibility = mapVisibility(objSym.getVisibility());
1572   bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
1573 
1574   int c = objSym.getComdatIndex();
1575   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1576     Undefined newSym(&f, name, binding, visibility, type);
1577     if (canOmitFromDynSym)
1578       newSym.exportDynamic = false;
1579     Symbol *ret = symtab->addSymbol(newSym);
1580     ret->referenced = true;
1581     return ret;
1582   }
1583 
1584   if (objSym.isCommon())
1585     return symtab->addSymbol(
1586         CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
1587                      objSym.getCommonAlignment(), objSym.getCommonSize()});
1588 
1589   Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
1590   if (canOmitFromDynSym)
1591     newSym.exportDynamic = false;
1592   return symtab->addSymbol(newSym);
1593 }
1594 
1595 template <class ELFT> void BitcodeFile::parse() {
1596   std::vector<bool> keptComdats;
1597   for (StringRef s : obj->getComdatTable())
1598     keptComdats.push_back(
1599         symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
1600 
1601   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1602     symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
1603 
1604   for (auto l : obj->getDependentLibraries())
1605     addDependentLibrary(l, this);
1606 }
1607 
1608 void BinaryFile::parse() {
1609   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1610   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1611                                      8, data, ".data");
1612   sections.push_back(section);
1613 
1614   // For each input file foo that is embedded to a result as a binary
1615   // blob, we define _binary_foo_{start,end,size} symbols, so that
1616   // user programs can access blobs by name. Non-alphanumeric
1617   // characters in a filename are replaced with underscore.
1618   std::string s = "_binary_" + mb.getBufferIdentifier().str();
1619   for (size_t i = 0; i < s.size(); ++i)
1620     if (!isAlnum(s[i]))
1621       s[i] = '_';
1622 
1623   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
1624                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
1625   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
1626                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
1627   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
1628                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
1629 }
1630 
1631 InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
1632                                  uint64_t offsetInArchive) {
1633   if (isBitcode(mb))
1634     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1635 
1636   switch (getELFKind(mb, archiveName)) {
1637   case ELF32LEKind:
1638     return make<ObjFile<ELF32LE>>(mb, archiveName);
1639   case ELF32BEKind:
1640     return make<ObjFile<ELF32BE>>(mb, archiveName);
1641   case ELF64LEKind:
1642     return make<ObjFile<ELF64LE>>(mb, archiveName);
1643   case ELF64BEKind:
1644     return make<ObjFile<ELF64BE>>(mb, archiveName);
1645   default:
1646     llvm_unreachable("getELFKind");
1647   }
1648 }
1649 
1650 void LazyObjFile::fetch() {
1651   if (fetched)
1652     return;
1653   fetched = true;
1654 
1655   InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
1656   file->groupId = groupId;
1657 
1658   // Copy symbol vector so that the new InputFile doesn't have to
1659   // insert the same defined symbols to the symbol table again.
1660   file->symbols = std::move(symbols);
1661 
1662   parseFile(file);
1663 }
1664 
1665 template <class ELFT> void LazyObjFile::parse() {
1666   using Elf_Sym = typename ELFT::Sym;
1667 
1668   // A lazy object file wraps either a bitcode file or an ELF file.
1669   if (isBitcode(this->mb)) {
1670     std::unique_ptr<lto::InputFile> obj =
1671         CHECK(lto::InputFile::create(this->mb), this);
1672     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
1673       if (sym.isUndefined())
1674         continue;
1675       symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
1676     }
1677     return;
1678   }
1679 
1680   if (getELFKind(this->mb, archiveName) != config->ekind) {
1681     error("incompatible file: " + this->mb.getBufferIdentifier());
1682     return;
1683   }
1684 
1685   // Find a symbol table.
1686   ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
1687   ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
1688 
1689   for (const typename ELFT::Shdr &sec : sections) {
1690     if (sec.sh_type != SHT_SYMTAB)
1691       continue;
1692 
1693     // A symbol table is found.
1694     ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
1695     uint32_t firstGlobal = sec.sh_info;
1696     StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
1697     this->symbols.resize(eSyms.size());
1698 
1699     // Get existing symbols or insert placeholder symbols.
1700     for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1701       if (eSyms[i].st_shndx != SHN_UNDEF)
1702         this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
1703 
1704     // Replace existing symbols with LazyObject symbols.
1705     //
1706     // resolve() may trigger this->fetch() if an existing symbol is an
1707     // undefined symbol. If that happens, this LazyObjFile has served
1708     // its purpose, and we can exit from the loop early.
1709     for (Symbol *sym : this->symbols) {
1710       if (!sym)
1711         continue;
1712       sym->resolve(LazyObject{*this, sym->getName()});
1713 
1714       // If fetched, stop iterating because this->symbols has been transferred
1715       // to the instantiated ObjFile.
1716       if (fetched)
1717         return;
1718     }
1719     return;
1720   }
1721 }
1722 
1723 std::string elf::replaceThinLTOSuffix(StringRef path) {
1724   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1725   StringRef repl = config->thinLTOObjectSuffixReplace.second;
1726 
1727   if (path.consume_back(suffix))
1728     return (path + repl).str();
1729   return std::string(path);
1730 }
1731 
1732 template void BitcodeFile::parse<ELF32LE>();
1733 template void BitcodeFile::parse<ELF32BE>();
1734 template void BitcodeFile::parse<ELF64LE>();
1735 template void BitcodeFile::parse<ELF64BE>();
1736 
1737 template void LazyObjFile::parse<ELF32LE>();
1738 template void LazyObjFile::parse<ELF32BE>();
1739 template void LazyObjFile::parse<ELF64LE>();
1740 template void LazyObjFile::parse<ELF64BE>();
1741 
1742 template class elf::ObjFile<ELF32LE>;
1743 template class elf::ObjFile<ELF32BE>;
1744 template class elf::ObjFile<ELF64LE>;
1745 template class elf::ObjFile<ELF64BE>;
1746 
1747 template void SharedFile::parse<ELF32LE>();
1748 template void SharedFile::parse<ELF32BE>();
1749 template void SharedFile::parse<ELF64LE>();
1750 template void SharedFile::parse<ELF64BE>();
1751