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