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