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