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(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     if (!(sec.sh_flags & SHF_LINK_ORDER))
661       continue;
662 
663     // .ARM.exidx sections have a reverse dependency on the InputSection they
664     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
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     InputSection *isec = cast<InputSection>(this->sections[i]);
672     linkSec->dependentSections.push_back(isec);
673     if (!isa<InputSection>(linkSec))
674       error("a section " + isec->name +
675             " with SHF_LINK_ORDER should not refer a non-regular section: " +
676             toString(linkSec));
677   }
678 
679   for (ArrayRef<Elf_Word> entries : selectedGroups)
680     handleSectionGroup<ELFT>(this->sections, entries);
681 }
682 
683 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
684 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
685 // the input objects have been compiled.
686 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
687                              const InputFile *f) {
688   Optional<unsigned> attr =
689       attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
690   if (!attr.hasValue())
691     // If an ABI tag isn't present then it is implicitly given the value of 0
692     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
693     // including some in glibc that don't use FP args (and should have value 3)
694     // don't have the attribute so we do not consider an implicit value of 0
695     // as a clash.
696     return;
697 
698   unsigned vfpArgs = attr.getValue();
699   ARMVFPArgKind arg;
700   switch (vfpArgs) {
701   case ARMBuildAttrs::BaseAAPCS:
702     arg = ARMVFPArgKind::Base;
703     break;
704   case ARMBuildAttrs::HardFPAAPCS:
705     arg = ARMVFPArgKind::VFP;
706     break;
707   case ARMBuildAttrs::ToolChainFPPCS:
708     // Tool chain specific convention that conforms to neither AAPCS variant.
709     arg = ARMVFPArgKind::ToolChain;
710     break;
711   case ARMBuildAttrs::CompatibleFPAAPCS:
712     // Object compatible with all conventions.
713     return;
714   default:
715     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
716     return;
717   }
718   // Follow ld.bfd and error if there is a mix of calling conventions.
719   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
720     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
721   else
722     config->armVFPArgs = arg;
723 }
724 
725 // The ARM support in lld makes some use of instructions that are not available
726 // on all ARM architectures. Namely:
727 // - Use of BLX instruction for interworking between ARM and Thumb state.
728 // - Use of the extended Thumb branch encoding in relocation.
729 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
730 // The ARM Attributes section contains information about the architecture chosen
731 // at compile time. We follow the convention that if at least one input object
732 // is compiled with an architecture that supports these features then lld is
733 // permitted to use them.
734 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
735   Optional<unsigned> attr =
736       attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
737   if (!attr.hasValue())
738     return;
739   auto arch = attr.getValue();
740   switch (arch) {
741   case ARMBuildAttrs::Pre_v4:
742   case ARMBuildAttrs::v4:
743   case ARMBuildAttrs::v4T:
744     // Architectures prior to v5 do not support BLX instruction
745     break;
746   case ARMBuildAttrs::v5T:
747   case ARMBuildAttrs::v5TE:
748   case ARMBuildAttrs::v5TEJ:
749   case ARMBuildAttrs::v6:
750   case ARMBuildAttrs::v6KZ:
751   case ARMBuildAttrs::v6K:
752     config->armHasBlx = true;
753     // Architectures used in pre-Cortex processors do not support
754     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
755     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
756     break;
757   default:
758     // All other Architectures have BLX and extended branch encoding
759     config->armHasBlx = true;
760     config->armJ1J2BranchEncoding = true;
761     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
762       // All Architectures used in Cortex processors with the exception
763       // of v6-M and v6S-M have the MOVT and MOVW instructions.
764       config->armHasMovtMovw = true;
765     break;
766   }
767 }
768 
769 // If a source file is compiled with x86 hardware-assisted call flow control
770 // enabled, the generated object file contains feature flags indicating that
771 // fact. This function reads the feature flags and returns it.
772 //
773 // Essentially we want to read a single 32-bit value in this function, but this
774 // function is rather complicated because the value is buried deep inside a
775 // .note.gnu.property section.
776 //
777 // The section consists of one or more NOTE records. Each NOTE record consists
778 // of zero or more type-length-value fields. We want to find a field of a
779 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
780 // the ABI is unnecessarily complicated.
781 template <class ELFT>
782 static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
783   using Elf_Nhdr = typename ELFT::Nhdr;
784   using Elf_Note = typename ELFT::Note;
785 
786   uint32_t featuresSet = 0;
787   while (!data.empty()) {
788     // Read one NOTE record.
789     if (data.size() < sizeof(Elf_Nhdr))
790       fatal(toString(obj) + ": .note.gnu.property: section too short");
791 
792     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
793     if (data.size() < nhdr->getSize())
794       fatal(toString(obj) + ": .note.gnu.property: section too short");
795 
796     Elf_Note note(*nhdr);
797     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
798       data = data.slice(nhdr->getSize());
799       continue;
800     }
801 
802     uint32_t featureAndType = config->emachine == EM_AARCH64
803                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
804                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
805 
806     // Read a body of a NOTE record, which consists of type-length-value fields.
807     ArrayRef<uint8_t> desc = note.getDesc();
808     while (!desc.empty()) {
809       if (desc.size() < 8)
810         fatal(toString(obj) + ": .note.gnu.property: section too short");
811 
812       uint32_t type = read32le(desc.data());
813       uint32_t size = read32le(desc.data() + 4);
814 
815       if (type == featureAndType) {
816         // We found a FEATURE_1_AND field. There may be more than one of these
817         // in a .note.gnu.property section, for a relocatable object we
818         // accumulate the bits set.
819         featuresSet |= read32le(desc.data() + 8);
820       }
821 
822       // On 64-bit, a payload may be followed by a 4-byte padding to make its
823       // size a multiple of 8.
824       if (ELFT::Is64Bits)
825         size = alignTo(size, 8);
826 
827       desc = desc.slice(size + 8); // +8 for Type and Size
828     }
829 
830     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
831     data = data.slice(nhdr->getSize());
832   }
833 
834   return featuresSet;
835 }
836 
837 template <class ELFT>
838 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
839   uint32_t idx = sec.sh_info;
840   if (idx >= this->sections.size())
841     fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
842   InputSectionBase *target = this->sections[idx];
843 
844   // Strictly speaking, a relocation section must be included in the
845   // group of the section it relocates. However, LLVM 3.3 and earlier
846   // would fail to do so, so we gracefully handle that case.
847   if (target == &InputSection::discarded)
848     return nullptr;
849 
850   if (!target)
851     fatal(toString(this) + ": unsupported relocation reference");
852   return target;
853 }
854 
855 // Create a regular InputSection class that has the same contents
856 // as a given section.
857 static InputSection *toRegularSection(MergeInputSection *sec) {
858   return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
859                             sec->data(), sec->name);
860 }
861 
862 template <class ELFT>
863 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
864   StringRef name = getSectionName(sec);
865 
866   switch (sec.sh_type) {
867   case SHT_ARM_ATTRIBUTES: {
868     if (config->emachine != EM_ARM)
869       break;
870     ARMAttributeParser attributes;
871     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
872     if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
873                                                  ? support::little
874                                                  : support::big)) {
875       auto *isec = make<InputSection>(*this, sec, name);
876       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
877       break;
878     }
879     updateSupportedARMFeatures(attributes);
880     updateARMVFPArgs(attributes, this);
881 
882     // FIXME: Retain the first attribute section we see. The eglibc ARM
883     // dynamic loaders require the presence of an attribute section for dlopen
884     // to work. In a full implementation we would merge all attribute sections.
885     if (in.armAttributes == nullptr) {
886       in.armAttributes = make<InputSection>(*this, sec, name);
887       return in.armAttributes;
888     }
889     return &InputSection::discarded;
890   }
891   case SHT_LLVM_DEPENDENT_LIBRARIES: {
892     if (config->relocatable)
893       break;
894     ArrayRef<char> data =
895         CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
896     if (!data.empty() && data.back() != '\0') {
897       error(toString(this) +
898             ": corrupted dependent libraries section (unterminated string): " +
899             name);
900       return &InputSection::discarded;
901     }
902     for (const char *d = data.begin(), *e = data.end(); d < e;) {
903       StringRef s(d);
904       addDependentLibrary(s, this);
905       d += s.size() + 1;
906     }
907     return &InputSection::discarded;
908   }
909   case SHT_RELA:
910   case SHT_REL: {
911     // Find a relocation target section and associate this section with that.
912     // Target may have been discarded if it is in a different section group
913     // and the group is discarded, even though it's a violation of the
914     // spec. We handle that situation gracefully by discarding dangling
915     // relocation sections.
916     InputSectionBase *target = getRelocTarget(sec);
917     if (!target)
918       return nullptr;
919 
920     // ELF spec allows mergeable sections with relocations, but they are
921     // rare, and it is in practice hard to merge such sections by contents,
922     // because applying relocations at end of linking changes section
923     // contents. So, we simply handle such sections as non-mergeable ones.
924     // Degrading like this is acceptable because section merging is optional.
925     if (auto *ms = dyn_cast<MergeInputSection>(target)) {
926       target = toRegularSection(ms);
927       this->sections[sec.sh_info] = target;
928     }
929 
930     if (target->firstRelocation)
931       fatal(toString(this) +
932             ": multiple relocation sections to one section are not supported");
933 
934     if (sec.sh_type == SHT_RELA) {
935       ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
936       target->firstRelocation = rels.begin();
937       target->numRelocations = rels.size();
938       target->areRelocsRela = true;
939     } else {
940       ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
941       target->firstRelocation = rels.begin();
942       target->numRelocations = rels.size();
943       target->areRelocsRela = false;
944     }
945     assert(isUInt<31>(target->numRelocations));
946 
947     // Relocation sections are usually removed from the output, so return
948     // `nullptr` for the normal case. However, if -r or --emit-relocs is
949     // specified, we need to copy them to the output. (Some post link analysis
950     // tools specify --emit-relocs to obtain the information.)
951     if (!config->relocatable && !config->emitRelocs)
952       return nullptr;
953     InputSection *relocSec = make<InputSection>(*this, sec, name);
954     // If the relocated section is discarded (due to /DISCARD/ or
955     // --gc-sections), the relocation section should be discarded as well.
956     target->dependentSections.push_back(relocSec);
957     return relocSec;
958   }
959   }
960 
961   // The GNU linker uses .note.GNU-stack section as a marker indicating
962   // that the code in the object file does not expect that the stack is
963   // executable (in terms of NX bit). If all input files have the marker,
964   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
965   // make the stack non-executable. Most object files have this section as
966   // of 2017.
967   //
968   // But making the stack non-executable is a norm today for security
969   // reasons. Failure to do so may result in a serious security issue.
970   // Therefore, we make LLD always add PT_GNU_STACK unless it is
971   // explicitly told to do otherwise (by -z execstack). Because the stack
972   // executable-ness is controlled solely by command line options,
973   // .note.GNU-stack sections are simply ignored.
974   if (name == ".note.GNU-stack")
975     return &InputSection::discarded;
976 
977   // Object files that use processor features such as Intel Control-Flow
978   // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
979   // .note.gnu.property section containing a bitfield of feature bits like the
980   // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
981   //
982   // Since we merge bitmaps from multiple object files to create a new
983   // .note.gnu.property containing a single AND'ed bitmap, we discard an input
984   // file's .note.gnu.property section.
985   if (name == ".note.gnu.property") {
986     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
987     this->andFeatures = readAndFeatures(this, contents);
988     return &InputSection::discarded;
989   }
990 
991   // Split stacks is a feature to support a discontiguous stack,
992   // commonly used in the programming language Go. For the details,
993   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
994   // for split stack will include a .note.GNU-split-stack section.
995   if (name == ".note.GNU-split-stack") {
996     if (config->relocatable) {
997       error("cannot mix split-stack and non-split-stack in a relocatable link");
998       return &InputSection::discarded;
999     }
1000     this->splitStack = true;
1001     return &InputSection::discarded;
1002   }
1003 
1004   // An object file cmpiled for split stack, but where some of the
1005   // functions were compiled with the no_split_stack_attribute will
1006   // include a .note.GNU-no-split-stack section.
1007   if (name == ".note.GNU-no-split-stack") {
1008     this->someNoSplitStack = true;
1009     return &InputSection::discarded;
1010   }
1011 
1012   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1013   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1014   // sections. Drop those sections to avoid duplicate symbol errors.
1015   // FIXME: This is glibc PR20543, we should remove this hack once that has been
1016   // fixed for a while.
1017   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1018       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1019     return &InputSection::discarded;
1020 
1021   // If we are creating a new .build-id section, strip existing .build-id
1022   // sections so that the output won't have more than one .build-id.
1023   // This is not usually a problem because input object files normally don't
1024   // have .build-id sections, but you can create such files by
1025   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1026   if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
1027     return &InputSection::discarded;
1028 
1029   // The linker merges EH (exception handling) frames and creates a
1030   // .eh_frame_hdr section for runtime. So we handle them with a special
1031   // class. For relocatable outputs, they are just passed through.
1032   if (name == ".eh_frame" && !config->relocatable)
1033     return make<EhInputSection>(*this, sec, name);
1034 
1035   if (shouldMerge(sec, name))
1036     return make<MergeInputSection>(*this, sec, name);
1037   return make<InputSection>(*this, sec, name);
1038 }
1039 
1040 template <class ELFT>
1041 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1042   return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1043 }
1044 
1045 // Initialize this->Symbols. this->Symbols is a parallel array as
1046 // its corresponding ELF symbol table.
1047 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1048   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1049   this->symbols.resize(eSyms.size());
1050 
1051   // Fill in InputFile::symbols. Some entries have been initialized
1052   // because of LazyObjFile.
1053   for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
1054     if (this->symbols[i])
1055       continue;
1056     const Elf_Sym &eSym = eSyms[i];
1057     uint32_t secIdx = getSectionIndex(eSym);
1058     if (secIdx >= this->sections.size())
1059       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1060     if (eSym.getBinding() != STB_LOCAL) {
1061       if (i < firstGlobal)
1062         error(toString(this) + ": non-local symbol (" + Twine(i) +
1063               ") found at index < .symtab's sh_info (" + Twine(firstGlobal) +
1064               ")");
1065       this->symbols[i] =
1066           symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1067       continue;
1068     }
1069 
1070     // Handle local symbols. Local symbols are not added to the symbol
1071     // table because they are not visible from other object files. We
1072     // allocate symbol instances and add their pointers to symbols.
1073     if (i >= firstGlobal)
1074       errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) +
1075                   ") found at index >= .symtab's sh_info (" +
1076                   Twine(firstGlobal) + ")");
1077 
1078     InputSectionBase *sec = this->sections[secIdx];
1079     uint8_t type = eSym.getType();
1080     if (type == STT_FILE)
1081       sourceFile = CHECK(eSym.getName(this->stringTable), this);
1082     if (this->stringTable.size() <= eSym.st_name)
1083       fatal(toString(this) + ": invalid symbol name offset");
1084     StringRefZ name = this->stringTable.data() + eSym.st_name;
1085 
1086     if (eSym.st_shndx == SHN_UNDEF)
1087       this->symbols[i] =
1088           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type);
1089     else if (sec == &InputSection::discarded)
1090       this->symbols[i] =
1091           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type,
1092                           /*discardedSecIdx=*/secIdx);
1093     else
1094       this->symbols[i] = make<Defined>(this, name, STB_LOCAL, eSym.st_other,
1095                                        type, eSym.st_value, eSym.st_size, sec);
1096   }
1097 
1098   // Symbol resolution of non-local symbols.
1099   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1100     const Elf_Sym &eSym = eSyms[i];
1101     uint8_t binding = eSym.getBinding();
1102     if (binding == STB_LOCAL)
1103       continue; // Errored above.
1104 
1105     uint32_t secIdx = getSectionIndex(eSym);
1106     InputSectionBase *sec = this->sections[secIdx];
1107     uint8_t stOther = eSym.st_other;
1108     uint8_t type = eSym.getType();
1109     uint64_t value = eSym.st_value;
1110     uint64_t size = eSym.st_size;
1111     StringRefZ name = this->stringTable.data() + eSym.st_name;
1112 
1113     // Handle global undefined symbols.
1114     if (eSym.st_shndx == SHN_UNDEF) {
1115       this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1116       this->symbols[i]->referenced = true;
1117       continue;
1118     }
1119 
1120     // Handle global common symbols.
1121     if (eSym.st_shndx == SHN_COMMON) {
1122       if (value == 0 || value >= UINT32_MAX)
1123         fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1124               "' has invalid alignment: " + Twine(value));
1125       this->symbols[i]->resolve(
1126           CommonSymbol{this, name, binding, stOther, type, value, size});
1127       continue;
1128     }
1129 
1130     // If a defined symbol is in a discarded section, handle it as if it
1131     // were an undefined symbol. Such symbol doesn't comply with the
1132     // standard, but in practice, a .eh_frame often directly refer
1133     // COMDAT member sections, and if a comdat group is discarded, some
1134     // defined symbol in a .eh_frame becomes dangling symbols.
1135     if (sec == &InputSection::discarded) {
1136       Undefined und{this, name, binding, stOther, type, secIdx};
1137       Symbol *sym = this->symbols[i];
1138       // !ArchiveFile::parsed or LazyObjFile::fetched means that the file
1139       // containing this object has not finished processing, i.e. this symbol is
1140       // a result of a lazy symbol fetch. We should demote the lazy symbol to an
1141       // Undefined so that any relocations outside of the group to it will
1142       // trigger a discarded section error.
1143       if ((sym->symbolKind == Symbol::LazyArchiveKind &&
1144            !cast<ArchiveFile>(sym->file)->parsed) ||
1145           (sym->symbolKind == Symbol::LazyObjectKind &&
1146            cast<LazyObjFile>(sym->file)->fetched))
1147         sym->replace(und);
1148       else
1149         sym->resolve(und);
1150       continue;
1151     }
1152 
1153     // Handle global defined symbols.
1154     if (binding == STB_GLOBAL || binding == STB_WEAK ||
1155         binding == STB_GNU_UNIQUE) {
1156       this->symbols[i]->resolve(
1157           Defined{this, name, binding, stOther, type, value, size, sec});
1158       continue;
1159     }
1160 
1161     fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1162   }
1163 }
1164 
1165 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
1166     : InputFile(ArchiveKind, file->getMemoryBufferRef()),
1167       file(std::move(file)) {}
1168 
1169 void ArchiveFile::parse() {
1170   for (const Archive::Symbol &sym : file->symbols())
1171     symtab->addSymbol(LazyArchive{*this, sym});
1172 
1173   // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this
1174   // archive has been processed.
1175   parsed = true;
1176 }
1177 
1178 // Returns a buffer pointing to a member file containing a given symbol.
1179 void ArchiveFile::fetch(const Archive::Symbol &sym) {
1180   Archive::Child c =
1181       CHECK(sym.getMember(), toString(this) +
1182                                  ": could not get the member for symbol " +
1183                                  toELFString(sym));
1184 
1185   if (!seen.insert(c.getChildOffset()).second)
1186     return;
1187 
1188   MemoryBufferRef mb =
1189       CHECK(c.getMemoryBufferRef(),
1190             toString(this) +
1191                 ": could not get the buffer for the member defining symbol " +
1192                 toELFString(sym));
1193 
1194   if (tar && c.getParent()->isThin())
1195     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
1196 
1197   InputFile *file = createObjectFile(mb, getName(), c.getChildOffset());
1198   file->groupId = groupId;
1199   parseFile(file);
1200 }
1201 
1202 size_t ArchiveFile::getMemberCount() const {
1203   size_t count = 0;
1204   Error err = Error::success();
1205   for (const Archive::Child &c : file->children(err)) {
1206     (void)c;
1207     ++count;
1208   }
1209   // This function is used by --print-archive-stats=, where an error does not
1210   // really matter.
1211   consumeError(std::move(err));
1212   return count;
1213 }
1214 
1215 unsigned SharedFile::vernauxNum;
1216 
1217 // Parse the version definitions in the object file if present, and return a
1218 // vector whose nth element contains a pointer to the Elf_Verdef for version
1219 // identifier n. Version identifiers that are not definitions map to nullptr.
1220 template <typename ELFT>
1221 static std::vector<const void *> parseVerdefs(const uint8_t *base,
1222                                               const typename ELFT::Shdr *sec) {
1223   if (!sec)
1224     return {};
1225 
1226   // We cannot determine the largest verdef identifier without inspecting
1227   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1228   // sequentially starting from 1, so we predict that the largest identifier
1229   // will be verdefCount.
1230   unsigned verdefCount = sec->sh_info;
1231   std::vector<const void *> verdefs(verdefCount + 1);
1232 
1233   // Build the Verdefs array by following the chain of Elf_Verdef objects
1234   // from the start of the .gnu.version_d section.
1235   const uint8_t *verdef = base + sec->sh_offset;
1236   for (unsigned i = 0; i != verdefCount; ++i) {
1237     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1238     verdef += curVerdef->vd_next;
1239     unsigned verdefIndex = curVerdef->vd_ndx;
1240     verdefs.resize(verdefIndex + 1);
1241     verdefs[verdefIndex] = curVerdef;
1242   }
1243   return verdefs;
1244 }
1245 
1246 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1247 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1248 // implement sophisticated error checking like in llvm-readobj because the value
1249 // of such diagnostics is low.
1250 template <typename ELFT>
1251 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1252                                                const typename ELFT::Shdr *sec) {
1253   if (!sec)
1254     return {};
1255   std::vector<uint32_t> verneeds;
1256   ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(sec), this);
1257   const uint8_t *verneedBuf = data.begin();
1258   for (unsigned i = 0; i != sec->sh_info; ++i) {
1259     if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
1260       fatal(toString(this) + " has an invalid Verneed");
1261     auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1262     const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1263     for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1264       if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
1265         fatal(toString(this) + " has an invalid Vernaux");
1266       auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1267       if (aux->vna_name >= this->stringTable.size())
1268         fatal(toString(this) + " has a Vernaux with an invalid vna_name");
1269       uint16_t version = aux->vna_other & VERSYM_VERSION;
1270       if (version >= verneeds.size())
1271         verneeds.resize(version + 1);
1272       verneeds[version] = aux->vna_name;
1273       vernauxBuf += aux->vna_next;
1274     }
1275     verneedBuf += vn->vn_next;
1276   }
1277   return verneeds;
1278 }
1279 
1280 // We do not usually care about alignments of data in shared object
1281 // files because the loader takes care of it. However, if we promote a
1282 // DSO symbol to point to .bss due to copy relocation, we need to keep
1283 // the original alignment requirements. We infer it in this function.
1284 template <typename ELFT>
1285 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1286                              const typename ELFT::Sym &sym) {
1287   uint64_t ret = UINT64_MAX;
1288   if (sym.st_value)
1289     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1290   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1291     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1292   return (ret > UINT32_MAX) ? 0 : ret;
1293 }
1294 
1295 // Fully parse the shared object file.
1296 //
1297 // This function parses symbol versions. If a DSO has version information,
1298 // the file has a ".gnu.version_d" section which contains symbol version
1299 // definitions. Each symbol is associated to one version through a table in
1300 // ".gnu.version" section. That table is a parallel array for the symbol
1301 // table, and each table entry contains an index in ".gnu.version_d".
1302 //
1303 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1304 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1305 // ".gnu.version_d".
1306 //
1307 // The file format for symbol versioning is perhaps a bit more complicated
1308 // than necessary, but you can easily understand the code if you wrap your
1309 // head around the data structure described above.
1310 template <class ELFT> void SharedFile::parse() {
1311   using Elf_Dyn = typename ELFT::Dyn;
1312   using Elf_Shdr = typename ELFT::Shdr;
1313   using Elf_Sym = typename ELFT::Sym;
1314   using Elf_Verdef = typename ELFT::Verdef;
1315   using Elf_Versym = typename ELFT::Versym;
1316 
1317   ArrayRef<Elf_Dyn> dynamicTags;
1318   const ELFFile<ELFT> obj = this->getObj<ELFT>();
1319   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1320 
1321   const Elf_Shdr *versymSec = nullptr;
1322   const Elf_Shdr *verdefSec = nullptr;
1323   const Elf_Shdr *verneedSec = nullptr;
1324 
1325   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1326   for (const Elf_Shdr &sec : sections) {
1327     switch (sec.sh_type) {
1328     default:
1329       continue;
1330     case SHT_DYNAMIC:
1331       dynamicTags =
1332           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1333       break;
1334     case SHT_GNU_versym:
1335       versymSec = &sec;
1336       break;
1337     case SHT_GNU_verdef:
1338       verdefSec = &sec;
1339       break;
1340     case SHT_GNU_verneed:
1341       verneedSec = &sec;
1342       break;
1343     }
1344   }
1345 
1346   if (versymSec && numELFSyms == 0) {
1347     error("SHT_GNU_versym should be associated with symbol table");
1348     return;
1349   }
1350 
1351   // Search for a DT_SONAME tag to initialize this->soName.
1352   for (const Elf_Dyn &dyn : dynamicTags) {
1353     if (dyn.d_tag == DT_NEEDED) {
1354       uint64_t val = dyn.getVal();
1355       if (val >= this->stringTable.size())
1356         fatal(toString(this) + ": invalid DT_NEEDED entry");
1357       dtNeeded.push_back(this->stringTable.data() + val);
1358     } else if (dyn.d_tag == DT_SONAME) {
1359       uint64_t val = dyn.getVal();
1360       if (val >= this->stringTable.size())
1361         fatal(toString(this) + ": invalid DT_SONAME entry");
1362       soName = this->stringTable.data() + val;
1363     }
1364   }
1365 
1366   // DSOs are uniquified not by filename but by soname.
1367   DenseMap<StringRef, SharedFile *>::iterator it;
1368   bool wasInserted;
1369   std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1370 
1371   // If a DSO appears more than once on the command line with and without
1372   // --as-needed, --no-as-needed takes precedence over --as-needed because a
1373   // user can add an extra DSO with --no-as-needed to force it to be added to
1374   // the dependency list.
1375   it->second->isNeeded |= isNeeded;
1376   if (!wasInserted)
1377     return;
1378 
1379   sharedFiles.push_back(this);
1380 
1381   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1382   std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1383 
1384   // Parse ".gnu.version" section which is a parallel array for the symbol
1385   // table. If a given file doesn't have a ".gnu.version" section, we use
1386   // VER_NDX_GLOBAL.
1387   size_t size = numELFSyms - firstGlobal;
1388   std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1389   if (versymSec) {
1390     ArrayRef<Elf_Versym> versym =
1391         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1392               this)
1393             .slice(firstGlobal);
1394     for (size_t i = 0; i < size; ++i)
1395       versyms[i] = versym[i].vs_index;
1396   }
1397 
1398   // System libraries can have a lot of symbols with versions. Using a
1399   // fixed buffer for computing the versions name (foo@ver) can save a
1400   // lot of allocations.
1401   SmallString<0> versionedNameBuffer;
1402 
1403   // Add symbols to the symbol table.
1404   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1405   for (size_t i = 0; i < syms.size(); ++i) {
1406     const Elf_Sym &sym = syms[i];
1407 
1408     // ELF spec requires that all local symbols precede weak or global
1409     // symbols in each symbol table, and the index of first non-local symbol
1410     // is stored to sh_info. If a local symbol appears after some non-local
1411     // symbol, that's a violation of the spec.
1412     StringRef name = CHECK(sym.getName(this->stringTable), this);
1413     if (sym.getBinding() == STB_LOCAL) {
1414       warn("found local symbol '" + name +
1415            "' in global part of symbol table in file " + toString(this));
1416       continue;
1417     }
1418 
1419     uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
1420     if (sym.isUndefined()) {
1421       // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1422       // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1423       if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
1424         if (idx >= verneeds.size()) {
1425           error("corrupt input file: version need index " + Twine(idx) +
1426                 " for symbol " + name + " is out of bounds\n>>> defined in " +
1427                 toString(this));
1428           continue;
1429         }
1430         StringRef verName = this->stringTable.data() + verneeds[idx];
1431         versionedNameBuffer.clear();
1432         name =
1433             saver.save((name + "@" + verName).toStringRef(versionedNameBuffer));
1434       }
1435       Symbol *s = symtab->addSymbol(
1436           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1437       s->exportDynamic = true;
1438       continue;
1439     }
1440 
1441     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1442     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1443     // workaround for this bug.
1444     if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
1445         name == "_gp_disp")
1446       continue;
1447 
1448     uint32_t alignment = getAlignment<ELFT>(sections, sym);
1449     if (!(versyms[i] & VERSYM_HIDDEN)) {
1450       symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1451                                      sym.st_other, sym.getType(), sym.st_value,
1452                                      sym.st_size, alignment, idx});
1453     }
1454 
1455     // Also add the symbol with the versioned name to handle undefined symbols
1456     // with explicit versions.
1457     if (idx == VER_NDX_GLOBAL)
1458       continue;
1459 
1460     if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1461       error("corrupt input file: version definition index " + Twine(idx) +
1462             " for symbol " + name + " is out of bounds\n>>> defined in " +
1463             toString(this));
1464       continue;
1465     }
1466 
1467     StringRef verName =
1468         this->stringTable.data() +
1469         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1470     versionedNameBuffer.clear();
1471     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1472     symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1473                                    sym.st_other, sym.getType(), sym.st_value,
1474                                    sym.st_size, alignment, idx});
1475   }
1476 }
1477 
1478 static ELFKind getBitcodeELFKind(const Triple &t) {
1479   if (t.isLittleEndian())
1480     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1481   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1482 }
1483 
1484 static uint8_t getBitcodeMachineKind(StringRef path, const Triple &t) {
1485   switch (t.getArch()) {
1486   case Triple::aarch64:
1487     return EM_AARCH64;
1488   case Triple::amdgcn:
1489   case Triple::r600:
1490     return EM_AMDGPU;
1491   case Triple::arm:
1492   case Triple::thumb:
1493     return EM_ARM;
1494   case Triple::avr:
1495     return EM_AVR;
1496   case Triple::mips:
1497   case Triple::mipsel:
1498   case Triple::mips64:
1499   case Triple::mips64el:
1500     return EM_MIPS;
1501   case Triple::msp430:
1502     return EM_MSP430;
1503   case Triple::ppc:
1504     return EM_PPC;
1505   case Triple::ppc64:
1506   case Triple::ppc64le:
1507     return EM_PPC64;
1508   case Triple::riscv32:
1509   case Triple::riscv64:
1510     return EM_RISCV;
1511   case Triple::x86:
1512     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1513   case Triple::x86_64:
1514     return EM_X86_64;
1515   default:
1516     error(path + ": could not infer e_machine from bitcode target triple " +
1517           t.str());
1518     return EM_NONE;
1519   }
1520 }
1521 
1522 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1523                          uint64_t offsetInArchive)
1524     : InputFile(BitcodeKind, mb) {
1525   this->archiveName = std::string(archiveName);
1526 
1527   std::string path = mb.getBufferIdentifier().str();
1528   if (config->thinLTOIndexOnly)
1529     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
1530 
1531   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1532   // name. If two archives define two members with the same name, this
1533   // causes a collision which result in only one of the objects being taken
1534   // into consideration at LTO time (which very likely causes undefined
1535   // symbols later in the link stage). So we append file offset to make
1536   // filename unique.
1537   StringRef name =
1538       archiveName.empty()
1539           ? saver.save(path)
1540           : saver.save(archiveName + "(" + path::filename(path) + " at " +
1541                        utostr(offsetInArchive) + ")");
1542   MemoryBufferRef mbref(mb.getBuffer(), name);
1543 
1544   obj = CHECK(lto::InputFile::create(mbref), this);
1545 
1546   Triple t(obj->getTargetTriple());
1547   ekind = getBitcodeELFKind(t);
1548   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1549 }
1550 
1551 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1552   switch (gvVisibility) {
1553   case GlobalValue::DefaultVisibility:
1554     return STV_DEFAULT;
1555   case GlobalValue::HiddenVisibility:
1556     return STV_HIDDEN;
1557   case GlobalValue::ProtectedVisibility:
1558     return STV_PROTECTED;
1559   }
1560   llvm_unreachable("unknown visibility");
1561 }
1562 
1563 template <class ELFT>
1564 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
1565                                    const lto::InputFile::Symbol &objSym,
1566                                    BitcodeFile &f) {
1567   StringRef name = saver.save(objSym.getName());
1568   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1569   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1570   uint8_t visibility = mapVisibility(objSym.getVisibility());
1571   bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
1572 
1573   int c = objSym.getComdatIndex();
1574   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1575     Undefined newSym(&f, name, binding, visibility, type);
1576     if (canOmitFromDynSym)
1577       newSym.exportDynamic = false;
1578     Symbol *ret = symtab->addSymbol(newSym);
1579     ret->referenced = true;
1580     return ret;
1581   }
1582 
1583   if (objSym.isCommon())
1584     return symtab->addSymbol(
1585         CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
1586                      objSym.getCommonAlignment(), objSym.getCommonSize()});
1587 
1588   Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
1589   if (canOmitFromDynSym)
1590     newSym.exportDynamic = false;
1591   return symtab->addSymbol(newSym);
1592 }
1593 
1594 template <class ELFT> void BitcodeFile::parse() {
1595   std::vector<bool> keptComdats;
1596   for (StringRef s : obj->getComdatTable())
1597     keptComdats.push_back(
1598         symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
1599 
1600   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1601     symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
1602 
1603   for (auto l : obj->getDependentLibraries())
1604     addDependentLibrary(l, this);
1605 }
1606 
1607 void BinaryFile::parse() {
1608   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1609   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1610                                      8, data, ".data");
1611   sections.push_back(section);
1612 
1613   // For each input file foo that is embedded to a result as a binary
1614   // blob, we define _binary_foo_{start,end,size} symbols, so that
1615   // user programs can access blobs by name. Non-alphanumeric
1616   // characters in a filename are replaced with underscore.
1617   std::string s = "_binary_" + mb.getBufferIdentifier().str();
1618   for (size_t i = 0; i < s.size(); ++i)
1619     if (!isAlnum(s[i]))
1620       s[i] = '_';
1621 
1622   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
1623                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
1624   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
1625                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
1626   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
1627                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
1628 }
1629 
1630 InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
1631                                  uint64_t offsetInArchive) {
1632   if (isBitcode(mb))
1633     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1634 
1635   switch (getELFKind(mb, archiveName)) {
1636   case ELF32LEKind:
1637     return make<ObjFile<ELF32LE>>(mb, archiveName);
1638   case ELF32BEKind:
1639     return make<ObjFile<ELF32BE>>(mb, archiveName);
1640   case ELF64LEKind:
1641     return make<ObjFile<ELF64LE>>(mb, archiveName);
1642   case ELF64BEKind:
1643     return make<ObjFile<ELF64BE>>(mb, archiveName);
1644   default:
1645     llvm_unreachable("getELFKind");
1646   }
1647 }
1648 
1649 void LazyObjFile::fetch() {
1650   if (fetched)
1651     return;
1652   fetched = true;
1653 
1654   InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
1655   file->groupId = groupId;
1656 
1657   // Copy symbol vector so that the new InputFile doesn't have to
1658   // insert the same defined symbols to the symbol table again.
1659   file->symbols = std::move(symbols);
1660 
1661   parseFile(file);
1662 }
1663 
1664 template <class ELFT> void LazyObjFile::parse() {
1665   using Elf_Sym = typename ELFT::Sym;
1666 
1667   // A lazy object file wraps either a bitcode file or an ELF file.
1668   if (isBitcode(this->mb)) {
1669     std::unique_ptr<lto::InputFile> obj =
1670         CHECK(lto::InputFile::create(this->mb), this);
1671     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
1672       if (sym.isUndefined())
1673         continue;
1674       symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
1675     }
1676     return;
1677   }
1678 
1679   if (getELFKind(this->mb, archiveName) != config->ekind) {
1680     error("incompatible file: " + this->mb.getBufferIdentifier());
1681     return;
1682   }
1683 
1684   // Find a symbol table.
1685   ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
1686   ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
1687 
1688   for (const typename ELFT::Shdr &sec : sections) {
1689     if (sec.sh_type != SHT_SYMTAB)
1690       continue;
1691 
1692     // A symbol table is found.
1693     ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
1694     uint32_t firstGlobal = sec.sh_info;
1695     StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
1696     this->symbols.resize(eSyms.size());
1697 
1698     // Get existing symbols or insert placeholder symbols.
1699     for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1700       if (eSyms[i].st_shndx != SHN_UNDEF)
1701         this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
1702 
1703     // Replace existing symbols with LazyObject symbols.
1704     //
1705     // resolve() may trigger this->fetch() if an existing symbol is an
1706     // undefined symbol. If that happens, this LazyObjFile has served
1707     // its purpose, and we can exit from the loop early.
1708     for (Symbol *sym : this->symbols) {
1709       if (!sym)
1710         continue;
1711       sym->resolve(LazyObject{*this, sym->getName()});
1712 
1713       // If fetched, stop iterating because this->symbols has been transferred
1714       // to the instantiated ObjFile.
1715       if (fetched)
1716         return;
1717     }
1718     return;
1719   }
1720 }
1721 
1722 std::string elf::replaceThinLTOSuffix(StringRef path) {
1723   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1724   StringRef repl = config->thinLTOObjectSuffixReplace.second;
1725 
1726   if (path.consume_back(suffix))
1727     return (path + repl).str();
1728   return std::string(path);
1729 }
1730 
1731 template void BitcodeFile::parse<ELF32LE>();
1732 template void BitcodeFile::parse<ELF32BE>();
1733 template void BitcodeFile::parse<ELF64LE>();
1734 template void BitcodeFile::parse<ELF64BE>();
1735 
1736 template void LazyObjFile::parse<ELF32LE>();
1737 template void LazyObjFile::parse<ELF32BE>();
1738 template void LazyObjFile::parse<ELF64LE>();
1739 template void LazyObjFile::parse<ELF64BE>();
1740 
1741 template class elf::ObjFile<ELF32LE>;
1742 template class elf::ObjFile<ELF32BE>;
1743 template class elf::ObjFile<ELF64LE>;
1744 template class elf::ObjFile<ELF64BE>;
1745 
1746 template void SharedFile::parse<ELF32LE>();
1747 template void SharedFile::parse<ELF32BE>();
1748 template void SharedFile::parse<ELF64LE>();
1749 template void SharedFile::parse<ELF64BE>();
1750