1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "InputFiles.h"
10 #include "Driver.h"
11 #include "InputSection.h"
12 #include "LinkerScript.h"
13 #include "SymbolTable.h"
14 #include "Symbols.h"
15 #include "SyntheticSections.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Memory.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/MC/StringTableBuilder.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Support/ARMAttributeParser.h"
27 #include "llvm/Support/ARMBuildAttributes.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/TarWriter.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace llvm;
34 using namespace llvm::ELF;
35 using namespace llvm::object;
36 using namespace llvm::sys;
37 using namespace llvm::sys::fs;
38 using namespace llvm::support::endian;
39 
40 using namespace lld;
41 using namespace lld::elf;
42 
43 bool InputFile::isInGroup;
44 uint32_t InputFile::nextGroupId;
45 std::vector<BinaryFile *> elf::binaryFiles;
46 std::vector<BitcodeFile *> elf::bitcodeFiles;
47 std::vector<LazyObjFile *> elf::lazyObjFiles;
48 std::vector<InputFile *> elf::objectFiles;
49 std::vector<SharedFile *> elf::sharedFiles;
50 
51 std::unique_ptr<TarWriter> elf::tar;
52 
53 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
54   unsigned char size;
55   unsigned char endian;
56   std::tie(size, endian) = getElfArchType(mb.getBuffer());
57 
58   auto report = [&](StringRef msg) {
59     StringRef filename = mb.getBufferIdentifier();
60     if (archiveName.empty())
61       fatal(filename + ": " + msg);
62     else
63       fatal(archiveName + "(" + filename + "): " + msg);
64   };
65 
66   if (!mb.getBuffer().startswith(ElfMagic))
67     report("not an ELF file");
68   if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
69     report("corrupted ELF file: invalid data encoding");
70   if (size != ELFCLASS32 && size != ELFCLASS64)
71     report("corrupted ELF file: invalid file class");
72 
73   size_t bufSize = mb.getBuffer().size();
74   if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
75       (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
76     report("corrupted ELF file: file is too short");
77 
78   if (size == ELFCLASS32)
79     return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
80   return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
81 }
82 
83 InputFile::InputFile(Kind k, MemoryBufferRef m)
84     : mb(m), groupId(nextGroupId), fileKind(k) {
85   // All files within the same --{start,end}-group get the same group ID.
86   // Otherwise, a new file will get a new group ID.
87   if (!isInGroup)
88     ++nextGroupId;
89 }
90 
91 Optional<MemoryBufferRef> elf::readFile(StringRef path) {
92   // The --chroot option changes our virtual root directory.
93   // This is useful when you are dealing with files created by --reproduce.
94   if (!config->chroot.empty() && path.startswith("/"))
95     path = saver.save(config->chroot + path);
96 
97   log(path);
98 
99   auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
100   if (auto ec = mbOrErr.getError()) {
101     error("cannot open " + path + ": " + ec.message());
102     return None;
103   }
104 
105   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
106   MemoryBufferRef mbref = mb->getMemBufferRef();
107   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
108 
109   if (tar)
110     tar->append(relativeToRoot(path), mbref.getBuffer());
111   return mbref;
112 }
113 
114 // All input object files must be for the same architecture
115 // (e.g. it does not make sense to link x86 object files with
116 // MIPS object files.) This function checks for that error.
117 static bool isCompatible(InputFile *file) {
118   if (!file->isElf() && !isa<BitcodeFile>(file))
119     return true;
120 
121   if (file->ekind == config->ekind && file->emachine == config->emachine) {
122     if (config->emachine != EM_MIPS)
123       return true;
124     if (isMipsN32Abi(file) == config->mipsN32Abi)
125       return true;
126   }
127 
128   if (!config->emulation.empty()) {
129     error(toString(file) + " is incompatible with " + config->emulation);
130     return false;
131   }
132 
133   InputFile *existing;
134   if (!objectFiles.empty())
135     existing = objectFiles[0];
136   else if (!sharedFiles.empty())
137     existing = sharedFiles[0];
138   else
139     existing = bitcodeFiles[0];
140 
141   error(toString(file) + " is incompatible with " + toString(existing));
142   return false;
143 }
144 
145 template <class ELFT> static void doParseFile(InputFile *file) {
146   if (!isCompatible(file))
147     return;
148 
149   // Binary file
150   if (auto *f = dyn_cast<BinaryFile>(file)) {
151     binaryFiles.push_back(f);
152     f->parse();
153     return;
154   }
155 
156   // .a file
157   if (auto *f = dyn_cast<ArchiveFile>(file)) {
158     f->parse();
159     return;
160   }
161 
162   // Lazy object file
163   if (auto *f = dyn_cast<LazyObjFile>(file)) {
164     lazyObjFiles.push_back(f);
165     f->parse<ELFT>();
166     return;
167   }
168 
169   if (config->trace)
170     message(toString(file));
171 
172   // .so file
173   if (auto *f = dyn_cast<SharedFile>(file)) {
174     f->parse<ELFT>();
175     return;
176   }
177 
178   // LLVM bitcode file
179   if (auto *f = dyn_cast<BitcodeFile>(file)) {
180     bitcodeFiles.push_back(f);
181     f->parse<ELFT>();
182     return;
183   }
184 
185   // Regular object file
186   objectFiles.push_back(file);
187   cast<ObjFile<ELFT>>(file)->parse();
188 }
189 
190 // Add symbols in File to the symbol table.
191 void elf::parseFile(InputFile *file) {
192   switch (config->ekind) {
193   case ELF32LEKind:
194     doParseFile<ELF32LE>(file);
195     return;
196   case ELF32BEKind:
197     doParseFile<ELF32BE>(file);
198     return;
199   case ELF64LEKind:
200     doParseFile<ELF64LE>(file);
201     return;
202   case ELF64BEKind:
203     doParseFile<ELF64BE>(file);
204     return;
205   default:
206     llvm_unreachable("unknown ELFT");
207   }
208 }
209 
210 // Concatenates arguments to construct a string representing an error location.
211 static std::string createFileLineMsg(StringRef path, unsigned line) {
212   std::string filename = path::filename(path);
213   std::string lineno = ":" + std::to_string(line);
214   if (filename == path)
215     return filename + lineno;
216   return filename + lineno + " (" + path.str() + lineno + ")";
217 }
218 
219 template <class ELFT>
220 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
221                                 InputSectionBase &sec, uint64_t offset) {
222   // In DWARF, functions and variables are stored to different places.
223   // First, lookup a function for a given offset.
224   if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
225     return createFileLineMsg(info->FileName, info->Line);
226 
227   // If it failed, lookup again as a variable.
228   if (Optional<std::pair<std::string, unsigned>> fileLine =
229           file.getVariableLoc(sym.getName()))
230     return createFileLineMsg(fileLine->first, fileLine->second);
231 
232   // File.sourceFile contains STT_FILE symbol, and that is a last resort.
233   return file.sourceFile;
234 }
235 
236 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
237                                  uint64_t offset) {
238   if (kind() != ObjKind)
239     return "";
240   switch (config->ekind) {
241   default:
242     llvm_unreachable("Invalid kind");
243   case ELF32LEKind:
244     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
245   case ELF32BEKind:
246     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
247   case ELF64LEKind:
248     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
249   case ELF64BEKind:
250     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
251   }
252 }
253 
254 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
255   dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
256   for (std::unique_ptr<DWARFUnit> &cu : dwarf->compile_units()) {
257     auto report = [](Error err) {
258       handleAllErrors(std::move(err),
259                       [](ErrorInfoBase &info) { warn(info.message()); });
260     };
261     Expected<const DWARFDebugLine::LineTable *> expectedLT =
262         dwarf->getLineTableForUnit(cu.get(), report);
263     const DWARFDebugLine::LineTable *lt = nullptr;
264     if (expectedLT)
265       lt = *expectedLT;
266     else
267       report(expectedLT.takeError());
268     if (!lt)
269       continue;
270     lineTables.push_back(lt);
271 
272     // Loop over variable records and insert them to variableLoc.
273     for (const auto &entry : cu->dies()) {
274       DWARFDie die(cu.get(), &entry);
275       // Skip all tags that are not variables.
276       if (die.getTag() != dwarf::DW_TAG_variable)
277         continue;
278 
279       // Skip if a local variable because we don't need them for generating
280       // error messages. In general, only non-local symbols can fail to be
281       // linked.
282       if (!dwarf::toUnsigned(die.find(dwarf::DW_AT_external), 0))
283         continue;
284 
285       // Get the source filename index for the variable.
286       unsigned file = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_file), 0);
287       if (!lt->hasFileAtIndex(file))
288         continue;
289 
290       // Get the line number on which the variable is declared.
291       unsigned line = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_line), 0);
292 
293       // Here we want to take the variable name to add it into variableLoc.
294       // Variable can have regular and linkage name associated. At first, we try
295       // to get linkage name as it can be different, for example when we have
296       // two variables in different namespaces of the same object. Use common
297       // name otherwise, but handle the case when it also absent in case if the
298       // input object file lacks some debug info.
299       StringRef name =
300           dwarf::toString(die.find(dwarf::DW_AT_linkage_name),
301                           dwarf::toString(die.find(dwarf::DW_AT_name), ""));
302       if (!name.empty())
303         variableLoc.insert({name, {lt, file, line}});
304     }
305   }
306 }
307 
308 // Returns the pair of file name and line number describing location of data
309 // object (variable, array, etc) definition.
310 template <class ELFT>
311 Optional<std::pair<std::string, unsigned>>
312 ObjFile<ELFT>::getVariableLoc(StringRef name) {
313   llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
314 
315   // Return if we have no debug information about data object.
316   auto it = variableLoc.find(name);
317   if (it == variableLoc.end())
318     return None;
319 
320   // Take file name string from line table.
321   std::string fileName;
322   if (!it->second.lt->getFileNameByIndex(
323           it->second.file, {},
324           DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, fileName))
325     return None;
326 
327   return std::make_pair(fileName, it->second.line);
328 }
329 
330 // Returns source line information for a given offset
331 // using DWARF debug info.
332 template <class ELFT>
333 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
334                                                   uint64_t offset) {
335   llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
336 
337   // Detect SectionIndex for specified section.
338   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
339   ArrayRef<InputSectionBase *> sections = s->file->getSections();
340   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
341     if (s == sections[curIndex]) {
342       sectionIndex = curIndex;
343       break;
344     }
345   }
346 
347   // Use fake address calcuated by adding section file offset and offset in
348   // section. See comments for ObjectInfo class.
349   DILineInfo info;
350   for (const llvm::DWARFDebugLine::LineTable *lt : lineTables) {
351     if (lt->getFileLineInfoForAddress(
352             {s->getOffsetInFile() + offset, sectionIndex}, nullptr,
353             DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, info))
354       return info;
355   }
356   return None;
357 }
358 
359 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
360 std::string lld::toString(const InputFile *f) {
361   if (!f)
362     return "<internal>";
363 
364   if (f->toStringCache.empty()) {
365     if (f->archiveName.empty())
366       f->toStringCache = f->getName();
367     else
368       f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str();
369   }
370   return f->toStringCache;
371 }
372 
373 ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
374   ekind = getELFKind(mb, "");
375 
376   switch (ekind) {
377   case ELF32LEKind:
378     init<ELF32LE>();
379     break;
380   case ELF32BEKind:
381     init<ELF32BE>();
382     break;
383   case ELF64LEKind:
384     init<ELF64LE>();
385     break;
386   case ELF64BEKind:
387     init<ELF64BE>();
388     break;
389   default:
390     llvm_unreachable("getELFKind");
391   }
392 }
393 
394 template <typename Elf_Shdr>
395 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
396   for (const Elf_Shdr &sec : sections)
397     if (sec.sh_type == type)
398       return &sec;
399   return nullptr;
400 }
401 
402 template <class ELFT> void ELFFileBase::init() {
403   using Elf_Shdr = typename ELFT::Shdr;
404   using Elf_Sym = typename ELFT::Sym;
405 
406   // Initialize trivial attributes.
407   const ELFFile<ELFT> &obj = getObj<ELFT>();
408   emachine = obj.getHeader()->e_machine;
409   osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
410   abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
411 
412   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
413 
414   // Find a symbol table.
415   bool isDSO =
416       (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
417   const Elf_Shdr *symtabSec =
418       findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
419 
420   if (!symtabSec)
421     return;
422 
423   // Initialize members corresponding to a symbol table.
424   firstGlobal = symtabSec->sh_info;
425 
426   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
427   if (firstGlobal == 0 || firstGlobal > eSyms.size())
428     fatal(toString(this) + ": invalid sh_info in symbol table");
429 
430   elfSyms = reinterpret_cast<const void *>(eSyms.data());
431   numELFSyms = eSyms.size();
432   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
433 }
434 
435 template <class ELFT>
436 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
437   return CHECK(
438       this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
439       this);
440 }
441 
442 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
443   if (this->symbols.empty())
444     return {};
445   return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
446 }
447 
448 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
449   return makeArrayRef(this->symbols).slice(this->firstGlobal);
450 }
451 
452 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
453   // Read a section table. justSymbols is usually false.
454   if (this->justSymbols)
455     initializeJustSymbols();
456   else
457     initializeSections(ignoreComdats);
458 
459   // Read a symbol table.
460   initializeSymbols();
461 }
462 
463 // Sections with SHT_GROUP and comdat bits define comdat section groups.
464 // They are identified and deduplicated by group name. This function
465 // returns a group name.
466 template <class ELFT>
467 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
468                                               const Elf_Shdr &sec) {
469   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
470   if (sec.sh_info >= symbols.size())
471     fatal(toString(this) + ": invalid symbol index");
472   const typename ELFT::Sym &sym = symbols[sec.sh_info];
473   StringRef signature = CHECK(sym.getName(this->stringTable), this);
474 
475   // As a special case, if a symbol is a section symbol and has no name,
476   // we use a section name as a signature.
477   //
478   // Such SHT_GROUP sections are invalid from the perspective of the ELF
479   // standard, but GNU gold 1.14 (the newest version as of July 2017) or
480   // older produce such sections as outputs for the -r option, so we need
481   // a bug-compatibility.
482   if (signature.empty() && sym.getType() == STT_SECTION)
483     return getSectionName(sec);
484   return signature;
485 }
486 
487 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec) {
488   // On a regular link we don't merge sections if -O0 (default is -O1). This
489   // sometimes makes the linker significantly faster, although the output will
490   // be bigger.
491   //
492   // Doing the same for -r would create a problem as it would combine sections
493   // with different sh_entsize. One option would be to just copy every SHF_MERGE
494   // section as is to the output. While this would produce a valid ELF file with
495   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
496   // they see two .debug_str. We could have separate logic for combining
497   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
498   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
499   // logic for -r.
500   if (config->optimize == 0 && !config->relocatable)
501     return false;
502 
503   // A mergeable section with size 0 is useless because they don't have
504   // any data to merge. A mergeable string section with size 0 can be
505   // argued as invalid because it doesn't end with a null character.
506   // We'll avoid a mess by handling them as if they were non-mergeable.
507   if (sec.sh_size == 0)
508     return false;
509 
510   // Check for sh_entsize. The ELF spec is not clear about the zero
511   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
512   // the section does not hold a table of fixed-size entries". We know
513   // that Rust 1.13 produces a string mergeable section with a zero
514   // sh_entsize. Here we just accept it rather than being picky about it.
515   uint64_t entSize = sec.sh_entsize;
516   if (entSize == 0)
517     return false;
518   if (sec.sh_size % entSize)
519     fatal(toString(this) +
520           ": SHF_MERGE section size must be a multiple of sh_entsize");
521 
522   uint64_t flags = sec.sh_flags;
523   if (!(flags & SHF_MERGE))
524     return false;
525   if (flags & SHF_WRITE)
526     fatal(toString(this) + ": writable SHF_MERGE section is not supported");
527 
528   return true;
529 }
530 
531 // This is for --just-symbols.
532 //
533 // --just-symbols is a very minor feature that allows you to link your
534 // output against other existing program, so that if you load both your
535 // program and the other program into memory, your output can refer the
536 // other program's symbols.
537 //
538 // When the option is given, we link "just symbols". The section table is
539 // initialized with null pointers.
540 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
541   ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
542   this->sections.resize(sections.size());
543 }
544 
545 // An ELF object file may contain a `.deplibs` section. If it exists, the
546 // section contains a list of library specifiers such as `m` for libm. This
547 // function resolves a given name by finding the first matching library checking
548 // the various ways that a library can be specified to LLD. This ELF extension
549 // is a form of autolinking and is called `dependent libraries`. It is currently
550 // unique to LLVM and lld.
551 static void addDependentLibrary(StringRef specifier, const InputFile *f) {
552   if (!config->dependentLibraries)
553     return;
554   if (fs::exists(specifier))
555     driver->addFile(specifier, /*withLOption=*/false);
556   else if (Optional<std::string> s = findFromSearchPaths(specifier))
557     driver->addFile(*s, /*withLOption=*/true);
558   else if (Optional<std::string> s = searchLibraryBaseName(specifier))
559     driver->addFile(*s, /*withLOption=*/true);
560   else
561     error(toString(f) +
562           ": unable to find library from dependent library specifier: " +
563           specifier);
564 }
565 
566 template <class ELFT>
567 void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
568   const ELFFile<ELFT> &obj = this->getObj();
569 
570   ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
571   uint64_t size = objSections.size();
572   this->sections.resize(size);
573   this->sectionStringTable =
574       CHECK(obj.getSectionStringTable(objSections), this);
575 
576   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
577     if (this->sections[i] == &InputSection::discarded)
578       continue;
579     const Elf_Shdr &sec = objSections[i];
580 
581     if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
582       cgProfile =
583           check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
584 
585     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
586     // if -r is given, we'll let the final link discard such sections.
587     // This is compatible with GNU.
588     if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
589       if (sec.sh_type == SHT_LLVM_ADDRSIG) {
590         // We ignore the address-significance table if we know that the object
591         // file was created by objcopy or ld -r. This is because these tools
592         // will reorder the symbols in the symbol table, invalidating the data
593         // in the address-significance table, which refers to symbols by index.
594         if (sec.sh_link != 0)
595           this->addrsigSec = &sec;
596         else if (config->icf == ICFLevel::Safe)
597           warn(toString(this) + ": --icf=safe is incompatible with object "
598                                 "files created using objcopy or ld -r");
599       }
600       this->sections[i] = &InputSection::discarded;
601       continue;
602     }
603 
604     switch (sec.sh_type) {
605     case SHT_GROUP: {
606       // De-duplicate section groups by their signatures.
607       StringRef signature = getShtGroupSignature(objSections, sec);
608       this->sections[i] = &InputSection::discarded;
609 
610 
611       ArrayRef<Elf_Word> entries =
612           CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
613       if (entries.empty())
614         fatal(toString(this) + ": empty SHT_GROUP");
615 
616       // The first word of a SHT_GROUP section contains flags. Currently,
617       // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
618       // An group with the empty flag doesn't define anything; such sections
619       // are just skipped.
620       if (entries[0] == 0)
621         continue;
622 
623       if (entries[0] != GRP_COMDAT)
624         fatal(toString(this) + ": unsupported SHT_GROUP format");
625 
626       bool isNew =
627           ignoreComdats ||
628           symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
629               .second;
630       if (isNew) {
631         if (config->relocatable)
632           this->sections[i] = createInputSection(sec);
633         continue;
634       }
635 
636       // Otherwise, discard group members.
637       for (uint32_t secIndex : entries.slice(1)) {
638         if (secIndex >= size)
639           fatal(toString(this) +
640                 ": invalid section index in group: " + Twine(secIndex));
641         this->sections[secIndex] = &InputSection::discarded;
642       }
643       break;
644     }
645     case SHT_SYMTAB_SHNDX:
646       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
647       break;
648     case SHT_SYMTAB:
649     case SHT_STRTAB:
650     case SHT_NULL:
651       break;
652     default:
653       this->sections[i] = createInputSection(sec);
654     }
655   }
656 
657   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
658     if (this->sections[i] == &InputSection::discarded)
659       continue;
660     const Elf_Shdr &sec = objSections[i];
661     if (!(sec.sh_flags & SHF_LINK_ORDER))
662       continue;
663 
664     // .ARM.exidx sections have a reverse dependency on the InputSection they
665     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
666     InputSectionBase *linkSec = nullptr;
667     if (sec.sh_link < this->sections.size())
668       linkSec = this->sections[sec.sh_link];
669     if (!linkSec)
670       fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
671 
672     InputSection *isec = cast<InputSection>(this->sections[i]);
673     linkSec->dependentSections.push_back(isec);
674     if (!isa<InputSection>(linkSec))
675       error("a section " + isec->name +
676             " with SHF_LINK_ORDER should not refer a non-regular section: " +
677             toString(linkSec));
678   }
679 }
680 
681 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
682 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
683 // the input objects have been compiled.
684 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
685                              const InputFile *f) {
686   if (!attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
687     // If an ABI tag isn't present then it is implicitly given the value of 0
688     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
689     // including some in glibc that don't use FP args (and should have value 3)
690     // don't have the attribute so we do not consider an implicit value of 0
691     // as a clash.
692     return;
693 
694   unsigned vfpArgs = attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
695   ARMVFPArgKind arg;
696   switch (vfpArgs) {
697   case ARMBuildAttrs::BaseAAPCS:
698     arg = ARMVFPArgKind::Base;
699     break;
700   case ARMBuildAttrs::HardFPAAPCS:
701     arg = ARMVFPArgKind::VFP;
702     break;
703   case ARMBuildAttrs::ToolChainFPPCS:
704     // Tool chain specific convention that conforms to neither AAPCS variant.
705     arg = ARMVFPArgKind::ToolChain;
706     break;
707   case ARMBuildAttrs::CompatibleFPAAPCS:
708     // Object compatible with all conventions.
709     return;
710   default:
711     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
712     return;
713   }
714   // Follow ld.bfd and error if there is a mix of calling conventions.
715   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
716     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
717   else
718     config->armVFPArgs = arg;
719 }
720 
721 // The ARM support in lld makes some use of instructions that are not available
722 // on all ARM architectures. Namely:
723 // - Use of BLX instruction for interworking between ARM and Thumb state.
724 // - Use of the extended Thumb branch encoding in relocation.
725 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
726 // The ARM Attributes section contains information about the architecture chosen
727 // at compile time. We follow the convention that if at least one input object
728 // is compiled with an architecture that supports these features then lld is
729 // permitted to use them.
730 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
731   if (!attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
732     return;
733   auto arch = attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
734   switch (arch) {
735   case ARMBuildAttrs::Pre_v4:
736   case ARMBuildAttrs::v4:
737   case ARMBuildAttrs::v4T:
738     // Architectures prior to v5 do not support BLX instruction
739     break;
740   case ARMBuildAttrs::v5T:
741   case ARMBuildAttrs::v5TE:
742   case ARMBuildAttrs::v5TEJ:
743   case ARMBuildAttrs::v6:
744   case ARMBuildAttrs::v6KZ:
745   case ARMBuildAttrs::v6K:
746     config->armHasBlx = true;
747     // Architectures used in pre-Cortex processors do not support
748     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
749     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
750     break;
751   default:
752     // All other Architectures have BLX and extended branch encoding
753     config->armHasBlx = true;
754     config->armJ1J2BranchEncoding = true;
755     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
756       // All Architectures used in Cortex processors with the exception
757       // of v6-M and v6S-M have the MOVT and MOVW instructions.
758       config->armHasMovtMovw = true;
759     break;
760   }
761 }
762 
763 // If a source file is compiled with x86 hardware-assisted call flow control
764 // enabled, the generated object file contains feature flags indicating that
765 // fact. This function reads the feature flags and returns it.
766 //
767 // Essentially we want to read a single 32-bit value in this function, but this
768 // function is rather complicated because the value is buried deep inside a
769 // .note.gnu.property section.
770 //
771 // The section consists of one or more NOTE records. Each NOTE record consists
772 // of zero or more type-length-value fields. We want to find a field of a
773 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
774 // the ABI is unnecessarily complicated.
775 template <class ELFT>
776 static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
777   using Elf_Nhdr = typename ELFT::Nhdr;
778   using Elf_Note = typename ELFT::Note;
779 
780   uint32_t featuresSet = 0;
781   while (!data.empty()) {
782     // Read one NOTE record.
783     if (data.size() < sizeof(Elf_Nhdr))
784       fatal(toString(obj) + ": .note.gnu.property: section too short");
785 
786     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
787     if (data.size() < nhdr->getSize())
788       fatal(toString(obj) + ": .note.gnu.property: section too short");
789 
790     Elf_Note note(*nhdr);
791     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
792       data = data.slice(nhdr->getSize());
793       continue;
794     }
795 
796     uint32_t featureAndType = config->emachine == EM_AARCH64
797                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
798                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
799 
800     // Read a body of a NOTE record, which consists of type-length-value fields.
801     ArrayRef<uint8_t> desc = note.getDesc();
802     while (!desc.empty()) {
803       if (desc.size() < 8)
804         fatal(toString(obj) + ": .note.gnu.property: section too short");
805 
806       uint32_t type = read32le(desc.data());
807       uint32_t size = read32le(desc.data() + 4);
808 
809       if (type == featureAndType) {
810         // We found a FEATURE_1_AND field. There may be more than one of these
811         // in a .note.gnu.propery section, for a relocatable object we
812         // accumulate the bits set.
813         featuresSet |= read32le(desc.data() + 8);
814       }
815 
816       // On 64-bit, a payload may be followed by a 4-byte padding to make its
817       // size a multiple of 8.
818       if (ELFT::Is64Bits)
819         size = alignTo(size, 8);
820 
821       desc = desc.slice(size + 8); // +8 for Type and Size
822     }
823 
824     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
825     data = data.slice(nhdr->getSize());
826   }
827 
828   return featuresSet;
829 }
830 
831 template <class ELFT>
832 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
833   uint32_t idx = sec.sh_info;
834   if (idx >= this->sections.size())
835     fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
836   InputSectionBase *target = this->sections[idx];
837 
838   // Strictly speaking, a relocation section must be included in the
839   // group of the section it relocates. However, LLVM 3.3 and earlier
840   // would fail to do so, so we gracefully handle that case.
841   if (target == &InputSection::discarded)
842     return nullptr;
843 
844   if (!target)
845     fatal(toString(this) + ": unsupported relocation reference");
846   return target;
847 }
848 
849 // Create a regular InputSection class that has the same contents
850 // as a given section.
851 static InputSection *toRegularSection(MergeInputSection *sec) {
852   return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
853                             sec->data(), sec->name);
854 }
855 
856 template <class ELFT>
857 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
858   StringRef name = getSectionName(sec);
859 
860   switch (sec.sh_type) {
861   case SHT_ARM_ATTRIBUTES: {
862     if (config->emachine != EM_ARM)
863       break;
864     ARMAttributeParser attributes;
865     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
866     attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
867     updateSupportedARMFeatures(attributes);
868     updateARMVFPArgs(attributes, this);
869 
870     // FIXME: Retain the first attribute section we see. The eglibc ARM
871     // dynamic loaders require the presence of an attribute section for dlopen
872     // to work. In a full implementation we would merge all attribute sections.
873     if (in.armAttributes == nullptr) {
874       in.armAttributes = make<InputSection>(*this, sec, name);
875       return in.armAttributes;
876     }
877     return &InputSection::discarded;
878   }
879   case SHT_LLVM_DEPENDENT_LIBRARIES: {
880     if (config->relocatable)
881       break;
882     ArrayRef<char> data =
883         CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
884     if (!data.empty() && data.back() != '\0') {
885       error(toString(this) +
886             ": corrupted dependent libraries section (unterminated string): " +
887             name);
888       return &InputSection::discarded;
889     }
890     for (const char *d = data.begin(), *e = data.end(); d < e;) {
891       StringRef s(d);
892       addDependentLibrary(s, this);
893       d += s.size() + 1;
894     }
895     return &InputSection::discarded;
896   }
897   case SHT_RELA:
898   case SHT_REL: {
899     // Find a relocation target section and associate this section with that.
900     // Target may have been discarded if it is in a different section group
901     // and the group is discarded, even though it's a violation of the
902     // spec. We handle that situation gracefully by discarding dangling
903     // relocation sections.
904     InputSectionBase *target = getRelocTarget(sec);
905     if (!target)
906       return nullptr;
907 
908     // This section contains relocation information.
909     // If -r is given, we do not interpret or apply relocation
910     // but just copy relocation sections to output.
911     if (config->relocatable) {
912       InputSection *relocSec = make<InputSection>(*this, sec, name);
913       // We want to add a dependency to target, similar like we do for
914       // -emit-relocs below. This is useful for the case when linker script
915       // contains the "/DISCARD/". It is perhaps uncommon to use a script with
916       // -r, but we faced it in the Linux kernel and have to handle such case
917       // and not to crash.
918       target->dependentSections.push_back(relocSec);
919       return relocSec;
920     }
921 
922     if (target->firstRelocation)
923       fatal(toString(this) +
924             ": multiple relocation sections to one section are not supported");
925 
926     // ELF spec allows mergeable sections with relocations, but they are
927     // rare, and it is in practice hard to merge such sections by contents,
928     // because applying relocations at end of linking changes section
929     // contents. So, we simply handle such sections as non-mergeable ones.
930     // Degrading like this is acceptable because section merging is optional.
931     if (auto *ms = dyn_cast<MergeInputSection>(target)) {
932       target = toRegularSection(ms);
933       this->sections[sec.sh_info] = target;
934     }
935 
936     if (sec.sh_type == SHT_RELA) {
937       ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
938       target->firstRelocation = rels.begin();
939       target->numRelocations = rels.size();
940       target->areRelocsRela = true;
941     } else {
942       ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
943       target->firstRelocation = rels.begin();
944       target->numRelocations = rels.size();
945       target->areRelocsRela = false;
946     }
947     assert(isUInt<31>(target->numRelocations));
948 
949     // Relocation sections processed by the linker are usually removed
950     // from the output, so returning `nullptr` for the normal case.
951     // However, if -emit-relocs is given, we need to leave them in the output.
952     // (Some post link analysis tools need this information.)
953     if (config->emitRelocs) {
954       InputSection *relocSec = make<InputSection>(*this, sec, name);
955       // We will not emit relocation section if target was discarded.
956       target->dependentSections.push_back(relocSec);
957       return relocSec;
958     }
959     return nullptr;
960   }
961   }
962 
963   // The GNU linker uses .note.GNU-stack section as a marker indicating
964   // that the code in the object file does not expect that the stack is
965   // executable (in terms of NX bit). If all input files have the marker,
966   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
967   // make the stack non-executable. Most object files have this section as
968   // of 2017.
969   //
970   // But making the stack non-executable is a norm today for security
971   // reasons. Failure to do so may result in a serious security issue.
972   // Therefore, we make LLD always add PT_GNU_STACK unless it is
973   // explicitly told to do otherwise (by -z execstack). Because the stack
974   // executable-ness is controlled solely by command line options,
975   // .note.GNU-stack sections are simply ignored.
976   if (name == ".note.GNU-stack")
977     return &InputSection::discarded;
978 
979   // Object files that use processor features such as Intel Control-Flow
980   // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
981   // .note.gnu.property section containing a bitfield of feature bits like the
982   // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
983   //
984   // Since we merge bitmaps from multiple object files to create a new
985   // .note.gnu.property containing a single AND'ed bitmap, we discard an input
986   // file's .note.gnu.property section.
987   if (name == ".note.gnu.property") {
988     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
989     this->andFeatures = readAndFeatures(this, contents);
990     return &InputSection::discarded;
991   }
992 
993   // Split stacks is a feature to support a discontiguous stack,
994   // commonly used in the programming language Go. For the details,
995   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
996   // for split stack will include a .note.GNU-split-stack section.
997   if (name == ".note.GNU-split-stack") {
998     if (config->relocatable) {
999       error("cannot mix split-stack and non-split-stack in a relocatable link");
1000       return &InputSection::discarded;
1001     }
1002     this->splitStack = true;
1003     return &InputSection::discarded;
1004   }
1005 
1006   // An object file cmpiled for split stack, but where some of the
1007   // functions were compiled with the no_split_stack_attribute will
1008   // include a .note.GNU-no-split-stack section.
1009   if (name == ".note.GNU-no-split-stack") {
1010     this->someNoSplitStack = true;
1011     return &InputSection::discarded;
1012   }
1013 
1014   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1015   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1016   // sections. Drop those sections to avoid duplicate symbol errors.
1017   // FIXME: This is glibc PR20543, we should remove this hack once that has been
1018   // fixed for a while.
1019   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1020       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1021     return &InputSection::discarded;
1022 
1023   // If we are creating a new .build-id section, strip existing .build-id
1024   // sections so that the output won't have more than one .build-id.
1025   // This is not usually a problem because input object files normally don't
1026   // have .build-id sections, but you can create such files by
1027   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1028   if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
1029     return &InputSection::discarded;
1030 
1031   // The linker merges EH (exception handling) frames and creates a
1032   // .eh_frame_hdr section for runtime. So we handle them with a special
1033   // class. For relocatable outputs, they are just passed through.
1034   if (name == ".eh_frame" && !config->relocatable)
1035     return make<EhInputSection>(*this, sec, name);
1036 
1037   if (shouldMerge(sec))
1038     return make<MergeInputSection>(*this, sec, name);
1039   return make<InputSection>(*this, sec, name);
1040 }
1041 
1042 template <class ELFT>
1043 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1044   return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1045 }
1046 
1047 // Initialize this->Symbols. this->Symbols is a parallel array as
1048 // its corresponding ELF symbol table.
1049 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1050   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1051   this->symbols.resize(eSyms.size());
1052 
1053   // Our symbol table may have already been partially initialized
1054   // because of LazyObjFile.
1055   for (size_t i = 0, end = eSyms.size(); i != end; ++i)
1056     if (!this->symbols[i] && eSyms[i].getBinding() != STB_LOCAL)
1057       this->symbols[i] =
1058           symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1059 
1060   // Fill this->Symbols. A symbol is either local or global.
1061   for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
1062     const Elf_Sym &eSym = eSyms[i];
1063 
1064     // Read symbol attributes.
1065     uint32_t secIdx = getSectionIndex(eSym);
1066     if (secIdx >= this->sections.size())
1067       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1068 
1069     InputSectionBase *sec = this->sections[secIdx];
1070     uint8_t binding = eSym.getBinding();
1071     uint8_t stOther = eSym.st_other;
1072     uint8_t type = eSym.getType();
1073     uint64_t value = eSym.st_value;
1074     uint64_t size = eSym.st_size;
1075     StringRefZ name = this->stringTable.data() + eSym.st_name;
1076 
1077     // Handle local symbols. Local symbols are not added to the symbol
1078     // table because they are not visible from other object files. We
1079     // allocate symbol instances and add their pointers to Symbols.
1080     if (binding == STB_LOCAL) {
1081       if (eSym.getType() == STT_FILE)
1082         sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083 
1084       if (this->stringTable.size() <= eSym.st_name)
1085         fatal(toString(this) + ": invalid symbol name offset");
1086 
1087       if (eSym.st_shndx == SHN_UNDEF)
1088         this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
1089       else if (sec == &InputSection::discarded)
1090         this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
1091                                            /*DiscardedSecIdx=*/secIdx);
1092       else
1093         this->symbols[i] =
1094             make<Defined>(this, name, binding, stOther, type, value, size, sec);
1095       continue;
1096     }
1097 
1098     // Handle global undefined symbols.
1099     if (eSym.st_shndx == SHN_UNDEF) {
1100       this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
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 New(&f, name, binding, visibility, type);
1478     if (canOmitFromDynSym)
1479       New.exportDynamic = false;
1480     return symtab->addSymbol(New);
1481   }
1482 
1483   if (objSym.isCommon())
1484     return symtab->addSymbol(
1485         CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
1486                      objSym.getCommonAlignment(), objSym.getCommonSize()});
1487 
1488   Defined New(&f, name, binding, visibility, type, 0, 0, nullptr);
1489   if (canOmitFromDynSym)
1490     New.exportDynamic = false;
1491   return symtab->addSymbol(New);
1492 }
1493 
1494 template <class ELFT> void BitcodeFile::parse() {
1495   std::vector<bool> keptComdats;
1496   for (StringRef s : obj->getComdatTable())
1497     keptComdats.push_back(
1498         symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
1499 
1500   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1501     symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
1502 
1503   for (auto l : obj->getDependentLibraries())
1504     addDependentLibrary(l, this);
1505 }
1506 
1507 void BinaryFile::parse() {
1508   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1509   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1510                                      8, data, ".data");
1511   sections.push_back(section);
1512 
1513   // For each input file foo that is embedded to a result as a binary
1514   // blob, we define _binary_foo_{start,end,size} symbols, so that
1515   // user programs can access blobs by name. Non-alphanumeric
1516   // characters in a filename are replaced with underscore.
1517   std::string s = "_binary_" + mb.getBufferIdentifier().str();
1518   for (size_t i = 0; i < s.size(); ++i)
1519     if (!isAlnum(s[i]))
1520       s[i] = '_';
1521 
1522   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
1523                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
1524   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
1525                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
1526   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
1527                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
1528 }
1529 
1530 InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
1531                                  uint64_t offsetInArchive) {
1532   if (isBitcode(mb))
1533     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1534 
1535   switch (getELFKind(mb, archiveName)) {
1536   case ELF32LEKind:
1537     return make<ObjFile<ELF32LE>>(mb, archiveName);
1538   case ELF32BEKind:
1539     return make<ObjFile<ELF32BE>>(mb, archiveName);
1540   case ELF64LEKind:
1541     return make<ObjFile<ELF64LE>>(mb, archiveName);
1542   case ELF64BEKind:
1543     return make<ObjFile<ELF64BE>>(mb, archiveName);
1544   default:
1545     llvm_unreachable("getELFKind");
1546   }
1547 }
1548 
1549 void LazyObjFile::fetch() {
1550   if (mb.getBuffer().empty())
1551     return;
1552 
1553   InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
1554   file->groupId = groupId;
1555 
1556   mb = {};
1557 
1558   // Copy symbol vector so that the new InputFile doesn't have to
1559   // insert the same defined symbols to the symbol table again.
1560   file->symbols = std::move(symbols);
1561 
1562   parseFile(file);
1563 }
1564 
1565 template <class ELFT> void LazyObjFile::parse() {
1566   using Elf_Sym = typename ELFT::Sym;
1567 
1568   // A lazy object file wraps either a bitcode file or an ELF file.
1569   if (isBitcode(this->mb)) {
1570     std::unique_ptr<lto::InputFile> obj =
1571         CHECK(lto::InputFile::create(this->mb), this);
1572     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
1573       if (sym.isUndefined())
1574         continue;
1575       symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
1576     }
1577     return;
1578   }
1579 
1580   if (getELFKind(this->mb, archiveName) != config->ekind) {
1581     error("incompatible file: " + this->mb.getBufferIdentifier());
1582     return;
1583   }
1584 
1585   // Find a symbol table.
1586   ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
1587   ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
1588 
1589   for (const typename ELFT::Shdr &sec : sections) {
1590     if (sec.sh_type != SHT_SYMTAB)
1591       continue;
1592 
1593     // A symbol table is found.
1594     ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
1595     uint32_t firstGlobal = sec.sh_info;
1596     StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
1597     this->symbols.resize(eSyms.size());
1598 
1599     // Get existing symbols or insert placeholder symbols.
1600     for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1601       if (eSyms[i].st_shndx != SHN_UNDEF)
1602         this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
1603 
1604     // Replace existing symbols with LazyObject symbols.
1605     //
1606     // resolve() may trigger this->fetch() if an existing symbol is an
1607     // undefined symbol. If that happens, this LazyObjFile has served
1608     // its purpose, and we can exit from the loop early.
1609     for (Symbol *sym : this->symbols) {
1610       if (!sym)
1611         continue;
1612       sym->resolve(LazyObject{*this, sym->getName()});
1613 
1614       // MemoryBuffer is emptied if this file is instantiated as ObjFile.
1615       if (mb.getBuffer().empty())
1616         return;
1617     }
1618     return;
1619   }
1620 }
1621 
1622 std::string elf::replaceThinLTOSuffix(StringRef path) {
1623   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1624   StringRef repl = config->thinLTOObjectSuffixReplace.second;
1625 
1626   if (path.consume_back(suffix))
1627     return (path + repl).str();
1628   return path;
1629 }
1630 
1631 template void BitcodeFile::parse<ELF32LE>();
1632 template void BitcodeFile::parse<ELF32BE>();
1633 template void BitcodeFile::parse<ELF64LE>();
1634 template void BitcodeFile::parse<ELF64BE>();
1635 
1636 template void LazyObjFile::parse<ELF32LE>();
1637 template void LazyObjFile::parse<ELF32BE>();
1638 template void LazyObjFile::parse<ELF64LE>();
1639 template void LazyObjFile::parse<ELF64BE>();
1640 
1641 template class elf::ObjFile<ELF32LE>;
1642 template class elf::ObjFile<ELF32BE>;
1643 template class elf::ObjFile<ELF64LE>;
1644 template class elf::ObjFile<ELF64BE>;
1645 
1646 template void SharedFile::parse<ELF32LE>();
1647 template void SharedFile::parse<ELF32BE>();
1648 template void SharedFile::parse<ELF64LE>();
1649 template void SharedFile::parse<ELF64BE>();
1650