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