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