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