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 "Driver.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/DWARF.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Memory.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/Analysis.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/Endian.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/RISCVAttributeParser.h"
31 #include "llvm/Support/TarWriter.h"
32 #include "llvm/Support/raw_ostream.h"
33 
34 using namespace llvm;
35 using namespace llvm::ELF;
36 using namespace llvm::object;
37 using namespace llvm::sys;
38 using namespace llvm::sys::fs;
39 using namespace llvm::support::endian;
40 using namespace lld;
41 using namespace lld::elf;
42 
43 bool InputFile::isInGroup;
44 uint32_t InputFile::nextGroupId;
45 
46 std::vector<ArchiveFile *> elf::archiveFiles;
47 std::vector<BinaryFile *> elf::binaryFiles;
48 std::vector<BitcodeFile *> elf::bitcodeFiles;
49 std::vector<LazyObjFile *> elf::lazyObjFiles;
50 std::vector<InputFile *> elf::objectFiles;
51 std::vector<SharedFile *> elf::sharedFiles;
52 
53 std::unique_ptr<TarWriter> elf::tar;
54 
55 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
56 std::string lld::toString(const InputFile *f) {
57   if (!f)
58     return "<internal>";
59 
60   if (f->toStringCache.empty()) {
61     if (f->archiveName.empty())
62       f->toStringCache = std::string(f->getName());
63     else
64       f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str();
65   }
66   return f->toStringCache;
67 }
68 
69 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
70   unsigned char size;
71   unsigned char endian;
72   std::tie(size, endian) = getElfArchType(mb.getBuffer());
73 
74   auto report = [&](StringRef msg) {
75     StringRef filename = mb.getBufferIdentifier();
76     if (archiveName.empty())
77       fatal(filename + ": " + msg);
78     else
79       fatal(archiveName + "(" + filename + "): " + msg);
80   };
81 
82   if (!mb.getBuffer().startswith(ElfMagic))
83     report("not an ELF file");
84   if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
85     report("corrupted ELF file: invalid data encoding");
86   if (size != ELFCLASS32 && size != ELFCLASS64)
87     report("corrupted ELF file: invalid file class");
88 
89   size_t bufSize = mb.getBuffer().size();
90   if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
91       (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
92     report("corrupted ELF file: file is too short");
93 
94   if (size == ELFCLASS32)
95     return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
96   return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
97 }
98 
99 InputFile::InputFile(Kind k, MemoryBufferRef m)
100     : mb(m), groupId(nextGroupId), fileKind(k) {
101   // All files within the same --{start,end}-group get the same group ID.
102   // Otherwise, a new file will get a new group ID.
103   if (!isInGroup)
104     ++nextGroupId;
105 }
106 
107 Optional<MemoryBufferRef> elf::readFile(StringRef path) {
108   llvm::TimeTraceScope timeScope("Load input files", path);
109 
110   // The --chroot option changes our virtual root directory.
111   // This is useful when you are dealing with files created by --reproduce.
112   if (!config->chroot.empty() && path.startswith("/"))
113     path = saver.save(config->chroot + path);
114 
115   log(path);
116   config->dependencyFiles.insert(llvm::CachedHashString(path));
117 
118   auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
119   if (auto ec = mbOrErr.getError()) {
120     error("cannot open " + path + ": " + ec.message());
121     return None;
122   }
123 
124   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
125   MemoryBufferRef mbref = mb->getMemBufferRef();
126   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
127 
128   if (tar)
129     tar->append(relativeToRoot(path), mbref.getBuffer());
130   return mbref;
131 }
132 
133 // All input object files must be for the same architecture
134 // (e.g. it does not make sense to link x86 object files with
135 // MIPS object files.) This function checks for that error.
136 static bool isCompatible(InputFile *file) {
137   if (!file->isElf() && !isa<BitcodeFile>(file))
138     return true;
139 
140   if (file->ekind == config->ekind && file->emachine == config->emachine) {
141     if (config->emachine != EM_MIPS)
142       return true;
143     if (isMipsN32Abi(file) == config->mipsN32Abi)
144       return true;
145   }
146 
147   StringRef target =
148       !config->bfdname.empty() ? config->bfdname : config->emulation;
149   if (!target.empty()) {
150     error(toString(file) + " is incompatible with " + target);
151     return false;
152   }
153 
154   InputFile *existing;
155   if (!objectFiles.empty())
156     existing = objectFiles[0];
157   else if (!sharedFiles.empty())
158     existing = sharedFiles[0];
159   else if (!bitcodeFiles.empty())
160     existing = bitcodeFiles[0];
161   else
162     llvm_unreachable("Must have -m, OUTPUT_FORMAT or existing input file to "
163                      "determine target emulation");
164 
165   error(toString(file) + " is incompatible with " + toString(existing));
166   return false;
167 }
168 
169 template <class ELFT> static void doParseFile(InputFile *file) {
170   if (!isCompatible(file))
171     return;
172 
173   // Binary file
174   if (auto *f = dyn_cast<BinaryFile>(file)) {
175     binaryFiles.push_back(f);
176     f->parse();
177     return;
178   }
179 
180   // .a file
181   if (auto *f = dyn_cast<ArchiveFile>(file)) {
182     archiveFiles.push_back(f);
183     f->parse();
184     return;
185   }
186 
187   // Lazy object file
188   if (auto *f = dyn_cast<LazyObjFile>(file)) {
189     lazyObjFiles.push_back(f);
190     f->parse<ELFT>();
191     return;
192   }
193 
194   if (config->trace)
195     message(toString(file));
196 
197   // .so file
198   if (auto *f = dyn_cast<SharedFile>(file)) {
199     f->parse<ELFT>();
200     return;
201   }
202 
203   // LLVM bitcode file
204   if (auto *f = dyn_cast<BitcodeFile>(file)) {
205     bitcodeFiles.push_back(f);
206     f->parse<ELFT>();
207     return;
208   }
209 
210   // Regular object file
211   objectFiles.push_back(file);
212   cast<ObjFile<ELFT>>(file)->parse();
213 }
214 
215 // Add symbols in File to the symbol table.
216 void elf::parseFile(InputFile *file) {
217   switch (config->ekind) {
218   case ELF32LEKind:
219     doParseFile<ELF32LE>(file);
220     return;
221   case ELF32BEKind:
222     doParseFile<ELF32BE>(file);
223     return;
224   case ELF64LEKind:
225     doParseFile<ELF64LE>(file);
226     return;
227   case ELF64BEKind:
228     doParseFile<ELF64BE>(file);
229     return;
230   default:
231     llvm_unreachable("unknown ELFT");
232   }
233 }
234 
235 // Concatenates arguments to construct a string representing an error location.
236 static std::string createFileLineMsg(StringRef path, unsigned line) {
237   std::string filename = std::string(path::filename(path));
238   std::string lineno = ":" + std::to_string(line);
239   if (filename == path)
240     return filename + lineno;
241   return filename + lineno + " (" + path.str() + lineno + ")";
242 }
243 
244 template <class ELFT>
245 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
246                                 InputSectionBase &sec, uint64_t offset) {
247   // In DWARF, functions and variables are stored to different places.
248   // First, lookup a function for a given offset.
249   if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
250     return createFileLineMsg(info->FileName, info->Line);
251 
252   // If it failed, lookup again as a variable.
253   if (Optional<std::pair<std::string, unsigned>> fileLine =
254           file.getVariableLoc(sym.getName()))
255     return createFileLineMsg(fileLine->first, fileLine->second);
256 
257   // File.sourceFile contains STT_FILE symbol, and that is a last resort.
258   return std::string(file.sourceFile);
259 }
260 
261 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
262                                  uint64_t offset) {
263   if (kind() != ObjKind)
264     return "";
265   switch (config->ekind) {
266   default:
267     llvm_unreachable("Invalid kind");
268   case ELF32LEKind:
269     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
270   case ELF32BEKind:
271     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
272   case ELF64LEKind:
273     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
274   case ELF64BEKind:
275     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
276   }
277 }
278 
279 StringRef InputFile::getNameForScript() const {
280   if (archiveName.empty())
281     return getName();
282 
283   if (nameForScriptCache.empty())
284     nameForScriptCache = (archiveName + Twine(':') + getName()).str();
285 
286   return nameForScriptCache;
287 }
288 
289 template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
290   llvm::call_once(initDwarf, [this]() {
291     dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
292         std::make_unique<LLDDwarfObj<ELFT>>(this), "",
293         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
294         [&](Error warning) {
295           warn(getName() + ": " + toString(std::move(warning)));
296         }));
297   });
298 
299   return dwarf.get();
300 }
301 
302 // Returns the pair of file name and line number describing location of data
303 // object (variable, array, etc) definition.
304 template <class ELFT>
305 Optional<std::pair<std::string, unsigned>>
306 ObjFile<ELFT>::getVariableLoc(StringRef name) {
307   return getDwarf()->getVariableLoc(name);
308 }
309 
310 // Returns source line information for a given offset
311 // using DWARF debug info.
312 template <class ELFT>
313 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
314                                                   uint64_t offset) {
315   // Detect SectionIndex for specified section.
316   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
317   ArrayRef<InputSectionBase *> sections = s->file->getSections();
318   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
319     if (s == sections[curIndex]) {
320       sectionIndex = curIndex;
321       break;
322     }
323   }
324 
325   return getDwarf()->getDILineInfo(offset, sectionIndex);
326 }
327 
328 ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
329   ekind = getELFKind(mb, "");
330 
331   switch (ekind) {
332   case ELF32LEKind:
333     init<ELF32LE>();
334     break;
335   case ELF32BEKind:
336     init<ELF32BE>();
337     break;
338   case ELF64LEKind:
339     init<ELF64LE>();
340     break;
341   case ELF64BEKind:
342     init<ELF64BE>();
343     break;
344   default:
345     llvm_unreachable("getELFKind");
346   }
347 }
348 
349 template <typename Elf_Shdr>
350 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
351   for (const Elf_Shdr &sec : sections)
352     if (sec.sh_type == type)
353       return &sec;
354   return nullptr;
355 }
356 
357 template <class ELFT> void ELFFileBase::init() {
358   using Elf_Shdr = typename ELFT::Shdr;
359   using Elf_Sym = typename ELFT::Sym;
360 
361   // Initialize trivial attributes.
362   const ELFFile<ELFT> &obj = getObj<ELFT>();
363   emachine = obj.getHeader().e_machine;
364   osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
365   abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
366 
367   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
368 
369   // Find a symbol table.
370   bool isDSO =
371       (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
372   const Elf_Shdr *symtabSec =
373       findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
374 
375   if (!symtabSec)
376     return;
377 
378   // Initialize members corresponding to a symbol table.
379   firstGlobal = symtabSec->sh_info;
380 
381   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
382   if (firstGlobal == 0 || firstGlobal > eSyms.size())
383     fatal(toString(this) + ": invalid sh_info in symbol table");
384 
385   elfSyms = reinterpret_cast<const void *>(eSyms.data());
386   numELFSyms = eSyms.size();
387   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
388 }
389 
390 template <class ELFT>
391 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
392   return CHECK(
393       this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
394       this);
395 }
396 
397 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
398   if (this->symbols.empty())
399     return {};
400   return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
401 }
402 
403 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
404   return makeArrayRef(this->symbols).slice(this->firstGlobal);
405 }
406 
407 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
408   // Read a section table. justSymbols is usually false.
409   if (this->justSymbols)
410     initializeJustSymbols();
411   else
412     initializeSections(ignoreComdats);
413 
414   // Read a symbol table.
415   initializeSymbols();
416 }
417 
418 // Sections with SHT_GROUP and comdat bits define comdat section groups.
419 // They are identified and deduplicated by group name. This function
420 // returns a group name.
421 template <class ELFT>
422 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
423                                               const Elf_Shdr &sec) {
424   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
425   if (sec.sh_info >= symbols.size())
426     fatal(toString(this) + ": invalid symbol index");
427   const typename ELFT::Sym &sym = symbols[sec.sh_info];
428   StringRef signature = CHECK(sym.getName(this->stringTable), this);
429 
430   // As a special case, if a symbol is a section symbol and has no name,
431   // we use a section name as a signature.
432   //
433   // Such SHT_GROUP sections are invalid from the perspective of the ELF
434   // standard, but GNU gold 1.14 (the newest version as of July 2017) or
435   // older produce such sections as outputs for the -r option, so we need
436   // a bug-compatibility.
437   if (signature.empty() && sym.getType() == STT_SECTION)
438     return getSectionName(sec);
439   return signature;
440 }
441 
442 template <class ELFT>
443 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
444   if (!(sec.sh_flags & SHF_MERGE))
445     return false;
446 
447   // On a regular link we don't merge sections if -O0 (default is -O1). This
448   // sometimes makes the linker significantly faster, although the output will
449   // be bigger.
450   //
451   // Doing the same for -r would create a problem as it would combine sections
452   // with different sh_entsize. One option would be to just copy every SHF_MERGE
453   // section as is to the output. While this would produce a valid ELF file with
454   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
455   // they see two .debug_str. We could have separate logic for combining
456   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
457   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
458   // logic for -r.
459   if (config->optimize == 0 && !config->relocatable)
460     return false;
461 
462   // A mergeable section with size 0 is useless because they don't have
463   // any data to merge. A mergeable string section with size 0 can be
464   // argued as invalid because it doesn't end with a null character.
465   // We'll avoid a mess by handling them as if they were non-mergeable.
466   if (sec.sh_size == 0)
467     return false;
468 
469   // Check for sh_entsize. The ELF spec is not clear about the zero
470   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
471   // the section does not hold a table of fixed-size entries". We know
472   // that Rust 1.13 produces a string mergeable section with a zero
473   // sh_entsize. Here we just accept it rather than being picky about it.
474   uint64_t entSize = sec.sh_entsize;
475   if (entSize == 0)
476     return false;
477   if (sec.sh_size % entSize)
478     fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
479           Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
480           Twine(entSize) + ")");
481 
482   if (sec.sh_flags & SHF_WRITE)
483     fatal(toString(this) + ":(" + name +
484           "): writable SHF_MERGE section is not supported");
485 
486   return true;
487 }
488 
489 // This is for --just-symbols.
490 //
491 // --just-symbols is a very minor feature that allows you to link your
492 // output against other existing program, so that if you load both your
493 // program and the other program into memory, your output can refer the
494 // other program's symbols.
495 //
496 // When the option is given, we link "just symbols". The section table is
497 // initialized with null pointers.
498 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
499   ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
500   this->sections.resize(sections.size());
501 }
502 
503 // An ELF object file may contain a `.deplibs` section. If it exists, the
504 // section contains a list of library specifiers such as `m` for libm. This
505 // function resolves a given name by finding the first matching library checking
506 // the various ways that a library can be specified to LLD. This ELF extension
507 // is a form of autolinking and is called `dependent libraries`. It is currently
508 // unique to LLVM and lld.
509 static void addDependentLibrary(StringRef specifier, const InputFile *f) {
510   if (!config->dependentLibraries)
511     return;
512   if (fs::exists(specifier))
513     driver->addFile(specifier, /*withLOption=*/false);
514   else if (Optional<std::string> s = findFromSearchPaths(specifier))
515     driver->addFile(*s, /*withLOption=*/true);
516   else if (Optional<std::string> s = searchLibraryBaseName(specifier))
517     driver->addFile(*s, /*withLOption=*/true);
518   else
519     error(toString(f) +
520           ": unable to find library from dependent library specifier: " +
521           specifier);
522 }
523 
524 // Record the membership of a section group so that in the garbage collection
525 // pass, section group members are kept or discarded as a unit.
526 template <class ELFT>
527 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
528                                ArrayRef<typename ELFT::Word> entries) {
529   bool hasAlloc = false;
530   for (uint32_t index : entries.slice(1)) {
531     if (index >= sections.size())
532       return;
533     if (InputSectionBase *s = sections[index])
534       if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
535         hasAlloc = true;
536   }
537 
538   // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
539   // collection. See the comment in markLive(). This rule retains .debug_types
540   // and .rela.debug_types.
541   if (!hasAlloc)
542     return;
543 
544   // Connect the members in a circular doubly-linked list via
545   // nextInSectionGroup.
546   InputSectionBase *head;
547   InputSectionBase *prev = nullptr;
548   for (uint32_t index : entries.slice(1)) {
549     InputSectionBase *s = sections[index];
550     if (!s || s == &InputSection::discarded)
551       continue;
552     if (prev)
553       prev->nextInSectionGroup = s;
554     else
555       head = s;
556     prev = s;
557   }
558   if (prev)
559     prev->nextInSectionGroup = head;
560 }
561 
562 template <class ELFT>
563 void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
564   const ELFFile<ELFT> &obj = this->getObj();
565 
566   ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
567   uint64_t size = objSections.size();
568   this->sections.resize(size);
569   this->sectionStringTable =
570       CHECK(obj.getSectionStringTable(objSections), this);
571 
572   std::vector<ArrayRef<Elf_Word>> selectedGroups;
573 
574   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
575     if (this->sections[i] == &InputSection::discarded)
576       continue;
577     const Elf_Shdr &sec = objSections[i];
578 
579     if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
580       cgProfile =
581           check(obj.template getSectionContentsAsArray<Elf_CGProfile>(sec));
582 
583     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
584     // if -r is given, we'll let the final link discard such sections.
585     // This is compatible with GNU.
586     if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
587       if (sec.sh_type == SHT_LLVM_ADDRSIG) {
588         // We ignore the address-significance table if we know that the object
589         // file was created by objcopy or ld -r. This is because these tools
590         // will reorder the symbols in the symbol table, invalidating the data
591         // in the address-significance table, which refers to symbols by index.
592         if (sec.sh_link != 0)
593           this->addrsigSec = &sec;
594         else if (config->icf == ICFLevel::Safe)
595           warn(toString(this) +
596                ": --icf=safe conservatively ignores "
597                "SHT_LLVM_ADDRSIG [index " +
598                Twine(i) +
599                "] with sh_link=0 "
600                "(likely created using objcopy or ld -r)");
601       }
602       this->sections[i] = &InputSection::discarded;
603       continue;
604     }
605 
606     switch (sec.sh_type) {
607     case SHT_GROUP: {
608       // De-duplicate section groups by their signatures.
609       StringRef signature = getShtGroupSignature(objSections, sec);
610       this->sections[i] = &InputSection::discarded;
611 
612 
613       ArrayRef<Elf_Word> entries =
614           CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
615       if (entries.empty())
616         fatal(toString(this) + ": empty SHT_GROUP");
617 
618       // The first word of a SHT_GROUP section contains flags. Currently,
619       // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
620       // An group with the empty flag doesn't define anything; such sections
621       // are just skipped.
622       if (entries[0] == 0)
623         continue;
624 
625       if (entries[0] != GRP_COMDAT)
626         fatal(toString(this) + ": unsupported SHT_GROUP format");
627 
628       bool isNew =
629           ignoreComdats ||
630           symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
631               .second;
632       if (isNew) {
633         if (config->relocatable)
634           this->sections[i] = createInputSection(sec);
635         selectedGroups.push_back(entries);
636         continue;
637       }
638 
639       // Otherwise, discard group members.
640       for (uint32_t secIndex : entries.slice(1)) {
641         if (secIndex >= size)
642           fatal(toString(this) +
643                 ": invalid section index in group: " + Twine(secIndex));
644         this->sections[secIndex] = &InputSection::discarded;
645       }
646       break;
647     }
648     case SHT_SYMTAB_SHNDX:
649       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
650       break;
651     case SHT_SYMTAB:
652     case SHT_STRTAB:
653     case SHT_REL:
654     case SHT_RELA:
655     case SHT_NULL:
656       break;
657     default:
658       this->sections[i] = createInputSection(sec);
659     }
660   }
661 
662   // We have a second loop. It is used to:
663   // 1) handle SHF_LINK_ORDER sections.
664   // 2) create SHT_REL[A] sections. In some cases the section header index of a
665   //    relocation section may be smaller than that of the relocated section. In
666   //    such cases, the relocation section would attempt to reference a target
667   //    section that has not yet been created. For simplicity, delay creation of
668   //    relocation sections until now.
669   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
670     if (this->sections[i] == &InputSection::discarded)
671       continue;
672     const Elf_Shdr &sec = objSections[i];
673 
674     if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA)
675       this->sections[i] = createInputSection(sec);
676 
677     // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
678     // the flag.
679     if (!(sec.sh_flags & SHF_LINK_ORDER) || !sec.sh_link)
680       continue;
681 
682     InputSectionBase *linkSec = nullptr;
683     if (sec.sh_link < this->sections.size())
684       linkSec = this->sections[sec.sh_link];
685     if (!linkSec)
686       fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
687 
688     // A SHF_LINK_ORDER section is discarded if its linked-to section is
689     // discarded.
690     InputSection *isec = cast<InputSection>(this->sections[i]);
691     linkSec->dependentSections.push_back(isec);
692     if (!isa<InputSection>(linkSec))
693       error("a section " + isec->name +
694             " with SHF_LINK_ORDER should not refer a non-regular section: " +
695             toString(linkSec));
696   }
697 
698   for (ArrayRef<Elf_Word> entries : selectedGroups)
699     handleSectionGroup<ELFT>(this->sections, entries);
700 }
701 
702 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
703 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
704 // the input objects have been compiled.
705 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
706                              const InputFile *f) {
707   Optional<unsigned> attr =
708       attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
709   if (!attr.hasValue())
710     // If an ABI tag isn't present then it is implicitly given the value of 0
711     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
712     // including some in glibc that don't use FP args (and should have value 3)
713     // don't have the attribute so we do not consider an implicit value of 0
714     // as a clash.
715     return;
716 
717   unsigned vfpArgs = attr.getValue();
718   ARMVFPArgKind arg;
719   switch (vfpArgs) {
720   case ARMBuildAttrs::BaseAAPCS:
721     arg = ARMVFPArgKind::Base;
722     break;
723   case ARMBuildAttrs::HardFPAAPCS:
724     arg = ARMVFPArgKind::VFP;
725     break;
726   case ARMBuildAttrs::ToolChainFPPCS:
727     // Tool chain specific convention that conforms to neither AAPCS variant.
728     arg = ARMVFPArgKind::ToolChain;
729     break;
730   case ARMBuildAttrs::CompatibleFPAAPCS:
731     // Object compatible with all conventions.
732     return;
733   default:
734     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
735     return;
736   }
737   // Follow ld.bfd and error if there is a mix of calling conventions.
738   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
739     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
740   else
741     config->armVFPArgs = arg;
742 }
743 
744 // The ARM support in lld makes some use of instructions that are not available
745 // on all ARM architectures. Namely:
746 // - Use of BLX instruction for interworking between ARM and Thumb state.
747 // - Use of the extended Thumb branch encoding in relocation.
748 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
749 // The ARM Attributes section contains information about the architecture chosen
750 // at compile time. We follow the convention that if at least one input object
751 // is compiled with an architecture that supports these features then lld is
752 // permitted to use them.
753 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
754   Optional<unsigned> attr =
755       attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
756   if (!attr.hasValue())
757     return;
758   auto arch = attr.getValue();
759   switch (arch) {
760   case ARMBuildAttrs::Pre_v4:
761   case ARMBuildAttrs::v4:
762   case ARMBuildAttrs::v4T:
763     // Architectures prior to v5 do not support BLX instruction
764     break;
765   case ARMBuildAttrs::v5T:
766   case ARMBuildAttrs::v5TE:
767   case ARMBuildAttrs::v5TEJ:
768   case ARMBuildAttrs::v6:
769   case ARMBuildAttrs::v6KZ:
770   case ARMBuildAttrs::v6K:
771     config->armHasBlx = true;
772     // Architectures used in pre-Cortex processors do not support
773     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
774     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
775     break;
776   default:
777     // All other Architectures have BLX and extended branch encoding
778     config->armHasBlx = true;
779     config->armJ1J2BranchEncoding = true;
780     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
781       // All Architectures used in Cortex processors with the exception
782       // of v6-M and v6S-M have the MOVT and MOVW instructions.
783       config->armHasMovtMovw = true;
784     break;
785   }
786 }
787 
788 // If a source file is compiled with x86 hardware-assisted call flow control
789 // enabled, the generated object file contains feature flags indicating that
790 // fact. This function reads the feature flags and returns it.
791 //
792 // Essentially we want to read a single 32-bit value in this function, but this
793 // function is rather complicated because the value is buried deep inside a
794 // .note.gnu.property section.
795 //
796 // The section consists of one or more NOTE records. Each NOTE record consists
797 // of zero or more type-length-value fields. We want to find a field of a
798 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
799 // the ABI is unnecessarily complicated.
800 template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) {
801   using Elf_Nhdr = typename ELFT::Nhdr;
802   using Elf_Note = typename ELFT::Note;
803 
804   uint32_t featuresSet = 0;
805   ArrayRef<uint8_t> data = sec.data();
806   auto reportFatal = [&](const uint8_t *place, const char *msg) {
807     fatal(toString(sec.file) + ":(" + sec.name + "+0x" +
808           Twine::utohexstr(place - sec.data().data()) + "): " + msg);
809   };
810   while (!data.empty()) {
811     // Read one NOTE record.
812     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
813     if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize())
814       reportFatal(data.data(), "data is too short");
815 
816     Elf_Note note(*nhdr);
817     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
818       data = data.slice(nhdr->getSize());
819       continue;
820     }
821 
822     uint32_t featureAndType = config->emachine == EM_AARCH64
823                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
824                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
825 
826     // Read a body of a NOTE record, which consists of type-length-value fields.
827     ArrayRef<uint8_t> desc = note.getDesc();
828     while (!desc.empty()) {
829       const uint8_t *place = desc.data();
830       if (desc.size() < 8)
831         reportFatal(place, "program property is too short");
832       uint32_t type = read32<ELFT::TargetEndianness>(desc.data());
833       uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4);
834       desc = desc.slice(8);
835       if (desc.size() < size)
836         reportFatal(place, "program property is too short");
837 
838       if (type == featureAndType) {
839         // We found a FEATURE_1_AND field. There may be more than one of these
840         // in a .note.gnu.property section, for a relocatable object we
841         // accumulate the bits set.
842         if (size < 4)
843           reportFatal(place, "FEATURE_1_AND entry is too short");
844         featuresSet |= read32<ELFT::TargetEndianness>(desc.data());
845       }
846 
847       // Padding is present in the note descriptor, if necessary.
848       desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
849     }
850 
851     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
852     data = data.slice(nhdr->getSize());
853   }
854 
855   return featuresSet;
856 }
857 
858 template <class ELFT>
859 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
860   uint32_t idx = sec.sh_info;
861   if (idx >= this->sections.size())
862     fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
863   InputSectionBase *target = this->sections[idx];
864 
865   // Strictly speaking, a relocation section must be included in the
866   // group of the section it relocates. However, LLVM 3.3 and earlier
867   // would fail to do so, so we gracefully handle that case.
868   if (target == &InputSection::discarded)
869     return nullptr;
870 
871   if (!target)
872     fatal(toString(this) + ": unsupported relocation reference");
873   return target;
874 }
875 
876 // Create a regular InputSection class that has the same contents
877 // as a given section.
878 static InputSection *toRegularSection(MergeInputSection *sec) {
879   return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
880                             sec->data(), sec->name);
881 }
882 
883 template <class ELFT>
884 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
885   StringRef name = getSectionName(sec);
886 
887   if (config->emachine == EM_ARM && sec.sh_type == SHT_ARM_ATTRIBUTES) {
888     ARMAttributeParser attributes;
889     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec));
890     if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
891                                                  ? support::little
892                                                  : support::big)) {
893       auto *isec = make<InputSection>(*this, sec, name);
894       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
895     } else {
896       updateSupportedARMFeatures(attributes);
897       updateARMVFPArgs(attributes, this);
898 
899       // FIXME: Retain the first attribute section we see. The eglibc ARM
900       // dynamic loaders require the presence of an attribute section for dlopen
901       // to work. In a full implementation we would merge all attribute
902       // sections.
903       if (in.attributes == nullptr) {
904         in.attributes = make<InputSection>(*this, sec, name);
905         return in.attributes;
906       }
907       return &InputSection::discarded;
908     }
909   }
910 
911   if (config->emachine == EM_RISCV && sec.sh_type == SHT_RISCV_ATTRIBUTES) {
912     RISCVAttributeParser attributes;
913     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec));
914     if (Error e = attributes.parse(contents, support::little)) {
915       auto *isec = make<InputSection>(*this, sec, name);
916       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
917     } else {
918       // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is
919       // present.
920 
921       // FIXME: Retain the first attribute section we see. Tools such as
922       // llvm-objdump make use of the attribute section to determine which
923       // standard extensions to enable. In a full implementation we would merge
924       // all attribute sections.
925       if (in.attributes == nullptr) {
926         in.attributes = make<InputSection>(*this, sec, name);
927         return in.attributes;
928       }
929       return &InputSection::discarded;
930     }
931   }
932 
933   switch (sec.sh_type) {
934   case SHT_LLVM_DEPENDENT_LIBRARIES: {
935     if (config->relocatable)
936       break;
937     ArrayRef<char> data =
938         CHECK(this->getObj().template getSectionContentsAsArray<char>(sec), this);
939     if (!data.empty() && data.back() != '\0') {
940       error(toString(this) +
941             ": corrupted dependent libraries section (unterminated string): " +
942             name);
943       return &InputSection::discarded;
944     }
945     for (const char *d = data.begin(), *e = data.end(); d < e;) {
946       StringRef s(d);
947       addDependentLibrary(s, this);
948       d += s.size() + 1;
949     }
950     return &InputSection::discarded;
951   }
952   case SHT_RELA:
953   case SHT_REL: {
954     // Find a relocation target section and associate this section with that.
955     // Target may have been discarded if it is in a different section group
956     // and the group is discarded, even though it's a violation of the
957     // spec. We handle that situation gracefully by discarding dangling
958     // relocation sections.
959     InputSectionBase *target = getRelocTarget(sec);
960     if (!target)
961       return nullptr;
962 
963     // ELF spec allows mergeable sections with relocations, but they are
964     // rare, and it is in practice hard to merge such sections by contents,
965     // because applying relocations at end of linking changes section
966     // contents. So, we simply handle such sections as non-mergeable ones.
967     // Degrading like this is acceptable because section merging is optional.
968     if (auto *ms = dyn_cast<MergeInputSection>(target)) {
969       target = toRegularSection(ms);
970       this->sections[sec.sh_info] = target;
971     }
972 
973     if (target->firstRelocation)
974       fatal(toString(this) +
975             ": multiple relocation sections to one section are not supported");
976 
977     if (sec.sh_type == SHT_RELA) {
978       ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(sec), this);
979       target->firstRelocation = rels.begin();
980       target->numRelocations = rels.size();
981       target->areRelocsRela = true;
982     } else {
983       ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(sec), this);
984       target->firstRelocation = rels.begin();
985       target->numRelocations = rels.size();
986       target->areRelocsRela = false;
987     }
988     assert(isUInt<31>(target->numRelocations));
989 
990     // Relocation sections are usually removed from the output, so return
991     // `nullptr` for the normal case. However, if -r or --emit-relocs is
992     // specified, we need to copy them to the output. (Some post link analysis
993     // tools specify --emit-relocs to obtain the information.)
994     if (!config->relocatable && !config->emitRelocs)
995       return nullptr;
996     InputSection *relocSec = make<InputSection>(*this, sec, name);
997     // If the relocated section is discarded (due to /DISCARD/ or
998     // --gc-sections), the relocation section should be discarded as well.
999     target->dependentSections.push_back(relocSec);
1000     return relocSec;
1001   }
1002   }
1003 
1004   // The GNU linker uses .note.GNU-stack section as a marker indicating
1005   // that the code in the object file does not expect that the stack is
1006   // executable (in terms of NX bit). If all input files have the marker,
1007   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
1008   // make the stack non-executable. Most object files have this section as
1009   // of 2017.
1010   //
1011   // But making the stack non-executable is a norm today for security
1012   // reasons. Failure to do so may result in a serious security issue.
1013   // Therefore, we make LLD always add PT_GNU_STACK unless it is
1014   // explicitly told to do otherwise (by -z execstack). Because the stack
1015   // executable-ness is controlled solely by command line options,
1016   // .note.GNU-stack sections are simply ignored.
1017   if (name == ".note.GNU-stack")
1018     return &InputSection::discarded;
1019 
1020   // Object files that use processor features such as Intel Control-Flow
1021   // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
1022   // .note.gnu.property section containing a bitfield of feature bits like the
1023   // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
1024   //
1025   // Since we merge bitmaps from multiple object files to create a new
1026   // .note.gnu.property containing a single AND'ed bitmap, we discard an input
1027   // file's .note.gnu.property section.
1028   if (name == ".note.gnu.property") {
1029     this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name));
1030     return &InputSection::discarded;
1031   }
1032 
1033   // Split stacks is a feature to support a discontiguous stack,
1034   // commonly used in the programming language Go. For the details,
1035   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
1036   // for split stack will include a .note.GNU-split-stack section.
1037   if (name == ".note.GNU-split-stack") {
1038     if (config->relocatable) {
1039       error("cannot mix split-stack and non-split-stack in a relocatable link");
1040       return &InputSection::discarded;
1041     }
1042     this->splitStack = true;
1043     return &InputSection::discarded;
1044   }
1045 
1046   // An object file cmpiled for split stack, but where some of the
1047   // functions were compiled with the no_split_stack_attribute will
1048   // include a .note.GNU-no-split-stack section.
1049   if (name == ".note.GNU-no-split-stack") {
1050     this->someNoSplitStack = true;
1051     return &InputSection::discarded;
1052   }
1053 
1054   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1055   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1056   // sections. Drop those sections to avoid duplicate symbol errors.
1057   // FIXME: This is glibc PR20543, we should remove this hack once that has been
1058   // fixed for a while.
1059   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1060       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1061     return &InputSection::discarded;
1062 
1063   // If we are creating a new .build-id section, strip existing .build-id
1064   // sections so that the output won't have more than one .build-id.
1065   // This is not usually a problem because input object files normally don't
1066   // have .build-id sections, but you can create such files by
1067   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1068   if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
1069     return &InputSection::discarded;
1070 
1071   // The linker merges EH (exception handling) frames and creates a
1072   // .eh_frame_hdr section for runtime. So we handle them with a special
1073   // class. For relocatable outputs, they are just passed through.
1074   if (name == ".eh_frame" && !config->relocatable)
1075     return make<EhInputSection>(*this, sec, name);
1076 
1077   if (shouldMerge(sec, name))
1078     return make<MergeInputSection>(*this, sec, name);
1079   return make<InputSection>(*this, sec, name);
1080 }
1081 
1082 template <class ELFT>
1083 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1084   return CHECK(getObj().getSectionName(sec, sectionStringTable), this);
1085 }
1086 
1087 // Initialize this->Symbols. this->Symbols is a parallel array as
1088 // its corresponding ELF symbol table.
1089 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1090   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1091   this->symbols.resize(eSyms.size());
1092 
1093   // Fill in InputFile::symbols. Some entries have been initialized
1094   // because of LazyObjFile.
1095   for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
1096     if (this->symbols[i])
1097       continue;
1098     const Elf_Sym &eSym = eSyms[i];
1099     uint32_t secIdx = getSectionIndex(eSym);
1100     if (secIdx >= this->sections.size())
1101       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1102     if (eSym.getBinding() != STB_LOCAL) {
1103       if (i < firstGlobal)
1104         error(toString(this) + ": non-local symbol (" + Twine(i) +
1105               ") found at index < .symtab's sh_info (" + Twine(firstGlobal) +
1106               ")");
1107       this->symbols[i] =
1108           symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1109       continue;
1110     }
1111 
1112     // Handle local symbols. Local symbols are not added to the symbol
1113     // table because they are not visible from other object files. We
1114     // allocate symbol instances and add their pointers to symbols.
1115     if (i >= firstGlobal)
1116       errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) +
1117                   ") found at index >= .symtab's sh_info (" +
1118                   Twine(firstGlobal) + ")");
1119 
1120     InputSectionBase *sec = this->sections[secIdx];
1121     uint8_t type = eSym.getType();
1122     if (type == STT_FILE)
1123       sourceFile = CHECK(eSym.getName(this->stringTable), this);
1124     if (this->stringTable.size() <= eSym.st_name)
1125       fatal(toString(this) + ": invalid symbol name offset");
1126     StringRefZ name = this->stringTable.data() + eSym.st_name;
1127 
1128     if (eSym.st_shndx == SHN_UNDEF)
1129       this->symbols[i] =
1130           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type);
1131     else if (sec == &InputSection::discarded)
1132       this->symbols[i] =
1133           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type,
1134                           /*discardedSecIdx=*/secIdx);
1135     else
1136       this->symbols[i] = make<Defined>(this, name, STB_LOCAL, eSym.st_other,
1137                                        type, eSym.st_value, eSym.st_size, sec);
1138   }
1139 
1140   // Symbol resolution of non-local symbols.
1141   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1142     const Elf_Sym &eSym = eSyms[i];
1143     uint8_t binding = eSym.getBinding();
1144     if (binding == STB_LOCAL)
1145       continue; // Errored above.
1146 
1147     uint32_t secIdx = getSectionIndex(eSym);
1148     InputSectionBase *sec = this->sections[secIdx];
1149     uint8_t stOther = eSym.st_other;
1150     uint8_t type = eSym.getType();
1151     uint64_t value = eSym.st_value;
1152     uint64_t size = eSym.st_size;
1153     StringRefZ name = this->stringTable.data() + eSym.st_name;
1154 
1155     // Handle global undefined symbols.
1156     if (eSym.st_shndx == SHN_UNDEF) {
1157       this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1158       this->symbols[i]->referenced = true;
1159       continue;
1160     }
1161 
1162     // Handle global common symbols.
1163     if (eSym.st_shndx == SHN_COMMON) {
1164       if (value == 0 || value >= UINT32_MAX)
1165         fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1166               "' has invalid alignment: " + Twine(value));
1167       this->symbols[i]->resolve(
1168           CommonSymbol{this, name, binding, stOther, type, value, size});
1169       continue;
1170     }
1171 
1172     // If a defined symbol is in a discarded section, handle it as if it
1173     // were an undefined symbol. Such symbol doesn't comply with the
1174     // standard, but in practice, a .eh_frame often directly refer
1175     // COMDAT member sections, and if a comdat group is discarded, some
1176     // defined symbol in a .eh_frame becomes dangling symbols.
1177     if (sec == &InputSection::discarded) {
1178       Undefined und{this, name, binding, stOther, type, secIdx};
1179       Symbol *sym = this->symbols[i];
1180       // !ArchiveFile::parsed or LazyObjFile::fetched means that the file
1181       // containing this object has not finished processing, i.e. this symbol is
1182       // a result of a lazy symbol fetch. We should demote the lazy symbol to an
1183       // Undefined so that any relocations outside of the group to it will
1184       // trigger a discarded section error.
1185       if ((sym->symbolKind == Symbol::LazyArchiveKind &&
1186            !cast<ArchiveFile>(sym->file)->parsed) ||
1187           (sym->symbolKind == Symbol::LazyObjectKind &&
1188            cast<LazyObjFile>(sym->file)->fetched))
1189         sym->replace(und);
1190       else
1191         sym->resolve(und);
1192       continue;
1193     }
1194 
1195     // Handle global defined symbols.
1196     if (binding == STB_GLOBAL || binding == STB_WEAK ||
1197         binding == STB_GNU_UNIQUE) {
1198       this->symbols[i]->resolve(
1199           Defined{this, name, binding, stOther, type, value, size, sec});
1200       continue;
1201     }
1202 
1203     fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1204   }
1205 }
1206 
1207 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
1208     : InputFile(ArchiveKind, file->getMemoryBufferRef()),
1209       file(std::move(file)) {}
1210 
1211 void ArchiveFile::parse() {
1212   for (const Archive::Symbol &sym : file->symbols())
1213     symtab->addSymbol(LazyArchive{*this, sym});
1214 
1215   // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this
1216   // archive has been processed.
1217   parsed = true;
1218 }
1219 
1220 // Returns a buffer pointing to a member file containing a given symbol.
1221 void ArchiveFile::fetch(const Archive::Symbol &sym) {
1222   Archive::Child c =
1223       CHECK(sym.getMember(), toString(this) +
1224                                  ": could not get the member for symbol " +
1225                                  toELFString(sym));
1226 
1227   if (!seen.insert(c.getChildOffset()).second)
1228     return;
1229 
1230   MemoryBufferRef mb =
1231       CHECK(c.getMemoryBufferRef(),
1232             toString(this) +
1233                 ": could not get the buffer for the member defining symbol " +
1234                 toELFString(sym));
1235 
1236   if (tar && c.getParent()->isThin())
1237     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
1238 
1239   InputFile *file = createObjectFile(mb, getName(), c.getChildOffset());
1240   file->groupId = groupId;
1241   parseFile(file);
1242 }
1243 
1244 // The handling of tentative definitions (COMMON symbols) in archives is murky.
1245 // A tentative defintion will be promoted to a global definition if there are no
1246 // non-tentative definitions to dominate it. When we hold a tentative definition
1247 // to a symbol and are inspecting archive memebers for inclusion there are 2
1248 // ways we can proceed:
1249 //
1250 // 1) Consider the tentative definition a 'real' definition (ie promotion from
1251 //    tentative to real definition has already happened) and not inspect
1252 //    archive members for Global/Weak definitions to replace the tentative
1253 //    definition. An archive member would only be included if it satisfies some
1254 //    other undefined symbol. This is the behavior Gold uses.
1255 //
1256 // 2) Consider the tentative definition as still undefined (ie the promotion to
1257 //    a real definiton happens only after all symbol resolution is done).
1258 //    The linker searches archive memebers for global or weak definitions to
1259 //    replace the tentative definition with. This is the behavior used by
1260 //    GNU ld.
1261 //
1262 //  The second behavior is inherited from SysVR4, which based it on the FORTRAN
1263 //  COMMON BLOCK model. This behavior is needed for proper initalizations in old
1264 //  (pre F90) FORTRAN code that is packaged into an archive.
1265 //
1266 //  The following functions search archive members for defintions to replace
1267 //  tentative defintions (implementing behavior 2).
1268 static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1269                                   StringRef archiveName) {
1270   IRSymtabFile symtabFile = check(readIRSymtab(mb));
1271   for (const irsymtab::Reader::SymbolRef &sym :
1272        symtabFile.TheReader.symbols()) {
1273     if (sym.isGlobal() && sym.getName() == symName)
1274       return !sym.isUndefined() && !sym.isCommon();
1275   }
1276   return false;
1277 }
1278 
1279 template <class ELFT>
1280 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1281                            StringRef archiveName) {
1282   ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName);
1283   StringRef stringtable = obj->getStringTable();
1284 
1285   for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1286     Expected<StringRef> name = sym.getName(stringtable);
1287     if (name && name.get() == symName)
1288       return sym.isDefined() && !sym.isCommon();
1289   }
1290   return false;
1291 }
1292 
1293 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1294                            StringRef archiveName) {
1295   switch (getELFKind(mb, archiveName)) {
1296   case ELF32LEKind:
1297     return isNonCommonDef<ELF32LE>(mb, symName, archiveName);
1298   case ELF32BEKind:
1299     return isNonCommonDef<ELF32BE>(mb, symName, archiveName);
1300   case ELF64LEKind:
1301     return isNonCommonDef<ELF64LE>(mb, symName, archiveName);
1302   case ELF64BEKind:
1303     return isNonCommonDef<ELF64BE>(mb, symName, archiveName);
1304   default:
1305     llvm_unreachable("getELFKind");
1306   }
1307 }
1308 
1309 bool ArchiveFile::shouldFetchForCommon(const Archive::Symbol &sym) {
1310   Archive::Child c =
1311       CHECK(sym.getMember(), toString(this) +
1312                                  ": could not get the member for symbol " +
1313                                  toELFString(sym));
1314   MemoryBufferRef mb =
1315       CHECK(c.getMemoryBufferRef(),
1316             toString(this) +
1317                 ": could not get the buffer for the member defining symbol " +
1318                 toELFString(sym));
1319 
1320   if (isBitcode(mb))
1321     return isBitcodeNonCommonDef(mb, sym.getName(), getName());
1322 
1323   return isNonCommonDef(mb, sym.getName(), getName());
1324 }
1325 
1326 size_t ArchiveFile::getMemberCount() const {
1327   size_t count = 0;
1328   Error err = Error::success();
1329   for (const Archive::Child &c : file->children(err)) {
1330     (void)c;
1331     ++count;
1332   }
1333   // This function is used by --print-archive-stats=, where an error does not
1334   // really matter.
1335   consumeError(std::move(err));
1336   return count;
1337 }
1338 
1339 unsigned SharedFile::vernauxNum;
1340 
1341 // Parse the version definitions in the object file if present, and return a
1342 // vector whose nth element contains a pointer to the Elf_Verdef for version
1343 // identifier n. Version identifiers that are not definitions map to nullptr.
1344 template <typename ELFT>
1345 static std::vector<const void *> parseVerdefs(const uint8_t *base,
1346                                               const typename ELFT::Shdr *sec) {
1347   if (!sec)
1348     return {};
1349 
1350   // We cannot determine the largest verdef identifier without inspecting
1351   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1352   // sequentially starting from 1, so we predict that the largest identifier
1353   // will be verdefCount.
1354   unsigned verdefCount = sec->sh_info;
1355   std::vector<const void *> verdefs(verdefCount + 1);
1356 
1357   // Build the Verdefs array by following the chain of Elf_Verdef objects
1358   // from the start of the .gnu.version_d section.
1359   const uint8_t *verdef = base + sec->sh_offset;
1360   for (unsigned i = 0; i != verdefCount; ++i) {
1361     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1362     verdef += curVerdef->vd_next;
1363     unsigned verdefIndex = curVerdef->vd_ndx;
1364     verdefs.resize(verdefIndex + 1);
1365     verdefs[verdefIndex] = curVerdef;
1366   }
1367   return verdefs;
1368 }
1369 
1370 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1371 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1372 // implement sophisticated error checking like in llvm-readobj because the value
1373 // of such diagnostics is low.
1374 template <typename ELFT>
1375 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1376                                                const typename ELFT::Shdr *sec) {
1377   if (!sec)
1378     return {};
1379   std::vector<uint32_t> verneeds;
1380   ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this);
1381   const uint8_t *verneedBuf = data.begin();
1382   for (unsigned i = 0; i != sec->sh_info; ++i) {
1383     if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
1384       fatal(toString(this) + " has an invalid Verneed");
1385     auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1386     const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1387     for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1388       if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
1389         fatal(toString(this) + " has an invalid Vernaux");
1390       auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1391       if (aux->vna_name >= this->stringTable.size())
1392         fatal(toString(this) + " has a Vernaux with an invalid vna_name");
1393       uint16_t version = aux->vna_other & VERSYM_VERSION;
1394       if (version >= verneeds.size())
1395         verneeds.resize(version + 1);
1396       verneeds[version] = aux->vna_name;
1397       vernauxBuf += aux->vna_next;
1398     }
1399     verneedBuf += vn->vn_next;
1400   }
1401   return verneeds;
1402 }
1403 
1404 // We do not usually care about alignments of data in shared object
1405 // files because the loader takes care of it. However, if we promote a
1406 // DSO symbol to point to .bss due to copy relocation, we need to keep
1407 // the original alignment requirements. We infer it in this function.
1408 template <typename ELFT>
1409 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1410                              const typename ELFT::Sym &sym) {
1411   uint64_t ret = UINT64_MAX;
1412   if (sym.st_value)
1413     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1414   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1415     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1416   return (ret > UINT32_MAX) ? 0 : ret;
1417 }
1418 
1419 // Fully parse the shared object file.
1420 //
1421 // This function parses symbol versions. If a DSO has version information,
1422 // the file has a ".gnu.version_d" section which contains symbol version
1423 // definitions. Each symbol is associated to one version through a table in
1424 // ".gnu.version" section. That table is a parallel array for the symbol
1425 // table, and each table entry contains an index in ".gnu.version_d".
1426 //
1427 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1428 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1429 // ".gnu.version_d".
1430 //
1431 // The file format for symbol versioning is perhaps a bit more complicated
1432 // than necessary, but you can easily understand the code if you wrap your
1433 // head around the data structure described above.
1434 template <class ELFT> void SharedFile::parse() {
1435   using Elf_Dyn = typename ELFT::Dyn;
1436   using Elf_Shdr = typename ELFT::Shdr;
1437   using Elf_Sym = typename ELFT::Sym;
1438   using Elf_Verdef = typename ELFT::Verdef;
1439   using Elf_Versym = typename ELFT::Versym;
1440 
1441   ArrayRef<Elf_Dyn> dynamicTags;
1442   const ELFFile<ELFT> obj = this->getObj<ELFT>();
1443   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1444 
1445   const Elf_Shdr *versymSec = nullptr;
1446   const Elf_Shdr *verdefSec = nullptr;
1447   const Elf_Shdr *verneedSec = nullptr;
1448 
1449   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1450   for (const Elf_Shdr &sec : sections) {
1451     switch (sec.sh_type) {
1452     default:
1453       continue;
1454     case SHT_DYNAMIC:
1455       dynamicTags =
1456           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
1457       break;
1458     case SHT_GNU_versym:
1459       versymSec = &sec;
1460       break;
1461     case SHT_GNU_verdef:
1462       verdefSec = &sec;
1463       break;
1464     case SHT_GNU_verneed:
1465       verneedSec = &sec;
1466       break;
1467     }
1468   }
1469 
1470   if (versymSec && numELFSyms == 0) {
1471     error("SHT_GNU_versym should be associated with symbol table");
1472     return;
1473   }
1474 
1475   // Search for a DT_SONAME tag to initialize this->soName.
1476   for (const Elf_Dyn &dyn : dynamicTags) {
1477     if (dyn.d_tag == DT_NEEDED) {
1478       uint64_t val = dyn.getVal();
1479       if (val >= this->stringTable.size())
1480         fatal(toString(this) + ": invalid DT_NEEDED entry");
1481       dtNeeded.push_back(this->stringTable.data() + val);
1482     } else if (dyn.d_tag == DT_SONAME) {
1483       uint64_t val = dyn.getVal();
1484       if (val >= this->stringTable.size())
1485         fatal(toString(this) + ": invalid DT_SONAME entry");
1486       soName = this->stringTable.data() + val;
1487     }
1488   }
1489 
1490   // DSOs are uniquified not by filename but by soname.
1491   DenseMap<StringRef, SharedFile *>::iterator it;
1492   bool wasInserted;
1493   std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1494 
1495   // If a DSO appears more than once on the command line with and without
1496   // --as-needed, --no-as-needed takes precedence over --as-needed because a
1497   // user can add an extra DSO with --no-as-needed to force it to be added to
1498   // the dependency list.
1499   it->second->isNeeded |= isNeeded;
1500   if (!wasInserted)
1501     return;
1502 
1503   sharedFiles.push_back(this);
1504 
1505   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1506   std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1507 
1508   // Parse ".gnu.version" section which is a parallel array for the symbol
1509   // table. If a given file doesn't have a ".gnu.version" section, we use
1510   // VER_NDX_GLOBAL.
1511   size_t size = numELFSyms - firstGlobal;
1512   std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1513   if (versymSec) {
1514     ArrayRef<Elf_Versym> versym =
1515         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
1516               this)
1517             .slice(firstGlobal);
1518     for (size_t i = 0; i < size; ++i)
1519       versyms[i] = versym[i].vs_index;
1520   }
1521 
1522   // System libraries can have a lot of symbols with versions. Using a
1523   // fixed buffer for computing the versions name (foo@ver) can save a
1524   // lot of allocations.
1525   SmallString<0> versionedNameBuffer;
1526 
1527   // Add symbols to the symbol table.
1528   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1529   for (size_t i = 0; i < syms.size(); ++i) {
1530     const Elf_Sym &sym = syms[i];
1531 
1532     // ELF spec requires that all local symbols precede weak or global
1533     // symbols in each symbol table, and the index of first non-local symbol
1534     // is stored to sh_info. If a local symbol appears after some non-local
1535     // symbol, that's a violation of the spec.
1536     StringRef name = CHECK(sym.getName(this->stringTable), this);
1537     if (sym.getBinding() == STB_LOCAL) {
1538       warn("found local symbol '" + name +
1539            "' in global part of symbol table in file " + toString(this));
1540       continue;
1541     }
1542 
1543     uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
1544     if (sym.isUndefined()) {
1545       // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1546       // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1547       if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
1548         if (idx >= verneeds.size()) {
1549           error("corrupt input file: version need index " + Twine(idx) +
1550                 " for symbol " + name + " is out of bounds\n>>> defined in " +
1551                 toString(this));
1552           continue;
1553         }
1554         StringRef verName = this->stringTable.data() + verneeds[idx];
1555         versionedNameBuffer.clear();
1556         name =
1557             saver.save((name + "@" + verName).toStringRef(versionedNameBuffer));
1558       }
1559       Symbol *s = symtab->addSymbol(
1560           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1561       s->exportDynamic = true;
1562       continue;
1563     }
1564 
1565     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1566     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1567     // workaround for this bug.
1568     if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
1569         name == "_gp_disp")
1570       continue;
1571 
1572     uint32_t alignment = getAlignment<ELFT>(sections, sym);
1573     if (!(versyms[i] & VERSYM_HIDDEN)) {
1574       symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1575                                      sym.st_other, sym.getType(), sym.st_value,
1576                                      sym.st_size, alignment, idx});
1577     }
1578 
1579     // Also add the symbol with the versioned name to handle undefined symbols
1580     // with explicit versions.
1581     if (idx == VER_NDX_GLOBAL)
1582       continue;
1583 
1584     if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1585       error("corrupt input file: version definition index " + Twine(idx) +
1586             " for symbol " + name + " is out of bounds\n>>> defined in " +
1587             toString(this));
1588       continue;
1589     }
1590 
1591     StringRef verName =
1592         this->stringTable.data() +
1593         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1594     versionedNameBuffer.clear();
1595     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1596     symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1597                                    sym.st_other, sym.getType(), sym.st_value,
1598                                    sym.st_size, alignment, idx});
1599   }
1600 }
1601 
1602 static ELFKind getBitcodeELFKind(const Triple &t) {
1603   if (t.isLittleEndian())
1604     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1605   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1606 }
1607 
1608 static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) {
1609   switch (t.getArch()) {
1610   case Triple::aarch64:
1611   case Triple::aarch64_be:
1612     return EM_AARCH64;
1613   case Triple::amdgcn:
1614   case Triple::r600:
1615     return EM_AMDGPU;
1616   case Triple::arm:
1617   case Triple::thumb:
1618     return EM_ARM;
1619   case Triple::avr:
1620     return EM_AVR;
1621   case Triple::mips:
1622   case Triple::mipsel:
1623   case Triple::mips64:
1624   case Triple::mips64el:
1625     return EM_MIPS;
1626   case Triple::msp430:
1627     return EM_MSP430;
1628   case Triple::ppc:
1629   case Triple::ppcle:
1630     return EM_PPC;
1631   case Triple::ppc64:
1632   case Triple::ppc64le:
1633     return EM_PPC64;
1634   case Triple::riscv32:
1635   case Triple::riscv64:
1636     return EM_RISCV;
1637   case Triple::x86:
1638     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1639   case Triple::x86_64:
1640     return EM_X86_64;
1641   default:
1642     error(path + ": could not infer e_machine from bitcode target triple " +
1643           t.str());
1644     return EM_NONE;
1645   }
1646 }
1647 
1648 static uint8_t getOsAbi(const Triple &t) {
1649   switch (t.getOS()) {
1650   case Triple::AMDHSA:
1651     return ELF::ELFOSABI_AMDGPU_HSA;
1652   case Triple::AMDPAL:
1653     return ELF::ELFOSABI_AMDGPU_PAL;
1654   case Triple::Mesa3D:
1655     return ELF::ELFOSABI_AMDGPU_MESA3D;
1656   default:
1657     return ELF::ELFOSABI_NONE;
1658   }
1659 }
1660 
1661 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1662                          uint64_t offsetInArchive)
1663     : InputFile(BitcodeKind, mb) {
1664   this->archiveName = std::string(archiveName);
1665 
1666   std::string path = mb.getBufferIdentifier().str();
1667   if (config->thinLTOIndexOnly)
1668     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
1669 
1670   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1671   // name. If two archives define two members with the same name, this
1672   // causes a collision which result in only one of the objects being taken
1673   // into consideration at LTO time (which very likely causes undefined
1674   // symbols later in the link stage). So we append file offset to make
1675   // filename unique.
1676   StringRef name =
1677       archiveName.empty()
1678           ? saver.save(path)
1679           : saver.save(archiveName + "(" + path::filename(path) + " at " +
1680                        utostr(offsetInArchive) + ")");
1681   MemoryBufferRef mbref(mb.getBuffer(), name);
1682 
1683   obj = CHECK(lto::InputFile::create(mbref), this);
1684 
1685   Triple t(obj->getTargetTriple());
1686   ekind = getBitcodeELFKind(t);
1687   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1688   osabi = getOsAbi(t);
1689 }
1690 
1691 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1692   switch (gvVisibility) {
1693   case GlobalValue::DefaultVisibility:
1694     return STV_DEFAULT;
1695   case GlobalValue::HiddenVisibility:
1696     return STV_HIDDEN;
1697   case GlobalValue::ProtectedVisibility:
1698     return STV_PROTECTED;
1699   }
1700   llvm_unreachable("unknown visibility");
1701 }
1702 
1703 template <class ELFT>
1704 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
1705                                    const lto::InputFile::Symbol &objSym,
1706                                    BitcodeFile &f) {
1707   StringRef name = saver.save(objSym.getName());
1708   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1709   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1710   uint8_t visibility = mapVisibility(objSym.getVisibility());
1711   bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
1712 
1713   int c = objSym.getComdatIndex();
1714   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1715     Undefined newSym(&f, name, binding, visibility, type);
1716     if (canOmitFromDynSym)
1717       newSym.exportDynamic = false;
1718     Symbol *ret = symtab->addSymbol(newSym);
1719     ret->referenced = true;
1720     return ret;
1721   }
1722 
1723   if (objSym.isCommon())
1724     return symtab->addSymbol(
1725         CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
1726                      objSym.getCommonAlignment(), objSym.getCommonSize()});
1727 
1728   Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
1729   if (canOmitFromDynSym)
1730     newSym.exportDynamic = false;
1731   return symtab->addSymbol(newSym);
1732 }
1733 
1734 template <class ELFT> void BitcodeFile::parse() {
1735   std::vector<bool> keptComdats;
1736   for (StringRef s : obj->getComdatTable())
1737     keptComdats.push_back(
1738         symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
1739 
1740   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1741     symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
1742 
1743   for (auto l : obj->getDependentLibraries())
1744     addDependentLibrary(l, this);
1745 }
1746 
1747 void BinaryFile::parse() {
1748   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1749   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1750                                      8, data, ".data");
1751   sections.push_back(section);
1752 
1753   // For each input file foo that is embedded to a result as a binary
1754   // blob, we define _binary_foo_{start,end,size} symbols, so that
1755   // user programs can access blobs by name. Non-alphanumeric
1756   // characters in a filename are replaced with underscore.
1757   std::string s = "_binary_" + mb.getBufferIdentifier().str();
1758   for (size_t i = 0; i < s.size(); ++i)
1759     if (!isAlnum(s[i]))
1760       s[i] = '_';
1761 
1762   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
1763                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
1764   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
1765                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
1766   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
1767                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
1768 }
1769 
1770 InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
1771                                  uint64_t offsetInArchive) {
1772   if (isBitcode(mb))
1773     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1774 
1775   switch (getELFKind(mb, archiveName)) {
1776   case ELF32LEKind:
1777     return make<ObjFile<ELF32LE>>(mb, archiveName);
1778   case ELF32BEKind:
1779     return make<ObjFile<ELF32BE>>(mb, archiveName);
1780   case ELF64LEKind:
1781     return make<ObjFile<ELF64LE>>(mb, archiveName);
1782   case ELF64BEKind:
1783     return make<ObjFile<ELF64BE>>(mb, archiveName);
1784   default:
1785     llvm_unreachable("getELFKind");
1786   }
1787 }
1788 
1789 void LazyObjFile::fetch() {
1790   if (fetched)
1791     return;
1792   fetched = true;
1793 
1794   InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
1795   file->groupId = groupId;
1796 
1797   // Copy symbol vector so that the new InputFile doesn't have to
1798   // insert the same defined symbols to the symbol table again.
1799   file->symbols = std::move(symbols);
1800 
1801   parseFile(file);
1802 }
1803 
1804 template <class ELFT> void LazyObjFile::parse() {
1805   using Elf_Sym = typename ELFT::Sym;
1806 
1807   // A lazy object file wraps either a bitcode file or an ELF file.
1808   if (isBitcode(this->mb)) {
1809     std::unique_ptr<lto::InputFile> obj =
1810         CHECK(lto::InputFile::create(this->mb), this);
1811     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
1812       if (sym.isUndefined())
1813         continue;
1814       symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
1815     }
1816     return;
1817   }
1818 
1819   if (getELFKind(this->mb, archiveName) != config->ekind) {
1820     error("incompatible file: " + this->mb.getBufferIdentifier());
1821     return;
1822   }
1823 
1824   // Find a symbol table.
1825   ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
1826   ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
1827 
1828   for (const typename ELFT::Shdr &sec : sections) {
1829     if (sec.sh_type != SHT_SYMTAB)
1830       continue;
1831 
1832     // A symbol table is found.
1833     ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
1834     uint32_t firstGlobal = sec.sh_info;
1835     StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
1836     this->symbols.resize(eSyms.size());
1837 
1838     // Get existing symbols or insert placeholder symbols.
1839     for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1840       if (eSyms[i].st_shndx != SHN_UNDEF)
1841         this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
1842 
1843     // Replace existing symbols with LazyObject symbols.
1844     //
1845     // resolve() may trigger this->fetch() if an existing symbol is an
1846     // undefined symbol. If that happens, this LazyObjFile has served
1847     // its purpose, and we can exit from the loop early.
1848     for (Symbol *sym : this->symbols) {
1849       if (!sym)
1850         continue;
1851       sym->resolve(LazyObject{*this, sym->getName()});
1852 
1853       // If fetched, stop iterating because this->symbols has been transferred
1854       // to the instantiated ObjFile.
1855       if (fetched)
1856         return;
1857     }
1858     return;
1859   }
1860 }
1861 
1862 bool LazyObjFile::shouldFetchForCommon(const StringRef &name) {
1863   if (isBitcode(mb))
1864     return isBitcodeNonCommonDef(mb, name, archiveName);
1865 
1866   return isNonCommonDef(mb, name, archiveName);
1867 }
1868 
1869 std::string elf::replaceThinLTOSuffix(StringRef path) {
1870   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1871   StringRef repl = config->thinLTOObjectSuffixReplace.second;
1872 
1873   if (path.consume_back(suffix))
1874     return (path + repl).str();
1875   return std::string(path);
1876 }
1877 
1878 template void BitcodeFile::parse<ELF32LE>();
1879 template void BitcodeFile::parse<ELF32BE>();
1880 template void BitcodeFile::parse<ELF64LE>();
1881 template void BitcodeFile::parse<ELF64BE>();
1882 
1883 template void LazyObjFile::parse<ELF32LE>();
1884 template void LazyObjFile::parse<ELF32BE>();
1885 template void LazyObjFile::parse<ELF64LE>();
1886 template void LazyObjFile::parse<ELF64BE>();
1887 
1888 template class elf::ObjFile<ELF32LE>;
1889 template class elf::ObjFile<ELF32BE>;
1890 template class elf::ObjFile<ELF64LE>;
1891 template class elf::ObjFile<ELF64BE>;
1892 
1893 template void SharedFile::parse<ELF32LE>();
1894 template void SharedFile::parse<ELF32BE>();
1895 template void SharedFile::parse<ELF64LE>();
1896 template void SharedFile::parse<ELF64BE>();
1897