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