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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of lld/ELF/InputFiles.cpp