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