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