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