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