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