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