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