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