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