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