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