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