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