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 "InputSection.h"
11 #include "LinkerScript.h"
12 #include "SymbolTable.h"
13 #include "Symbols.h"
14 #include "SyntheticSections.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/MC/StringTableBuilder.h"
24 #include "llvm/Object/ELFObjectFile.h"
25 #include "llvm/Support/ARMAttributeParser.h"
26 #include "llvm/Support/ARMBuildAttributes.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/TarWriter.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 using namespace llvm;
32 using namespace llvm::ELF;
33 using namespace llvm::object;
34 using namespace llvm::sys;
35 using namespace llvm::sys::fs;
36 
37 using namespace lld;
38 using namespace lld::elf;
39 
40 bool InputFile::IsInGroup;
41 uint32_t InputFile::NextGroupId;
42 std::vector<BinaryFile *> elf::BinaryFiles;
43 std::vector<BitcodeFile *> elf::BitcodeFiles;
44 std::vector<LazyObjFile *> elf::LazyObjFiles;
45 std::vector<InputFile *> elf::ObjectFiles;
46 std::vector<SharedFile *> elf::SharedFiles;
47 
48 std::unique_ptr<TarWriter> elf::Tar;
49 
50 InputFile::InputFile(Kind K, MemoryBufferRef M)
51     : MB(M), GroupId(NextGroupId), FileKind(K) {
52   // All files within the same --{start,end}-group get the same group ID.
53   // Otherwise, a new file will get a new group ID.
54   if (!IsInGroup)
55     ++NextGroupId;
56 }
57 
58 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
59   // The --chroot option changes our virtual root directory.
60   // This is useful when you are dealing with files created by --reproduce.
61   if (!Config->Chroot.empty() && Path.startswith("/"))
62     Path = Saver.save(Config->Chroot + Path);
63 
64   log(Path);
65 
66   auto MBOrErr = MemoryBuffer::getFile(Path, -1, false);
67   if (auto EC = MBOrErr.getError()) {
68     error("cannot open " + Path + ": " + EC.message());
69     return None;
70   }
71 
72   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
73   MemoryBufferRef MBRef = MB->getMemBufferRef();
74   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
75 
76   if (Tar)
77     Tar->append(relativeToRoot(Path), MBRef.getBuffer());
78   return MBRef;
79 }
80 
81 // All input object files must be for the same architecture
82 // (e.g. it does not make sense to link x86 object files with
83 // MIPS object files.) This function checks for that error.
84 static bool isCompatible(InputFile *File) {
85   if (!File->isElf() && !isa<BitcodeFile>(File))
86     return true;
87 
88   if (File->EKind == Config->EKind && File->EMachine == Config->EMachine) {
89     if (Config->EMachine != EM_MIPS)
90       return true;
91     if (isMipsN32Abi(File) == Config->MipsN32Abi)
92       return true;
93   }
94 
95   if (!Config->Emulation.empty()) {
96     error(toString(File) + " is incompatible with " + Config->Emulation);
97   } else {
98     InputFile *Existing;
99     if (!ObjectFiles.empty())
100       Existing = ObjectFiles[0];
101     else if (!SharedFiles.empty())
102       Existing = SharedFiles[0];
103     else
104       Existing = BitcodeFiles[0];
105 
106     error(toString(File) + " is incompatible with " + toString(Existing));
107   }
108 
109   return false;
110 }
111 
112 template <class ELFT> static void doParseFile(InputFile *File) {
113   // Comdat groups define "link once" sections. If two comdat groups have the
114   // same name, only one of them is linked, and the other is ignored. This set
115   // is used to uniquify them.
116   static llvm::DenseSet<llvm::CachedHashStringRef> ComdatGroups;
117 
118   if (!isCompatible(File))
119     return;
120 
121   // Binary file
122   if (auto *F = dyn_cast<BinaryFile>(File)) {
123     BinaryFiles.push_back(F);
124     F->parse();
125     return;
126   }
127 
128   // .a file
129   if (auto *F = dyn_cast<ArchiveFile>(File)) {
130     F->parse();
131     return;
132   }
133 
134   // Lazy object file
135   if (auto *F = dyn_cast<LazyObjFile>(File)) {
136     LazyObjFiles.push_back(F);
137     F->parse<ELFT>();
138     return;
139   }
140 
141   if (Config->Trace)
142     message(toString(File));
143 
144   // .so file
145   if (auto *F = dyn_cast<SharedFile>(File)) {
146     F->parse<ELFT>();
147     return;
148   }
149 
150   // LLVM bitcode file
151   if (auto *F = dyn_cast<BitcodeFile>(File)) {
152     BitcodeFiles.push_back(F);
153     F->parse<ELFT>(ComdatGroups);
154     return;
155   }
156 
157   // Regular object file
158   ObjectFiles.push_back(File);
159   cast<ObjFile<ELFT>>(File)->parse(ComdatGroups);
160 }
161 
162 // Add symbols in File to the symbol table.
163 void elf::parseFile(InputFile *File) {
164   switch (Config->EKind) {
165   case ELF32LEKind:
166     doParseFile<ELF32LE>(File);
167     return;
168   case ELF32BEKind:
169     doParseFile<ELF32BE>(File);
170     return;
171   case ELF64LEKind:
172     doParseFile<ELF64LE>(File);
173     return;
174   case ELF64BEKind:
175     doParseFile<ELF64BE>(File);
176     return;
177   default:
178     llvm_unreachable("unknown ELFT");
179   }
180 }
181 
182 // Concatenates arguments to construct a string representing an error location.
183 static std::string createFileLineMsg(StringRef Path, unsigned Line) {
184   std::string Filename = path::filename(Path);
185   std::string Lineno = ":" + std::to_string(Line);
186   if (Filename == Path)
187     return Filename + Lineno;
188   return Filename + Lineno + " (" + Path.str() + Lineno + ")";
189 }
190 
191 template <class ELFT>
192 static std::string getSrcMsgAux(ObjFile<ELFT> &File, const Symbol &Sym,
193                                 InputSectionBase &Sec, uint64_t Offset) {
194   // In DWARF, functions and variables are stored to different places.
195   // First, lookup a function for a given offset.
196   if (Optional<DILineInfo> Info = File.getDILineInfo(&Sec, Offset))
197     return createFileLineMsg(Info->FileName, Info->Line);
198 
199   // If it failed, lookup again as a variable.
200   if (Optional<std::pair<std::string, unsigned>> FileLine =
201           File.getVariableLoc(Sym.getName()))
202     return createFileLineMsg(FileLine->first, FileLine->second);
203 
204   // File.SourceFile contains STT_FILE symbol, and that is a last resort.
205   return File.SourceFile;
206 }
207 
208 std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec,
209                                  uint64_t Offset) {
210   if (kind() != ObjKind)
211     return "";
212   switch (Config->EKind) {
213   default:
214     llvm_unreachable("Invalid kind");
215   case ELF32LEKind:
216     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset);
217   case ELF32BEKind:
218     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset);
219   case ELF64LEKind:
220     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset);
221   case ELF64BEKind:
222     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset);
223   }
224 }
225 
226 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
227   Dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
228   for (std::unique_ptr<DWARFUnit> &CU : Dwarf->compile_units()) {
229     auto Report = [](Error Err) {
230       handleAllErrors(std::move(Err),
231                       [](ErrorInfoBase &Info) { warn(Info.message()); });
232     };
233     Expected<const DWARFDebugLine::LineTable *> ExpectedLT =
234         Dwarf->getLineTableForUnit(CU.get(), Report);
235     const DWARFDebugLine::LineTable *LT = nullptr;
236     if (ExpectedLT)
237       LT = *ExpectedLT;
238     else
239       Report(ExpectedLT.takeError());
240     if (!LT)
241       continue;
242     LineTables.push_back(LT);
243 
244     // Loop over variable records and insert them to VariableLoc.
245     for (const auto &Entry : CU->dies()) {
246       DWARFDie Die(CU.get(), &Entry);
247       // Skip all tags that are not variables.
248       if (Die.getTag() != dwarf::DW_TAG_variable)
249         continue;
250 
251       // Skip if a local variable because we don't need them for generating
252       // error messages. In general, only non-local symbols can fail to be
253       // linked.
254       if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
255         continue;
256 
257       // Get the source filename index for the variable.
258       unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
259       if (!LT->hasFileAtIndex(File))
260         continue;
261 
262       // Get the line number on which the variable is declared.
263       unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
264 
265       // Here we want to take the variable name to add it into VariableLoc.
266       // Variable can have regular and linkage name associated. At first, we try
267       // to get linkage name as it can be different, for example when we have
268       // two variables in different namespaces of the same object. Use common
269       // name otherwise, but handle the case when it also absent in case if the
270       // input object file lacks some debug info.
271       StringRef Name =
272           dwarf::toString(Die.find(dwarf::DW_AT_linkage_name),
273                           dwarf::toString(Die.find(dwarf::DW_AT_name), ""));
274       if (!Name.empty())
275         VariableLoc.insert({Name, {LT, File, Line}});
276     }
277   }
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   llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
286 
287   // Return if we have no debug information about data object.
288   auto It = VariableLoc.find(Name);
289   if (It == VariableLoc.end())
290     return None;
291 
292   // Take file name string from line table.
293   std::string FileName;
294   if (!It->second.LT->getFileNameByIndex(
295           It->second.File, nullptr,
296           DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
297     return None;
298 
299   return std::make_pair(FileName, It->second.Line);
300 }
301 
302 // Returns source line information for a given offset
303 // using DWARF debug info.
304 template <class ELFT>
305 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
306                                                   uint64_t Offset) {
307   llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
308 
309   // Detect SectionIndex for specified section.
310   uint64_t SectionIndex = object::SectionedAddress::UndefSection;
311   ArrayRef<InputSectionBase *> Sections = S->File->getSections();
312   for (uint64_t CurIndex = 0; CurIndex < Sections.size(); ++CurIndex) {
313     if (S == Sections[CurIndex]) {
314       SectionIndex = CurIndex;
315       break;
316     }
317   }
318 
319   // Use fake address calcuated by adding section file offset and offset in
320   // section. See comments for ObjectInfo class.
321   DILineInfo Info;
322   for (const llvm::DWARFDebugLine::LineTable *LT : LineTables) {
323     if (LT->getFileLineInfoForAddress(
324             {S->getOffsetInFile() + Offset, SectionIndex}, nullptr,
325             DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info))
326       return Info;
327   }
328   return None;
329 }
330 
331 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
332 std::string lld::toString(const InputFile *F) {
333   if (!F)
334     return "<internal>";
335 
336   if (F->ToStringCache.empty()) {
337     if (F->ArchiveName.empty())
338       F->ToStringCache = F->getName();
339     else
340       F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
341   }
342   return F->ToStringCache;
343 }
344 
345 ELFFileBase::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {}
346 
347 template <class ELFT> void ELFFileBase::parseHeader() {
348   if (ELFT::TargetEndianness == support::little)
349     EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
350   else
351     EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
352 
353   EMachine = getObj<ELFT>().getHeader()->e_machine;
354   OSABI = getObj<ELFT>().getHeader()->e_ident[llvm::ELF::EI_OSABI];
355   ABIVersion = getObj<ELFT>().getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
356 }
357 
358 template <class ELFT>
359 void ELFFileBase::initSymtab(ArrayRef<typename ELFT::Shdr> Sections,
360                              const typename ELFT::Shdr *Symtab) {
361   FirstGlobal = Symtab->sh_info;
362   ArrayRef<typename ELFT::Sym> ELFSyms =
363       CHECK(getObj<ELFT>().symbols(Symtab), this);
364   if (FirstGlobal == 0 || FirstGlobal > ELFSyms.size())
365     fatal(toString(this) + ": invalid sh_info in symbol table");
366   this->ELFSyms = reinterpret_cast<const void *>(ELFSyms.data());
367   this->NumELFSyms = ELFSyms.size();
368 
369   StringTable =
370       CHECK(getObj<ELFT>().getStringTableForSymtab(*Symtab, Sections), this);
371 }
372 
373 template <class ELFT>
374 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
375     : ELFFileBase(ObjKind, M) {
376   parseHeader<ELFT>();
377   this->ArchiveName = ArchiveName;
378 }
379 
380 template <class ELFT>
381 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
382   return CHECK(
383       this->getObj().getSectionIndex(&Sym, getELFSyms<ELFT>(), ShndxTable),
384       this);
385 }
386 
387 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
388   if (this->Symbols.empty())
389     return {};
390   return makeArrayRef(this->Symbols).slice(1, this->FirstGlobal - 1);
391 }
392 
393 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
394   return makeArrayRef(this->Symbols).slice(this->FirstGlobal);
395 }
396 
397 template <class ELFT>
398 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
399   // Read a section table. JustSymbols is usually false.
400   if (this->JustSymbols)
401     initializeJustSymbols();
402   else
403     initializeSections(ComdatGroups);
404 
405   // Read a symbol table.
406   initializeSymbols();
407 }
408 
409 // Sections with SHT_GROUP and comdat bits define comdat section groups.
410 // They are identified and deduplicated by group name. This function
411 // returns a group name.
412 template <class ELFT>
413 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
414                                               const Elf_Shdr &Sec) {
415   // Group signatures are stored as symbol names in object files.
416   // sh_info contains a symbol index, so we fetch a symbol and read its name.
417   if (this->getELFSyms<ELFT>().empty())
418     this->initSymtab<ELFT>(
419         Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this));
420 
421   const Elf_Sym *Sym =
422       CHECK(object::getSymbol<ELFT>(this->getELFSyms<ELFT>(), Sec.sh_info), this);
423   StringRef Signature = CHECK(Sym->getName(this->StringTable), this);
424 
425   // As a special case, if a symbol is a section symbol and has no name,
426   // we use a section name as a signature.
427   //
428   // Such SHT_GROUP sections are invalid from the perspective of the ELF
429   // standard, but GNU gold 1.14 (the newest version as of July 2017) or
430   // older produce such sections as outputs for the -r option, so we need
431   // a bug-compatibility.
432   if (Signature.empty() && Sym->getType() == STT_SECTION)
433     return getSectionName(Sec);
434   return Signature;
435 }
436 
437 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
438   // On a regular link we don't merge sections if -O0 (default is -O1). This
439   // sometimes makes the linker significantly faster, although the output will
440   // be bigger.
441   //
442   // Doing the same for -r would create a problem as it would combine sections
443   // with different sh_entsize. One option would be to just copy every SHF_MERGE
444   // section as is to the output. While this would produce a valid ELF file with
445   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
446   // they see two .debug_str. We could have separate logic for combining
447   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
448   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
449   // logic for -r.
450   if (Config->Optimize == 0 && !Config->Relocatable)
451     return false;
452 
453   // A mergeable section with size 0 is useless because they don't have
454   // any data to merge. A mergeable string section with size 0 can be
455   // argued as invalid because it doesn't end with a null character.
456   // We'll avoid a mess by handling them as if they were non-mergeable.
457   if (Sec.sh_size == 0)
458     return false;
459 
460   // Check for sh_entsize. The ELF spec is not clear about the zero
461   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
462   // the section does not hold a table of fixed-size entries". We know
463   // that Rust 1.13 produces a string mergeable section with a zero
464   // sh_entsize. Here we just accept it rather than being picky about it.
465   uint64_t EntSize = Sec.sh_entsize;
466   if (EntSize == 0)
467     return false;
468   if (Sec.sh_size % EntSize)
469     fatal(toString(this) +
470           ": SHF_MERGE section size must be a multiple of sh_entsize");
471 
472   uint64_t Flags = Sec.sh_flags;
473   if (!(Flags & SHF_MERGE))
474     return false;
475   if (Flags & SHF_WRITE)
476     fatal(toString(this) + ": writable SHF_MERGE section is not supported");
477 
478   return true;
479 }
480 
481 // This is for --just-symbols.
482 //
483 // --just-symbols is a very minor feature that allows you to link your
484 // output against other existing program, so that if you load both your
485 // program and the other program into memory, your output can refer the
486 // other program's symbols.
487 //
488 // When the option is given, we link "just symbols". The section table is
489 // initialized with null pointers.
490 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
491   ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
492   this->Sections.resize(ObjSections.size());
493 
494   for (const Elf_Shdr &Sec : ObjSections) {
495     if (Sec.sh_type != SHT_SYMTAB)
496       continue;
497     this->initSymtab<ELFT>(ObjSections, &Sec);
498     return;
499   }
500 }
501 
502 template <class ELFT>
503 void ObjFile<ELFT>::initializeSections(
504     DenseSet<CachedHashStringRef> &ComdatGroups) {
505   const ELFFile<ELFT> &Obj = this->getObj();
506 
507   ArrayRef<Elf_Shdr> ObjSections = CHECK(Obj.sections(), this);
508   uint64_t Size = ObjSections.size();
509   this->Sections.resize(Size);
510   this->SectionStringTable =
511       CHECK(Obj.getSectionStringTable(ObjSections), this);
512 
513   for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
514     if (this->Sections[I] == &InputSection::Discarded)
515       continue;
516     const Elf_Shdr &Sec = ObjSections[I];
517 
518     if (Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
519       CGProfile =
520           check(Obj.template getSectionContentsAsArray<Elf_CGProfile>(&Sec));
521 
522     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
523     // if -r is given, we'll let the final link discard such sections.
524     // This is compatible with GNU.
525     if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
526       if (Sec.sh_type == SHT_LLVM_ADDRSIG) {
527         // We ignore the address-significance table if we know that the object
528         // file was created by objcopy or ld -r. This is because these tools
529         // will reorder the symbols in the symbol table, invalidating the data
530         // in the address-significance table, which refers to symbols by index.
531         if (Sec.sh_link != 0)
532           this->AddrsigSec = &Sec;
533         else if (Config->ICF == ICFLevel::Safe)
534           warn(toString(this) + ": --icf=safe is incompatible with object "
535                                 "files created using objcopy or ld -r");
536       }
537       this->Sections[I] = &InputSection::Discarded;
538       continue;
539     }
540 
541     switch (Sec.sh_type) {
542     case SHT_GROUP: {
543       // De-duplicate section groups by their signatures.
544       StringRef Signature = getShtGroupSignature(ObjSections, Sec);
545       this->Sections[I] = &InputSection::Discarded;
546 
547 
548       ArrayRef<Elf_Word> Entries =
549           CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
550       if (Entries.empty())
551         fatal(toString(this) + ": empty SHT_GROUP");
552 
553       // The first word of a SHT_GROUP section contains flags. Currently,
554       // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
555       // An group with the empty flag doesn't define anything; such sections
556       // are just skipped.
557       if (Entries[0] == 0)
558         continue;
559 
560       if (Entries[0] != GRP_COMDAT)
561         fatal(toString(this) + ": unsupported SHT_GROUP format");
562 
563       bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
564       if (IsNew) {
565         if (Config->Relocatable)
566           this->Sections[I] = createInputSection(Sec);
567         continue;
568       }
569 
570       // Otherwise, discard group members.
571       for (uint32_t SecIndex : Entries.slice(1)) {
572         if (SecIndex >= Size)
573           fatal(toString(this) +
574                 ": invalid section index in group: " + Twine(SecIndex));
575         this->Sections[SecIndex] = &InputSection::Discarded;
576       }
577       break;
578     }
579     case SHT_SYMTAB:
580       this->initSymtab<ELFT>(ObjSections, &Sec);
581       break;
582     case SHT_SYMTAB_SHNDX:
583       ShndxTable = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
584       break;
585     case SHT_STRTAB:
586     case SHT_NULL:
587       break;
588     default:
589       this->Sections[I] = createInputSection(Sec);
590     }
591 
592     // .ARM.exidx sections have a reverse dependency on the InputSection they
593     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
594     if (Sec.sh_flags & SHF_LINK_ORDER) {
595       InputSectionBase *LinkSec = nullptr;
596       if (Sec.sh_link < this->Sections.size())
597         LinkSec = this->Sections[Sec.sh_link];
598       if (!LinkSec)
599         fatal(toString(this) +
600               ": invalid sh_link index: " + Twine(Sec.sh_link));
601 
602       InputSection *IS = cast<InputSection>(this->Sections[I]);
603       LinkSec->DependentSections.push_back(IS);
604       if (!isa<InputSection>(LinkSec))
605         error("a section " + IS->Name +
606               " with SHF_LINK_ORDER should not refer a non-regular "
607               "section: " +
608               toString(LinkSec));
609     }
610   }
611 }
612 
613 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
614 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
615 // the input objects have been compiled.
616 static void updateARMVFPArgs(const ARMAttributeParser &Attributes,
617                              const InputFile *F) {
618   if (!Attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
619     // If an ABI tag isn't present then it is implicitly given the value of 0
620     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
621     // including some in glibc that don't use FP args (and should have value 3)
622     // don't have the attribute so we do not consider an implicit value of 0
623     // as a clash.
624     return;
625 
626   unsigned VFPArgs = Attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
627   ARMVFPArgKind Arg;
628   switch (VFPArgs) {
629   case ARMBuildAttrs::BaseAAPCS:
630     Arg = ARMVFPArgKind::Base;
631     break;
632   case ARMBuildAttrs::HardFPAAPCS:
633     Arg = ARMVFPArgKind::VFP;
634     break;
635   case ARMBuildAttrs::ToolChainFPPCS:
636     // Tool chain specific convention that conforms to neither AAPCS variant.
637     Arg = ARMVFPArgKind::ToolChain;
638     break;
639   case ARMBuildAttrs::CompatibleFPAAPCS:
640     // Object compatible with all conventions.
641     return;
642   default:
643     error(toString(F) + ": unknown Tag_ABI_VFP_args value: " + Twine(VFPArgs));
644     return;
645   }
646   // Follow ld.bfd and error if there is a mix of calling conventions.
647   if (Config->ARMVFPArgs != Arg && Config->ARMVFPArgs != ARMVFPArgKind::Default)
648     error(toString(F) + ": incompatible Tag_ABI_VFP_args");
649   else
650     Config->ARMVFPArgs = Arg;
651 }
652 
653 // The ARM support in lld makes some use of instructions that are not available
654 // on all ARM architectures. Namely:
655 // - Use of BLX instruction for interworking between ARM and Thumb state.
656 // - Use of the extended Thumb branch encoding in relocation.
657 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
658 // The ARM Attributes section contains information about the architecture chosen
659 // at compile time. We follow the convention that if at least one input object
660 // is compiled with an architecture that supports these features then lld is
661 // permitted to use them.
662 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
663   if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
664     return;
665   auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
666   switch (Arch) {
667   case ARMBuildAttrs::Pre_v4:
668   case ARMBuildAttrs::v4:
669   case ARMBuildAttrs::v4T:
670     // Architectures prior to v5 do not support BLX instruction
671     break;
672   case ARMBuildAttrs::v5T:
673   case ARMBuildAttrs::v5TE:
674   case ARMBuildAttrs::v5TEJ:
675   case ARMBuildAttrs::v6:
676   case ARMBuildAttrs::v6KZ:
677   case ARMBuildAttrs::v6K:
678     Config->ARMHasBlx = true;
679     // Architectures used in pre-Cortex processors do not support
680     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
681     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
682     break;
683   default:
684     // All other Architectures have BLX and extended branch encoding
685     Config->ARMHasBlx = true;
686     Config->ARMJ1J2BranchEncoding = true;
687     if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
688       // All Architectures used in Cortex processors with the exception
689       // of v6-M and v6S-M have the MOVT and MOVW instructions.
690       Config->ARMHasMovtMovw = true;
691     break;
692   }
693 }
694 
695 template <class ELFT>
696 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
697   uint32_t Idx = Sec.sh_info;
698   if (Idx >= this->Sections.size())
699     fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
700   InputSectionBase *Target = this->Sections[Idx];
701 
702   // Strictly speaking, a relocation section must be included in the
703   // group of the section it relocates. However, LLVM 3.3 and earlier
704   // would fail to do so, so we gracefully handle that case.
705   if (Target == &InputSection::Discarded)
706     return nullptr;
707 
708   if (!Target)
709     fatal(toString(this) + ": unsupported relocation reference");
710   return Target;
711 }
712 
713 // Create a regular InputSection class that has the same contents
714 // as a given section.
715 static InputSection *toRegularSection(MergeInputSection *Sec) {
716   return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
717                             Sec->data(), Sec->Name);
718 }
719 
720 template <class ELFT>
721 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
722   StringRef Name = getSectionName(Sec);
723 
724   switch (Sec.sh_type) {
725   case SHT_ARM_ATTRIBUTES: {
726     if (Config->EMachine != EM_ARM)
727       break;
728     ARMAttributeParser Attributes;
729     ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
730     Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
731     updateSupportedARMFeatures(Attributes);
732     updateARMVFPArgs(Attributes, this);
733 
734     // FIXME: Retain the first attribute section we see. The eglibc ARM
735     // dynamic loaders require the presence of an attribute section for dlopen
736     // to work. In a full implementation we would merge all attribute sections.
737     if (In.ARMAttributes == nullptr) {
738       In.ARMAttributes = make<InputSection>(*this, Sec, Name);
739       return In.ARMAttributes;
740     }
741     return &InputSection::Discarded;
742   }
743   case SHT_RELA:
744   case SHT_REL: {
745     // Find a relocation target section and associate this section with that.
746     // Target may have been discarded if it is in a different section group
747     // and the group is discarded, even though it's a violation of the
748     // spec. We handle that situation gracefully by discarding dangling
749     // relocation sections.
750     InputSectionBase *Target = getRelocTarget(Sec);
751     if (!Target)
752       return nullptr;
753 
754     // This section contains relocation information.
755     // If -r is given, we do not interpret or apply relocation
756     // but just copy relocation sections to output.
757     if (Config->Relocatable) {
758       InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
759       // We want to add a dependency to target, similar like we do for
760       // -emit-relocs below. This is useful for the case when linker script
761       // contains the "/DISCARD/". It is perhaps uncommon to use a script with
762       // -r, but we faced it in the Linux kernel and have to handle such case
763       // and not to crash.
764       Target->DependentSections.push_back(RelocSec);
765       return RelocSec;
766     }
767 
768     if (Target->FirstRelocation)
769       fatal(toString(this) +
770             ": multiple relocation sections to one section are not supported");
771 
772     // ELF spec allows mergeable sections with relocations, but they are
773     // rare, and it is in practice hard to merge such sections by contents,
774     // because applying relocations at end of linking changes section
775     // contents. So, we simply handle such sections as non-mergeable ones.
776     // Degrading like this is acceptable because section merging is optional.
777     if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
778       Target = toRegularSection(MS);
779       this->Sections[Sec.sh_info] = Target;
780     }
781 
782     if (Sec.sh_type == SHT_RELA) {
783       ArrayRef<Elf_Rela> Rels = CHECK(getObj().relas(&Sec), this);
784       Target->FirstRelocation = Rels.begin();
785       Target->NumRelocations = Rels.size();
786       Target->AreRelocsRela = true;
787     } else {
788       ArrayRef<Elf_Rel> Rels = CHECK(getObj().rels(&Sec), this);
789       Target->FirstRelocation = Rels.begin();
790       Target->NumRelocations = Rels.size();
791       Target->AreRelocsRela = false;
792     }
793     assert(isUInt<31>(Target->NumRelocations));
794 
795     // Relocation sections processed by the linker are usually removed
796     // from the output, so returning `nullptr` for the normal case.
797     // However, if -emit-relocs is given, we need to leave them in the output.
798     // (Some post link analysis tools need this information.)
799     if (Config->EmitRelocs) {
800       InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
801       // We will not emit relocation section if target was discarded.
802       Target->DependentSections.push_back(RelocSec);
803       return RelocSec;
804     }
805     return nullptr;
806   }
807   }
808 
809   // The GNU linker uses .note.GNU-stack section as a marker indicating
810   // that the code in the object file does not expect that the stack is
811   // executable (in terms of NX bit). If all input files have the marker,
812   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
813   // make the stack non-executable. Most object files have this section as
814   // of 2017.
815   //
816   // But making the stack non-executable is a norm today for security
817   // reasons. Failure to do so may result in a serious security issue.
818   // Therefore, we make LLD always add PT_GNU_STACK unless it is
819   // explicitly told to do otherwise (by -z execstack). Because the stack
820   // executable-ness is controlled solely by command line options,
821   // .note.GNU-stack sections are simply ignored.
822   if (Name == ".note.GNU-stack")
823     return &InputSection::Discarded;
824 
825   // Split stacks is a feature to support a discontiguous stack,
826   // commonly used in the programming language Go. For the details,
827   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
828   // for split stack will include a .note.GNU-split-stack section.
829   if (Name == ".note.GNU-split-stack") {
830     if (Config->Relocatable) {
831       error("cannot mix split-stack and non-split-stack in a relocatable link");
832       return &InputSection::Discarded;
833     }
834     this->SplitStack = true;
835     return &InputSection::Discarded;
836   }
837 
838   // An object file cmpiled for split stack, but where some of the
839   // functions were compiled with the no_split_stack_attribute will
840   // include a .note.GNU-no-split-stack section.
841   if (Name == ".note.GNU-no-split-stack") {
842     this->SomeNoSplitStack = true;
843     return &InputSection::Discarded;
844   }
845 
846   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
847   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
848   // sections. Drop those sections to avoid duplicate symbol errors.
849   // FIXME: This is glibc PR20543, we should remove this hack once that has been
850   // fixed for a while.
851   if (Name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
852       Name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
853     return &InputSection::Discarded;
854 
855   // If we are creating a new .build-id section, strip existing .build-id
856   // sections so that the output won't have more than one .build-id.
857   // This is not usually a problem because input object files normally don't
858   // have .build-id sections, but you can create such files by
859   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
860   if (Name == ".note.gnu.build-id" && Config->BuildId != BuildIdKind::None)
861     return &InputSection::Discarded;
862 
863   // The linker merges EH (exception handling) frames and creates a
864   // .eh_frame_hdr section for runtime. So we handle them with a special
865   // class. For relocatable outputs, they are just passed through.
866   if (Name == ".eh_frame" && !Config->Relocatable)
867     return make<EhInputSection>(*this, Sec, Name);
868 
869   if (shouldMerge(Sec))
870     return make<MergeInputSection>(*this, Sec, Name);
871   return make<InputSection>(*this, Sec, Name);
872 }
873 
874 template <class ELFT>
875 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
876   return CHECK(getObj().getSectionName(&Sec, SectionStringTable), this);
877 }
878 
879 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
880   this->Symbols.reserve(this->getELFSyms<ELFT>().size());
881   for (const Elf_Sym &Sym : this->getELFSyms<ELFT>())
882     this->Symbols.push_back(createSymbol(&Sym));
883 }
884 
885 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
886   uint32_t SecIdx = getSectionIndex(*Sym);
887   if (SecIdx >= this->Sections.size())
888     fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
889 
890   InputSectionBase *Sec = this->Sections[SecIdx];
891   uint8_t Binding = Sym->getBinding();
892   uint8_t StOther = Sym->st_other;
893   uint8_t Type = Sym->getType();
894   uint64_t Value = Sym->st_value;
895   uint64_t Size = Sym->st_size;
896 
897   if (Binding == STB_LOCAL) {
898     if (Sym->getType() == STT_FILE)
899       SourceFile = CHECK(Sym->getName(this->StringTable), this);
900 
901     if (this->StringTable.size() <= Sym->st_name)
902       fatal(toString(this) + ": invalid symbol name offset");
903 
904     StringRefZ Name = this->StringTable.data() + Sym->st_name;
905     if (Sym->st_shndx == SHN_UNDEF)
906       return make<Undefined>(this, Name, Binding, StOther, Type);
907     return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
908   }
909 
910   StringRef Name = CHECK(Sym->getName(this->StringTable), this);
911 
912   switch (Sym->st_shndx) {
913   case SHN_UNDEF:
914     return Symtab->addUndefined(Undefined{this, Name, Binding, StOther, Type});
915   case SHN_COMMON:
916     if (Value == 0 || Value >= UINT32_MAX)
917       fatal(toString(this) + ": common symbol '" + Name +
918             "' has invalid alignment: " + Twine(Value));
919     return Symtab->addCommon(
920         CommonSymbol{this, Name, Binding, StOther, Type, Value, Size});
921   }
922 
923   switch (Binding) {
924   default:
925     fatal(toString(this) + ": unexpected binding: " + Twine((int)Binding));
926   case STB_GLOBAL:
927   case STB_WEAK:
928   case STB_GNU_UNIQUE:
929     if (Sec == &InputSection::Discarded)
930       return Symtab->addUndefined(
931           Undefined{this, Name, Binding, StOther, Type});
932     return Symtab->addDefined(
933         Defined{this, Name, Binding, StOther, Type, Value, Size, Sec});
934   }
935 }
936 
937 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
938     : InputFile(ArchiveKind, File->getMemoryBufferRef()),
939       File(std::move(File)) {}
940 
941 void ArchiveFile::parse() {
942   for (const Archive::Symbol &Sym : File->symbols())
943     Symtab->addLazyArchive(LazyArchive{*this, Sym});
944 }
945 
946 // Returns a buffer pointing to a member file containing a given symbol.
947 InputFile *ArchiveFile::fetch(const Archive::Symbol &Sym) {
948   Archive::Child C =
949       CHECK(Sym.getMember(), toString(this) +
950                                  ": could not get the member for symbol " +
951                                  Sym.getName());
952 
953   if (!Seen.insert(C.getChildOffset()).second)
954     return nullptr;
955 
956   MemoryBufferRef MB =
957       CHECK(C.getMemoryBufferRef(),
958             toString(this) +
959                 ": could not get the buffer for the member defining symbol " +
960                 Sym.getName());
961 
962   if (Tar && C.getParent()->isThin())
963     Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), MB.getBuffer());
964 
965   InputFile *File = createObjectFile(
966       MB, getName(), C.getParent()->isThin() ? 0 : C.getChildOffset());
967   File->GroupId = GroupId;
968   return File;
969 }
970 
971 unsigned SharedFile::VernauxNum;
972 
973 SharedFile::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
974     : ELFFileBase(SharedKind, M), SoName(DefaultSoName),
975       IsNeeded(!Config->AsNeeded) {}
976 
977 // Parse the version definitions in the object file if present, and return a
978 // vector whose nth element contains a pointer to the Elf_Verdef for version
979 // identifier n. Version identifiers that are not definitions map to nullptr.
980 template <typename ELFT>
981 static std::vector<const void *> parseVerdefs(const uint8_t *Base,
982                                               const typename ELFT::Shdr *Sec) {
983   if (!Sec)
984     return {};
985 
986   // We cannot determine the largest verdef identifier without inspecting
987   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
988   // sequentially starting from 1, so we predict that the largest identifier
989   // will be VerdefCount.
990   unsigned VerdefCount = Sec->sh_info;
991   std::vector<const void *> Verdefs(VerdefCount + 1);
992 
993   // Build the Verdefs array by following the chain of Elf_Verdef objects
994   // from the start of the .gnu.version_d section.
995   const uint8_t *Verdef = Base + Sec->sh_offset;
996   for (unsigned I = 0; I != VerdefCount; ++I) {
997     auto *CurVerdef = reinterpret_cast<const typename ELFT::Verdef *>(Verdef);
998     Verdef += CurVerdef->vd_next;
999     unsigned VerdefIndex = CurVerdef->vd_ndx;
1000     Verdefs.resize(VerdefIndex + 1);
1001     Verdefs[VerdefIndex] = CurVerdef;
1002   }
1003   return Verdefs;
1004 }
1005 
1006 // We do not usually care about alignments of data in shared object
1007 // files because the loader takes care of it. However, if we promote a
1008 // DSO symbol to point to .bss due to copy relocation, we need to keep
1009 // the original alignment requirements. We infer it in this function.
1010 template <typename ELFT>
1011 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> Sections,
1012                              const typename ELFT::Sym &Sym) {
1013   uint64_t Ret = UINT64_MAX;
1014   if (Sym.st_value)
1015     Ret = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
1016   if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size())
1017     Ret = std::min<uint64_t>(Ret, Sections[Sym.st_shndx].sh_addralign);
1018   return (Ret > UINT32_MAX) ? 0 : Ret;
1019 }
1020 
1021 // Fully parse the shared object file.
1022 //
1023 // This function parses symbol versions. If a DSO has version information,
1024 // the file has a ".gnu.version_d" section which contains symbol version
1025 // definitions. Each symbol is associated to one version through a table in
1026 // ".gnu.version" section. That table is a parallel array for the symbol
1027 // table, and each table entry contains an index in ".gnu.version_d".
1028 //
1029 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1030 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1031 // ".gnu.version_d".
1032 //
1033 // The file format for symbol versioning is perhaps a bit more complicated
1034 // than necessary, but you can easily understand the code if you wrap your
1035 // head around the data structure described above.
1036 template <class ELFT> void SharedFile::parse() {
1037   using Elf_Dyn = typename ELFT::Dyn;
1038   using Elf_Shdr = typename ELFT::Shdr;
1039   using Elf_Sym = typename ELFT::Sym;
1040   using Elf_Verdef = typename ELFT::Verdef;
1041   using Elf_Versym = typename ELFT::Versym;
1042 
1043   ArrayRef<Elf_Dyn> DynamicTags;
1044   const ELFFile<ELFT> Obj = this->getObj<ELFT>();
1045   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1046 
1047   const Elf_Shdr *VersymSec = nullptr;
1048   const Elf_Shdr *VerdefSec = nullptr;
1049 
1050   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1051   for (const Elf_Shdr &Sec : Sections) {
1052     switch (Sec.sh_type) {
1053     default:
1054       continue;
1055     case SHT_DYNSYM:
1056       this->initSymtab<ELFT>(Sections, &Sec);
1057       break;
1058     case SHT_DYNAMIC:
1059       DynamicTags =
1060           CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(&Sec), this);
1061       break;
1062     case SHT_GNU_versym:
1063       VersymSec = &Sec;
1064       break;
1065     case SHT_GNU_verdef:
1066       VerdefSec = &Sec;
1067       break;
1068     }
1069   }
1070 
1071   if (VersymSec && this->getELFSyms<ELFT>().empty()) {
1072     error("SHT_GNU_versym should be associated with symbol table");
1073     return;
1074   }
1075 
1076   // Search for a DT_SONAME tag to initialize this->SoName.
1077   for (const Elf_Dyn &Dyn : DynamicTags) {
1078     if (Dyn.d_tag == DT_NEEDED) {
1079       uint64_t Val = Dyn.getVal();
1080       if (Val >= this->StringTable.size())
1081         fatal(toString(this) + ": invalid DT_NEEDED entry");
1082       DtNeeded.push_back(this->StringTable.data() + Val);
1083     } else if (Dyn.d_tag == DT_SONAME) {
1084       uint64_t Val = Dyn.getVal();
1085       if (Val >= this->StringTable.size())
1086         fatal(toString(this) + ": invalid DT_SONAME entry");
1087       SoName = this->StringTable.data() + Val;
1088     }
1089   }
1090 
1091   // DSOs are uniquified not by filename but by soname.
1092   DenseMap<StringRef, SharedFile *>::iterator It;
1093   bool WasInserted;
1094   std::tie(It, WasInserted) = Symtab->SoNames.try_emplace(SoName, this);
1095 
1096   // If a DSO appears more than once on the command line with and without
1097   // --as-needed, --no-as-needed takes precedence over --as-needed because a
1098   // user can add an extra DSO with --no-as-needed to force it to be added to
1099   // the dependency list.
1100   It->second->IsNeeded |= IsNeeded;
1101   if (!WasInserted)
1102     return;
1103 
1104   SharedFiles.push_back(this);
1105 
1106   Verdefs = parseVerdefs<ELFT>(Obj.base(), VerdefSec);
1107 
1108   // Parse ".gnu.version" section which is a parallel array for the symbol
1109   // table. If a given file doesn't have a ".gnu.version" section, we use
1110   // VER_NDX_GLOBAL.
1111   size_t Size = this->getELFSyms<ELFT>().size() - this->FirstGlobal;
1112   std::vector<uint32_t> Versyms(Size, VER_NDX_GLOBAL);
1113   if (VersymSec) {
1114     ArrayRef<Elf_Versym> Versym =
1115         CHECK(Obj.template getSectionContentsAsArray<Elf_Versym>(VersymSec),
1116               this)
1117             .slice(FirstGlobal);
1118     for (size_t I = 0; I < Size; ++I)
1119       Versyms[I] = Versym[I].vs_index;
1120   }
1121 
1122   // System libraries can have a lot of symbols with versions. Using a
1123   // fixed buffer for computing the versions name (foo@ver) can save a
1124   // lot of allocations.
1125   SmallString<0> VersionedNameBuffer;
1126 
1127   // Add symbols to the symbol table.
1128   ArrayRef<Elf_Sym> Syms = this->getGlobalELFSyms<ELFT>();
1129   for (size_t I = 0; I < Syms.size(); ++I) {
1130     const Elf_Sym &Sym = Syms[I];
1131 
1132     // ELF spec requires that all local symbols precede weak or global
1133     // symbols in each symbol table, and the index of first non-local symbol
1134     // is stored to sh_info. If a local symbol appears after some non-local
1135     // symbol, that's a violation of the spec.
1136     StringRef Name = CHECK(Sym.getName(this->StringTable), this);
1137     if (Sym.getBinding() == STB_LOCAL) {
1138       warn("found local symbol '" + Name +
1139            "' in global part of symbol table in file " + toString(this));
1140       continue;
1141     }
1142 
1143     if (Sym.isUndefined()) {
1144       Symbol *S = Symtab->addUndefined(
1145           Undefined{this, Name, Sym.getBinding(), Sym.st_other, Sym.getType()});
1146       S->ExportDynamic = true;
1147       continue;
1148     }
1149 
1150     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1151     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1152     // workaround for this bug.
1153     uint32_t Idx = Versyms[I] & ~VERSYM_HIDDEN;
1154     if (Config->EMachine == EM_MIPS && Idx == VER_NDX_LOCAL &&
1155         Name == "_gp_disp")
1156       continue;
1157 
1158     uint32_t Alignment = getAlignment<ELFT>(Sections, Sym);
1159     if (!(Versyms[I] & VERSYM_HIDDEN)) {
1160       Symtab->addShared(SharedSymbol{*this, Name, Sym.getBinding(),
1161                                      Sym.st_other, Sym.getType(), Sym.st_value,
1162                                      Sym.st_size, Alignment, Idx});
1163     }
1164 
1165     // Also add the symbol with the versioned name to handle undefined symbols
1166     // with explicit versions.
1167     if (Idx == VER_NDX_GLOBAL)
1168       continue;
1169 
1170     if (Idx >= Verdefs.size() || Idx == VER_NDX_LOCAL) {
1171       error("corrupt input file: version definition index " + Twine(Idx) +
1172             " for symbol " + Name + " is out of bounds\n>>> defined in " +
1173             toString(this));
1174       continue;
1175     }
1176 
1177     StringRef VerName =
1178         this->StringTable.data() +
1179         reinterpret_cast<const Elf_Verdef *>(Verdefs[Idx])->getAux()->vda_name;
1180     VersionedNameBuffer.clear();
1181     Name = (Name + "@" + VerName).toStringRef(VersionedNameBuffer);
1182     Symtab->addShared(SharedSymbol{*this, Saver.save(Name), Sym.getBinding(),
1183                                    Sym.st_other, Sym.getType(), Sym.st_value,
1184                                    Sym.st_size, Alignment, Idx});
1185   }
1186 }
1187 
1188 static ELFKind getBitcodeELFKind(const Triple &T) {
1189   if (T.isLittleEndian())
1190     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1191   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1192 }
1193 
1194 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
1195   switch (T.getArch()) {
1196   case Triple::aarch64:
1197     return EM_AARCH64;
1198   case Triple::amdgcn:
1199   case Triple::r600:
1200     return EM_AMDGPU;
1201   case Triple::arm:
1202   case Triple::thumb:
1203     return EM_ARM;
1204   case Triple::avr:
1205     return EM_AVR;
1206   case Triple::mips:
1207   case Triple::mipsel:
1208   case Triple::mips64:
1209   case Triple::mips64el:
1210     return EM_MIPS;
1211   case Triple::msp430:
1212     return EM_MSP430;
1213   case Triple::ppc:
1214     return EM_PPC;
1215   case Triple::ppc64:
1216   case Triple::ppc64le:
1217     return EM_PPC64;
1218   case Triple::x86:
1219     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
1220   case Triple::x86_64:
1221     return EM_X86_64;
1222   default:
1223     error(Path + ": could not infer e_machine from bitcode target triple " +
1224           T.str());
1225     return EM_NONE;
1226   }
1227 }
1228 
1229 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
1230                          uint64_t OffsetInArchive)
1231     : InputFile(BitcodeKind, MB) {
1232   this->ArchiveName = ArchiveName;
1233 
1234   std::string Path = MB.getBufferIdentifier().str();
1235   if (Config->ThinLTOIndexOnly)
1236     Path = replaceThinLTOSuffix(MB.getBufferIdentifier());
1237 
1238   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1239   // name. If two archives define two members with the same name, this
1240   // causes a collision which result in only one of the objects being taken
1241   // into consideration at LTO time (which very likely causes undefined
1242   // symbols later in the link stage). So we append file offset to make
1243   // filename unique.
1244   StringRef Name = ArchiveName.empty()
1245                        ? Saver.save(Path)
1246                        : Saver.save(ArchiveName + "(" + Path + " at " +
1247                                     utostr(OffsetInArchive) + ")");
1248   MemoryBufferRef MBRef(MB.getBuffer(), Name);
1249 
1250   Obj = CHECK(lto::InputFile::create(MBRef), this);
1251 
1252   Triple T(Obj->getTargetTriple());
1253   EKind = getBitcodeELFKind(T);
1254   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
1255 }
1256 
1257 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
1258   switch (GvVisibility) {
1259   case GlobalValue::DefaultVisibility:
1260     return STV_DEFAULT;
1261   case GlobalValue::HiddenVisibility:
1262     return STV_HIDDEN;
1263   case GlobalValue::ProtectedVisibility:
1264     return STV_PROTECTED;
1265   }
1266   llvm_unreachable("unknown visibility");
1267 }
1268 
1269 template <class ELFT>
1270 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
1271                                    const lto::InputFile::Symbol &ObjSym,
1272                                    BitcodeFile &F) {
1273   StringRef Name = Saver.save(ObjSym.getName());
1274   uint8_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1275   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
1276   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
1277   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
1278 
1279   int C = ObjSym.getComdatIndex();
1280   if (ObjSym.isUndefined() || (C != -1 && !KeptComdats[C])) {
1281     Undefined New(&F, Name, Binding, Visibility, Type);
1282     if (CanOmitFromDynSym)
1283       New.ExportDynamic = false;
1284     return Symtab->addUndefined(New);
1285   }
1286 
1287   if (ObjSym.isCommon())
1288     return Symtab->addCommon(
1289         CommonSymbol{&F, Name, Binding, Visibility, STT_OBJECT,
1290                      ObjSym.getCommonAlignment(), ObjSym.getCommonSize()});
1291 
1292   Defined New(&F, Name, Binding, Visibility, Type, 0, 0, nullptr);
1293   if (CanOmitFromDynSym)
1294     New.ExportDynamic = false;
1295   return Symtab->addDefined(New);
1296 }
1297 
1298 template <class ELFT>
1299 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1300   std::vector<bool> KeptComdats;
1301   for (StringRef S : Obj->getComdatTable())
1302     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1303 
1304   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1305     Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1306 }
1307 
1308 static ELFKind getELFKind(MemoryBufferRef MB, StringRef ArchiveName) {
1309   unsigned char Size;
1310   unsigned char Endian;
1311   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1312 
1313   auto Fatal = [&](StringRef Msg) {
1314     StringRef Filename = MB.getBufferIdentifier();
1315     if (ArchiveName.empty())
1316       fatal(Filename + ": " + Msg);
1317     else
1318       fatal(ArchiveName + "(" + Filename + "): " + Msg);
1319   };
1320 
1321   if (!MB.getBuffer().startswith(ElfMagic))
1322     Fatal("not an ELF file");
1323   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1324     Fatal("corrupted ELF file: invalid data encoding");
1325   if (Size != ELFCLASS32 && Size != ELFCLASS64)
1326     Fatal("corrupted ELF file: invalid file class");
1327 
1328   size_t BufSize = MB.getBuffer().size();
1329   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1330       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1331     Fatal("corrupted ELF file: file is too short");
1332 
1333   if (Size == ELFCLASS32)
1334     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1335   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1336 }
1337 
1338 void BinaryFile::parse() {
1339   ArrayRef<uint8_t> Data = arrayRefFromStringRef(MB.getBuffer());
1340   auto *Section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1341                                      8, Data, ".data");
1342   Sections.push_back(Section);
1343 
1344   // For each input file foo that is embedded to a result as a binary
1345   // blob, we define _binary_foo_{start,end,size} symbols, so that
1346   // user programs can access blobs by name. Non-alphanumeric
1347   // characters in a filename are replaced with underscore.
1348   std::string S = "_binary_" + MB.getBufferIdentifier().str();
1349   for (size_t I = 0; I < S.size(); ++I)
1350     if (!isAlnum(S[I]))
1351       S[I] = '_';
1352 
1353   Symtab->addDefined(Defined{nullptr, Saver.save(S + "_start"), STB_GLOBAL,
1354                              STV_DEFAULT, STT_OBJECT, 0, 0, Section});
1355   Symtab->addDefined(Defined{nullptr, Saver.save(S + "_end"), STB_GLOBAL,
1356                              STV_DEFAULT, STT_OBJECT, Data.size(), 0, Section});
1357   Symtab->addDefined(Defined{nullptr, Saver.save(S + "_size"), STB_GLOBAL,
1358                              STV_DEFAULT, STT_OBJECT, Data.size(), 0, nullptr});
1359 }
1360 
1361 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1362                                  uint64_t OffsetInArchive) {
1363   if (isBitcode(MB))
1364     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1365 
1366   switch (getELFKind(MB, ArchiveName)) {
1367   case ELF32LEKind:
1368     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1369   case ELF32BEKind:
1370     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1371   case ELF64LEKind:
1372     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1373   case ELF64BEKind:
1374     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1375   default:
1376     llvm_unreachable("getELFKind");
1377   }
1378 }
1379 
1380 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1381   auto *F = make<SharedFile>(MB, DefaultSoName);
1382   switch (getELFKind(MB, "")) {
1383   case ELF32LEKind:
1384     F->parseHeader<ELF32LE>();
1385     break;
1386   case ELF32BEKind:
1387     F->parseHeader<ELF32BE>();
1388     break;
1389   case ELF64LEKind:
1390     F->parseHeader<ELF64LE>();
1391     break;
1392   case ELF64BEKind:
1393     F->parseHeader<ELF64BE>();
1394     break;
1395   default:
1396     llvm_unreachable("getELFKind");
1397   }
1398   return F;
1399 }
1400 
1401 MemoryBufferRef LazyObjFile::getBuffer() {
1402   if (AddedToLink)
1403     return MemoryBufferRef();
1404   AddedToLink = true;
1405   return MB;
1406 }
1407 
1408 InputFile *LazyObjFile::fetch() {
1409   MemoryBufferRef MBRef = getBuffer();
1410   if (MBRef.getBuffer().empty())
1411     return nullptr;
1412 
1413   InputFile *File = createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1414   File->GroupId = GroupId;
1415   return File;
1416 }
1417 
1418 template <class ELFT> void LazyObjFile::parse() {
1419   // A lazy object file wraps either a bitcode file or an ELF file.
1420   if (isBitcode(this->MB)) {
1421     std::unique_ptr<lto::InputFile> Obj =
1422         CHECK(lto::InputFile::create(this->MB), this);
1423     for (const lto::InputFile::Symbol &Sym : Obj->symbols()) {
1424       if (Sym.isUndefined())
1425         continue;
1426       Symtab->addLazyObject(LazyObject{*this, Saver.save(Sym.getName())});
1427     }
1428     return;
1429   }
1430 
1431   if (getELFKind(this->MB, ArchiveName) != Config->EKind) {
1432     error("incompatible file: " + this->MB.getBufferIdentifier());
1433     return;
1434   }
1435 
1436   ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(MB.getBuffer()));
1437   ArrayRef<typename ELFT::Shdr> Sections = CHECK(Obj.sections(), this);
1438 
1439   for (const typename ELFT::Shdr &Sec : Sections) {
1440     if (Sec.sh_type != SHT_SYMTAB)
1441       continue;
1442 
1443     typename ELFT::SymRange Syms = CHECK(Obj.symbols(&Sec), this);
1444     uint32_t FirstGlobal = Sec.sh_info;
1445     StringRef StringTable =
1446         CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1447 
1448     for (const typename ELFT::Sym &Sym : Syms.slice(FirstGlobal)) {
1449       if (Sym.st_shndx == SHN_UNDEF)
1450         continue;
1451       Symtab->addLazyObject(
1452           LazyObject{*this, CHECK(Sym.getName(StringTable), this)});
1453     }
1454     return;
1455   }
1456 }
1457 
1458 std::string elf::replaceThinLTOSuffix(StringRef Path) {
1459   StringRef Suffix = Config->ThinLTOObjectSuffixReplace.first;
1460   StringRef Repl = Config->ThinLTOObjectSuffixReplace.second;
1461 
1462   if (Path.consume_back(Suffix))
1463     return (Path + Repl).str();
1464   return Path;
1465 }
1466 
1467 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1468 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1469 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1470 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1471 
1472 template void LazyObjFile::parse<ELF32LE>();
1473 template void LazyObjFile::parse<ELF32BE>();
1474 template void LazyObjFile::parse<ELF64LE>();
1475 template void LazyObjFile::parse<ELF64BE>();
1476 
1477 template class elf::ObjFile<ELF32LE>;
1478 template class elf::ObjFile<ELF32BE>;
1479 template class elf::ObjFile<ELF64LE>;
1480 template class elf::ObjFile<ELF64BE>;
1481 
1482 template void SharedFile::parse<ELF32LE>();
1483 template void SharedFile::parse<ELF32BE>();
1484 template void SharedFile::parse<ELF64LE>();
1485 template void SharedFile::parse<ELF64BE>();
1486