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