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