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