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