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