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