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. STT_TLS symbols can
1392 // only be referenced by special TLS relocations. It is usually an error if
1393 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
1394 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS &&
1395 eSym.getType() != STT_NOTYPE)
1396 Err(ctx) << "TLS attribute mismatch: " << &sym << "\n>>> in " << sym.file
1397 << "\n>>> in " << this;
1398
1399 // Handle non-COMMON defined symbol below. !sym.file allows a symbol
1400 // assignment to redefine a symbol without an error.
1401 if (!sym.isDefined() || secIdx == SHN_UNDEF)
1402 continue;
1403 if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE)) {
1404 if (secIdx == SHN_COMMON)
1405 continue;
1406 if (secIdx == SHN_XINDEX)
1407 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1408 else
1409 secIdx = 0;
1410 }
1411
1412 if (LLVM_UNLIKELY(secIdx >= sections.size())) {
1413 Err(ctx) << this << ": invalid section index: " << secIdx;
1414 continue;
1415 }
1416 InputSectionBase *sec = sections[secIdx];
1417 if (sec == &InputSection::discarded) {
1418 if (sym.traced) {
1419 printTraceSymbol(sym: Undefined{this, sym.getName(), sym.binding,
1420 sym.stOther, sym.type, secIdx},
1421 name: sym.getName());
1422 }
1423 if (sym.file == this) {
1424 std::lock_guard<std::mutex> lock(mu);
1425 ctx.nonPrevailingSyms.emplace_back(&sym, secIdx);
1426 }
1427 continue;
1428 }
1429
1430 if (sym.file == this) {
1431 cast<Defined>(Val&: sym).section = sec;
1432 continue;
1433 }
1434
1435 if (sym.binding == STB_WEAK || binding == STB_WEAK)
1436 continue;
1437 std::lock_guard<std::mutex> lock(mu);
1438 ctx.duplicates.push_back(Elt: {&sym, this, sec, eSym.st_value});
1439 }
1440}
1441
1442// The handling of tentative definitions (COMMON symbols) in archives is murky.
1443// A tentative definition will be promoted to a global definition if there are
1444// no non-tentative definitions to dominate it. When we hold a tentative
1445// definition to a symbol and are inspecting archive members for inclusion
1446// there are 2 ways we can proceed:
1447//
1448// 1) Consider the tentative definition a 'real' definition (ie promotion from
1449// tentative to real definition has already happened) and not inspect
1450// archive members for Global/Weak definitions to replace the tentative
1451// definition. An archive member would only be included if it satisfies some
1452// other undefined symbol. This is the behavior Gold uses.
1453//
1454// 2) Consider the tentative definition as still undefined (ie the promotion to
1455// a real definition happens only after all symbol resolution is done).
1456// The linker searches archive members for STB_GLOBAL definitions to
1457// replace the tentative definition with. This is the behavior used by
1458// GNU ld.
1459//
1460// The second behavior is inherited from SysVR4, which based it on the FORTRAN
1461// COMMON BLOCK model. This behavior is needed for proper initialization in old
1462// (pre F90) FORTRAN code that is packaged into an archive.
1463//
1464// The following functions search archive members for definitions to replace
1465// tentative definitions (implementing behavior 2).
1466static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1467 StringRef archiveName) {
1468 IRSymtabFile symtabFile = check(e: readIRSymtab(MBRef: mb));
1469 for (const irsymtab::Reader::SymbolRef &sym :
1470 symtabFile.TheReader.symbols()) {
1471 if (sym.isGlobal() && sym.getName() == symName)
1472 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1473 }
1474 return false;
1475}
1476
1477template <class ELFT>
1478static bool isNonCommonDef(Ctx &ctx, ELFKind ekind, MemoryBufferRef mb,
1479 StringRef symName, StringRef archiveName) {
1480 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(ctx, ekind, mb, archiveName);
1481 obj->init();
1482 StringRef stringtable = obj->getStringTable();
1483
1484 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1485 Expected<StringRef> name = sym.getName(stringtable);
1486 if (name && name.get() == symName)
1487 return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1488 !sym.isCommon();
1489 }
1490 return false;
1491}
1492
1493static bool isNonCommonDef(Ctx &ctx, MemoryBufferRef mb, StringRef symName,
1494 StringRef archiveName) {
1495 switch (getELFKind(ctx, mb, archiveName)) {
1496 case ELF32LEKind:
1497 return isNonCommonDef<ELF32LE>(ctx, ekind: ELF32LEKind, mb, symName, archiveName);
1498 case ELF32BEKind:
1499 return isNonCommonDef<ELF32BE>(ctx, ekind: ELF32BEKind, mb, symName, archiveName);
1500 case ELF64LEKind:
1501 return isNonCommonDef<ELF64LE>(ctx, ekind: ELF64LEKind, mb, symName, archiveName);
1502 case ELF64BEKind:
1503 return isNonCommonDef<ELF64BE>(ctx, ekind: ELF64BEKind, mb, symName, archiveName);
1504 default:
1505 llvm_unreachable("getELFKind");
1506 }
1507}
1508
1509SharedFile::SharedFile(Ctx &ctx, MemoryBufferRef m, StringRef defaultSoName)
1510 : ELFFileBase(ctx, SharedKind, getELFKind(ctx, mb: m, archiveName: ""), m),
1511 soName(defaultSoName), isNeeded(!ctx.arg.asNeeded) {}
1512
1513// Parse the version definitions in the object file if present, and return a
1514// vector whose nth element contains a pointer to the Elf_Verdef for version
1515// identifier n. Version identifiers that are not definitions map to nullptr.
1516template <typename ELFT>
1517static SmallVector<const void *, 0>
1518parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
1519 if (!sec)
1520 return {};
1521
1522 // Build the Verdefs array by following the chain of Elf_Verdef objects
1523 // from the start of the .gnu.version_d section.
1524 SmallVector<const void *, 0> verdefs;
1525 const uint8_t *verdef = base + sec->sh_offset;
1526 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
1527 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1528 verdef += curVerdef->vd_next;
1529 unsigned verdefIndex = curVerdef->vd_ndx;
1530 if (verdefIndex >= verdefs.size())
1531 verdefs.resize(N: verdefIndex + 1);
1532 verdefs[verdefIndex] = curVerdef;
1533 }
1534 return verdefs;
1535}
1536
1537// Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1538// symbol. We detect fatal issues which would cause vulnerabilities, but do not
1539// implement sophisticated error checking like in llvm-readobj because the value
1540// of such diagnostics is low.
1541template <typename ELFT>
1542std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1543 const typename ELFT::Shdr *sec) {
1544 if (!sec)
1545 return {};
1546 std::vector<uint32_t> verneeds;
1547 ArrayRef<uint8_t> data = CHECK2(obj.getSectionContents(*sec), this);
1548 const uint8_t *verneedBuf = data.begin();
1549 for (unsigned i = 0; i != sec->sh_info; ++i) {
1550 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) {
1551 Err(ctx) << this << " has an invalid Verneed";
1552 break;
1553 }
1554 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1555 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1556 for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1557 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) {
1558 Err(ctx) << this << " has an invalid Vernaux";
1559 break;
1560 }
1561 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1562 if (aux->vna_name >= this->stringTable.size()) {
1563 Err(ctx) << this << " has a Vernaux with an invalid vna_name";
1564 break;
1565 }
1566 uint16_t version = aux->vna_other & VERSYM_VERSION;
1567 if (version >= verneeds.size())
1568 verneeds.resize(new_size: version + 1);
1569 verneeds[version] = aux->vna_name;
1570 vernauxBuf += aux->vna_next;
1571 }
1572 verneedBuf += vn->vn_next;
1573 }
1574 return verneeds;
1575}
1576
1577// Parse PT_GNU_PROPERTY segments in DSO. The process is similar to
1578// readGnuProperty, but we don't have the InputSection information.
1579template <typename ELFT>
1580void SharedFile::parseGnuAndFeatures(const ELFFile<ELFT> &obj) {
1581 if (ctx.arg.emachine != EM_AARCH64)
1582 return;
1583 const uint8_t *base = obj.base();
1584 auto phdrs = CHECK2(obj.program_headers(), this);
1585 for (auto phdr : phdrs) {
1586 if (phdr.p_type != PT_GNU_PROPERTY)
1587 continue;
1588 typename ELFT::Note note(
1589 *reinterpret_cast<const typename ELFT::Nhdr *>(base + phdr.p_offset));
1590 if (note.getType() != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU")
1591 continue;
1592
1593 ArrayRef<uint8_t> desc = note.getDesc(phdr.p_align);
1594 parseGnuPropertyNote<ELFT>(ctx, *this, GNU_PROPERTY_AARCH64_FEATURE_1_AND,
1595 desc, base);
1596 }
1597}
1598
1599// We do not usually care about alignments of data in shared object
1600// files because the loader takes care of it. However, if we promote a
1601// DSO symbol to point to .bss due to copy relocation, we need to keep
1602// the original alignment requirements. We infer it in this function.
1603template <typename ELFT>
1604static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1605 const typename ELFT::Sym &sym) {
1606 uint64_t ret = UINT64_MAX;
1607 if (sym.st_value)
1608 ret = 1ULL << llvm::countr_zero(Val: (uint64_t)sym.st_value);
1609 if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1610 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1611 return (ret > UINT32_MAX) ? 0 : ret;
1612}
1613
1614// Fully parse the shared object file.
1615//
1616// This function parses symbol versions. If a DSO has version information,
1617// the file has a ".gnu.version_d" section which contains symbol version
1618// definitions. Each symbol is associated to one version through a table in
1619// ".gnu.version" section. That table is a parallel array for the symbol
1620// table, and each table entry contains an index in ".gnu.version_d".
1621//
1622// The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1623// VER_NDX_GLOBAL. There's no table entry for these special versions in
1624// ".gnu.version_d".
1625//
1626// The file format for symbol versioning is perhaps a bit more complicated
1627// than necessary, but you can easily understand the code if you wrap your
1628// head around the data structure described above.
1629template <class ELFT> void SharedFile::parse() {
1630 using Elf_Dyn = typename ELFT::Dyn;
1631 using Elf_Shdr = typename ELFT::Shdr;
1632 using Elf_Sym = typename ELFT::Sym;
1633 using Elf_Verdef = typename ELFT::Verdef;
1634 using Elf_Versym = typename ELFT::Versym;
1635
1636 ArrayRef<Elf_Dyn> dynamicTags;
1637 const ELFFile<ELFT> obj = this->getObj<ELFT>();
1638 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
1639
1640 const Elf_Shdr *versymSec = nullptr;
1641 const Elf_Shdr *verdefSec = nullptr;
1642 const Elf_Shdr *verneedSec = nullptr;
1643 symbols = std::make_unique<Symbol *[]>(num: numSymbols);
1644
1645 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1646 for (const Elf_Shdr &sec : sections) {
1647 switch (sec.sh_type) {
1648 default:
1649 continue;
1650 case SHT_DYNAMIC:
1651 dynamicTags =
1652 CHECK2(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
1653 break;
1654 case SHT_GNU_versym:
1655 versymSec = &sec;
1656 break;
1657 case SHT_GNU_verdef:
1658 verdefSec = &sec;
1659 break;
1660 case SHT_GNU_verneed:
1661 verneedSec = &sec;
1662 break;
1663 }
1664 }
1665
1666 if (versymSec && numSymbols == 0) {
1667 ErrAlways(ctx) << "SHT_GNU_versym should be associated with symbol table";
1668 return;
1669 }
1670
1671 // Search for a DT_SONAME tag to initialize this->soName.
1672 for (const Elf_Dyn &dyn : dynamicTags) {
1673 if (dyn.d_tag == DT_NEEDED) {
1674 uint64_t val = dyn.getVal();
1675 if (val >= this->stringTable.size()) {
1676 Err(ctx) << this << ": invalid DT_NEEDED entry";
1677 return;
1678 }
1679 dtNeeded.push_back(Elt: this->stringTable.data() + val);
1680 } else if (dyn.d_tag == DT_SONAME) {
1681 uint64_t val = dyn.getVal();
1682 if (val >= this->stringTable.size()) {
1683 Err(ctx) << this << ": invalid DT_SONAME entry";
1684 return;
1685 }
1686 soName = this->stringTable.data() + val;
1687 }
1688 }
1689
1690 // DSOs are uniquified not by filename but by soname.
1691 StringSaver &ss = ctx.saver;
1692 DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
1693 bool wasInserted;
1694 std::tie(args&: it, args&: wasInserted) =
1695 ctx.symtab->soNames.try_emplace(Key: CachedHashStringRef(soName), Args: this);
1696
1697 // If a DSO appears more than once on the command line with and without
1698 // --as-needed, --no-as-needed takes precedence over --as-needed because a
1699 // user can add an extra DSO with --no-as-needed to force it to be added to
1700 // the dependency list.
1701 if (isNeeded)
1702 it->second->isNeeded.store(i: true, m: std::memory_order_relaxed);
1703 if (!wasInserted)
1704 return;
1705
1706 ctx.sharedFiles.push_back(Elt: this);
1707
1708 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1709 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1710 parseGnuAndFeatures<ELFT>(obj);
1711
1712 // Parse ".gnu.version" section which is a parallel array for the symbol
1713 // table. If a given file doesn't have a ".gnu.version" section, we use
1714 // VER_NDX_GLOBAL.
1715 size_t size = numSymbols - firstGlobal;
1716 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1717 if (versymSec) {
1718 ArrayRef<Elf_Versym> versym =
1719 CHECK2(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
1720 this)
1721 .slice(firstGlobal);
1722 for (size_t i = 0; i < size; ++i)
1723 versyms[i] = versym[i].vs_index;
1724 }
1725
1726 // System libraries can have a lot of symbols with versions. Using a
1727 // fixed buffer for computing the versions name (foo@ver) can save a
1728 // lot of allocations.
1729 SmallString<0> versionedNameBuffer;
1730
1731 // Add symbols to the symbol table.
1732 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1733 for (size_t i = 0, e = syms.size(); i != e; ++i) {
1734 const Elf_Sym &sym = syms[i];
1735
1736 // ELF spec requires that all local symbols precede weak or global
1737 // symbols in each symbol table, and the index of first non-local symbol
1738 // is stored to sh_info. If a local symbol appears after some non-local
1739 // symbol, that's a violation of the spec.
1740 StringRef name = CHECK2(sym.getName(stringTable), this);
1741 if (sym.getBinding() == STB_LOCAL) {
1742 Err(ctx) << this << ": invalid local symbol '" << name
1743 << "' in global part of symbol table";
1744 continue;
1745 }
1746
1747 const uint16_t ver = versyms[i], idx = ver & ~VERSYM_HIDDEN;
1748 if (sym.isUndefined()) {
1749 // Index 0 (VER_NDX_LOCAL) is used for unversioned undefined symbols.
1750 // GNU ld versions between 2.35 and 2.45 also generate VER_NDX_GLOBAL
1751 // for this case (https://sourceware.org/PR33577).
1752 if (ver != VER_NDX_LOCAL && ver != VER_NDX_GLOBAL) {
1753 if (idx >= verneeds.size()) {
1754 ErrAlways(ctx) << "corrupt input file: version need index " << idx
1755 << " for symbol " << name
1756 << " is out of bounds\n>>> defined in " << this;
1757 continue;
1758 }
1759 StringRef verName = stringTable.data() + verneeds[idx];
1760 versionedNameBuffer.clear();
1761 name = ss.save(S: (name + "@" + verName).toStringRef(Out&: versionedNameBuffer));
1762 }
1763 Symbol *s = ctx.symtab->addSymbol(
1764 newSym: Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1765 s->isExported = true;
1766 if (sym.getBinding() != STB_WEAK &&
1767 ctx.arg.unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1768 requiredSymbols.push_back(Elt: s);
1769 continue;
1770 }
1771
1772 if (ver == VER_NDX_LOCAL ||
1773 (ver != VER_NDX_GLOBAL && idx >= verdefs.size())) {
1774 // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the
1775 // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns
1776 // VER_NDX_LOCAL. Workaround this bug.
1777 if (ctx.arg.emachine == EM_MIPS && name == "_gp_disp")
1778 continue;
1779 ErrAlways(ctx) << "corrupt input file: version definition index " << idx
1780 << " for symbol " << name
1781 << " is out of bounds\n>>> defined in " << this;
1782 continue;
1783 }
1784
1785 uint32_t alignment = getAlignment<ELFT>(sections, sym);
1786 if (ver == idx) {
1787 auto *s = ctx.symtab->addSymbol(
1788 newSym: SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
1789 sym.getType(), sym.st_value, sym.st_size, alignment});
1790 s->dsoDefined = true;
1791 if (s->file == this)
1792 s->versionId = ver;
1793 }
1794
1795 // Also add the symbol with the versioned name to handle undefined symbols
1796 // with explicit versions.
1797 if (ver == VER_NDX_GLOBAL)
1798 continue;
1799
1800 StringRef verName =
1801 stringTable.data() +
1802 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1803 versionedNameBuffer.clear();
1804 name = (name + "@" + verName).toStringRef(Out&: versionedNameBuffer);
1805 auto *s = ctx.symtab->addSymbol(
1806 newSym: SharedSymbol{*this, ss.save(S: name), sym.getBinding(), sym.st_other,
1807 sym.getType(), sym.st_value, sym.st_size, alignment});
1808 s->dsoDefined = true;
1809 if (s->file == this)
1810 s->versionId = idx;
1811 }
1812}
1813
1814static ELFKind getBitcodeELFKind(const Triple &t) {
1815 if (t.isLittleEndian())
1816 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1817 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1818}
1819
1820static uint16_t getBitcodeMachineKind(Ctx &ctx, StringRef path,
1821 const Triple &t) {
1822 switch (t.getArch()) {
1823 case Triple::aarch64:
1824 case Triple::aarch64_be:
1825 return EM_AARCH64;
1826 case Triple::amdgpu:
1827 case Triple::r600:
1828 return EM_AMDGPU;
1829 case Triple::arm:
1830 case Triple::armeb:
1831 case Triple::thumb:
1832 case Triple::thumbeb:
1833 return EM_ARM;
1834 case Triple::avr:
1835 return EM_AVR;
1836 case Triple::hexagon:
1837 return EM_HEXAGON;
1838 case Triple::loongarch32:
1839 case Triple::loongarch64:
1840 return EM_LOONGARCH;
1841 case Triple::mips:
1842 case Triple::mipsel:
1843 case Triple::mips64:
1844 case Triple::mips64el:
1845 return EM_MIPS;
1846 case Triple::msp430:
1847 return EM_MSP430;
1848 case Triple::ppc:
1849 case Triple::ppcle:
1850 return EM_PPC;
1851 case Triple::ppc64:
1852 case Triple::ppc64le:
1853 return EM_PPC64;
1854 case Triple::riscv32:
1855 case Triple::riscv64:
1856 return EM_RISCV;
1857 case Triple::sparcv9:
1858 return EM_SPARCV9;
1859 case Triple::systemz:
1860 return EM_S390;
1861 case Triple::x86:
1862 return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1863 case Triple::x86_64:
1864 return EM_X86_64;
1865 default:
1866 ErrAlways(ctx) << path
1867 << ": could not infer e_machine from bitcode target triple "
1868 << t.str();
1869 return EM_NONE;
1870 }
1871}
1872
1873static uint8_t getOsAbi(const Triple &t) {
1874 switch (t.getOS()) {
1875 case Triple::AMDHSA:
1876 return ELF::ELFOSABI_AMDGPU_HSA;
1877 case Triple::AMDPAL:
1878 return ELF::ELFOSABI_AMDGPU_PAL;
1879 case Triple::Mesa3D:
1880 return ELF::ELFOSABI_AMDGPU_MESA3D;
1881 default:
1882 return ELF::ELFOSABI_NONE;
1883 }
1884}
1885
1886BitcodeFile::BitcodeFile(Ctx &ctx, MemoryBufferRef mb, StringRef archiveName,
1887 uint64_t offsetInArchive, bool lazy)
1888 : InputFile(ctx, BitcodeKind, mb) {
1889 this->archiveName = archiveName;
1890 this->lazy = lazy;
1891
1892 std::string path = mb.getBufferIdentifier().str();
1893 if (ctx.arg.thinLTOIndexOnly)
1894 path = replaceThinLTOSuffix(ctx, path: mb.getBufferIdentifier());
1895
1896 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1897 // name. If two archives define two members with the same name, this
1898 // causes a collision which result in only one of the objects being taken
1899 // into consideration at LTO time (which very likely causes undefined
1900 // symbols later in the link stage). So we append file offset to make
1901 // filename unique.
1902 StringSaver &ss = ctx.saver;
1903 StringRef name = archiveName.empty()
1904 ? ss.save(S: path)
1905 : ss.save(S: archiveName + "(" + path::filename(path) +
1906 " at " + utostr(X: offsetInArchive) + ")");
1907
1908 MemoryBufferRef mbref(mb.getBuffer(), name);
1909
1910 obj = CHECK2(lto::InputFile::create(mbref), this);
1911 obj->setArchivePathAndName(Path: archiveName, Name: mb.getBufferIdentifier());
1912
1913 Triple t(obj->getTargetTriple());
1914 ekind = getBitcodeELFKind(t);
1915 emachine = getBitcodeMachineKind(ctx, path: mb.getBufferIdentifier(), t);
1916 osabi = getOsAbi(t);
1917}
1918
1919static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1920 switch (gvVisibility) {
1921 case GlobalValue::DefaultVisibility:
1922 return STV_DEFAULT;
1923 case GlobalValue::HiddenVisibility:
1924 return STV_HIDDEN;
1925 case GlobalValue::ProtectedVisibility:
1926 return STV_PROTECTED;
1927 }
1928 llvm_unreachable("unknown visibility");
1929}
1930
1931static void createBitcodeSymbol(Ctx &ctx, Symbol *&sym,
1932 const lto::InputFile::Symbol &objSym,
1933 BitcodeFile &f) {
1934 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1935 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1936 uint8_t visibility = mapVisibility(gvVisibility: objSym.getVisibility());
1937
1938 if (!sym) {
1939 // Symbols can be duplicated in bitcode files because of '#include' and
1940 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1941 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1942 // this way LTO can reference the same string saver's copy rather than
1943 // keeping copies of its own.
1944 objSym.Name = ctx.uniqueSaver.save(S: objSym.getName());
1945 sym = ctx.symtab->insert(name: objSym.getName());
1946 }
1947
1948 if (objSym.isUndefined()) {
1949 Undefined newSym(&f, StringRef(), binding, visibility, type);
1950 sym->resolve(ctx, other: newSym);
1951 sym->referenced = true;
1952 return;
1953 }
1954
1955 if (objSym.isCommon()) {
1956 sym->resolve(ctx, other: CommonSymbol{ctx, &f, StringRef(), binding, visibility,
1957 STT_OBJECT, objSym.getCommonAlignment(),
1958 objSym.getCommonSize()});
1959 } else {
1960 Defined newSym(ctx, &f, StringRef(), binding, visibility, type, 0, 0,
1961 nullptr);
1962 // The definition can be omitted if all bitcode definitions satisfy
1963 // `canBeOmittedFromSymbolTable()` and isUsedInRegularObj is false.
1964 // The latter condition is tested in parseVersionAndComputeIsPreemptible.
1965 sym->ltoCanOmit = objSym.canBeOmittedFromSymbolTable() &&
1966 (!sym->isDefined() || sym->ltoCanOmit);
1967 sym->resolve(ctx, other: newSym);
1968 }
1969}
1970
1971void BitcodeFile::parse() {
1972 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
1973 keptComdats.push_back(
1974 x: s.second == Comdat::NoDeduplicate ||
1975 ctx.symtab->comdatGroups.try_emplace(Key: CachedHashStringRef(s.first), Args: this)
1976 .second);
1977 }
1978
1979 if (numSymbols == 0) {
1980 numSymbols = obj->symbols().size();
1981 symbols = std::make_unique<Symbol *[]>(num: numSymbols);
1982 }
1983 // Process defined symbols first. See the comment in
1984 // ObjFile<ELFT>::initializeSymbols.
1985 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols()))
1986 if (!irSym.isUndefined())
1987 createBitcodeSymbol(ctx, sym&: symbols[i], objSym: irSym, f&: *this);
1988 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols()))
1989 if (irSym.isUndefined())
1990 createBitcodeSymbol(ctx, sym&: symbols[i], objSym: irSym, f&: *this);
1991
1992 for (auto l : obj->getDependentLibraries())
1993 addDependentLibrary(ctx, specifier: l, f: this);
1994}
1995
1996void BitcodeFile::parseLazy() {
1997 numSymbols = obj->symbols().size();
1998 symbols = std::make_unique<Symbol *[]>(num: numSymbols);
1999 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols())) {
2000 // Symbols can be duplicated in bitcode files because of '#include' and
2001 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
2002 // Update objSym.Name to reference (via StringRef) the string saver's copy;
2003 // this way LTO can reference the same string saver's copy rather than
2004 // keeping copies of its own.
2005 irSym.Name = ctx.uniqueSaver.save(S: irSym.getName());
2006 if (!irSym.isUndefined()) {
2007 auto *sym = ctx.symtab->insert(name: irSym.getName());
2008 sym->resolve(ctx, other: LazySymbol{*this});
2009 symbols[i] = sym;
2010 }
2011 }
2012}
2013
2014void BitcodeFile::postParse() {
2015 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols())) {
2016 const Symbol &sym = *symbols[i];
2017 if (sym.file == this || !sym.isDefined() || irSym.isUndefined() ||
2018 irSym.isCommon() || irSym.isWeak())
2019 continue;
2020 int c = irSym.getComdatIndex();
2021 if (c != -1 && !keptComdats[c])
2022 continue;
2023 reportDuplicate(ctx, sym, newFile: this, errSec: nullptr, errOffset: 0);
2024 }
2025}
2026
2027void BinaryFile::parse() {
2028 ArrayRef<uint8_t> data = arrayRefFromStringRef(Input: mb.getBuffer());
2029 auto *section =
2030 make<InputSection>(args: this, args: ".data", args: SHT_PROGBITS, args: SHF_ALLOC | SHF_WRITE,
2031 /*addralign=*/args: 8, /*entsize=*/args: 0, args&: data);
2032 sections.push_back(Elt: section);
2033
2034 // For each input file foo that is embedded to a result as a binary
2035 // blob, we define _binary_foo_{start,end,size} symbols, so that
2036 // user programs can access blobs by name. Non-alphanumeric
2037 // characters in a filename are replaced with underscore.
2038 std::string s = "_binary_" + mb.getBufferIdentifier().str();
2039 for (char &c : s)
2040 if (!isAlnum(C: c))
2041 c = '_';
2042
2043 llvm::StringSaver &ss = ctx.saver;
2044 ctx.symtab->addAndCheckDuplicate(
2045 ctx, newSym: Defined{ctx, this, ss.save(S: s + "_start"), STB_GLOBAL, STV_DEFAULT,
2046 STT_OBJECT, 0, 0, section});
2047 ctx.symtab->addAndCheckDuplicate(
2048 ctx, newSym: Defined{ctx, this, ss.save(S: s + "_end"), STB_GLOBAL, STV_DEFAULT,
2049 STT_OBJECT, data.size(), 0, section});
2050 ctx.symtab->addAndCheckDuplicate(
2051 ctx, newSym: Defined{ctx, this, ss.save(S: s + "_size"), STB_GLOBAL, STV_DEFAULT,
2052 STT_OBJECT, data.size(), 0, nullptr});
2053}
2054
2055InputFile *elf::createInternalFile(Ctx &ctx, StringRef name) {
2056 auto *file =
2057 make<InputFile>(args&: ctx, args: InputFile::InternalKind, args: MemoryBufferRef("", name));
2058 // References from an internal file do not lead to --warn-backrefs
2059 // diagnostics.
2060 file->groupId = 0;
2061 return file;
2062}
2063
2064std::unique_ptr<ELFFileBase> elf::createObjFile(Ctx &ctx, MemoryBufferRef mb,
2065 StringRef archiveName,
2066 bool lazy) {
2067 std::unique_ptr<ELFFileBase> f;
2068 switch (getELFKind(ctx, mb, archiveName)) {
2069 case ELF32LEKind:
2070 f = std::make_unique<ObjFile<ELF32LE>>(args&: ctx, args: ELF32LEKind, args&: mb, args&: archiveName);
2071 break;
2072 case ELF32BEKind:
2073 f = std::make_unique<ObjFile<ELF32BE>>(args&: ctx, args: ELF32BEKind, args&: mb, args&: archiveName);
2074 break;
2075 case ELF64LEKind:
2076 f = std::make_unique<ObjFile<ELF64LE>>(args&: ctx, args: ELF64LEKind, args&: mb, args&: archiveName);
2077 break;
2078 case ELF64BEKind:
2079 f = std::make_unique<ObjFile<ELF64BE>>(args&: ctx, args: ELF64BEKind, args&: mb, args&: archiveName);
2080 break;
2081 default:
2082 llvm_unreachable("getELFKind");
2083 }
2084 f->init();
2085 f->lazy = lazy;
2086 return f;
2087}
2088
2089template <class ELFT> void ObjFile<ELFT>::parseLazy() {
2090 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
2091 numSymbols = eSyms.size();
2092 symbols = std::make_unique<Symbol *[]>(numSymbols);
2093
2094 // resolve() may trigger this->extract() if an existing symbol is an undefined
2095 // symbol. If that happens, this function has served its purpose, and we can
2096 // exit from the loop early.
2097 auto *symtab = ctx.symtab.get();
2098 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
2099 if (eSyms[i].st_shndx == SHN_UNDEF)
2100 continue;
2101 symbols[i] = symtab->insert(CHECK2(eSyms[i].getName(stringTable), this));
2102 symbols[i]->resolve(ctx, LazySymbol{*this});
2103 if (!lazy)
2104 break;
2105 }
2106}
2107
2108bool InputFile::shouldExtractForCommon(StringRef name) const {
2109 if (isa<BitcodeFile>(Val: this))
2110 return isBitcodeNonCommonDef(mb, symName: name, archiveName);
2111
2112 return isNonCommonDef(ctx, mb, symName: name, archiveName);
2113}
2114
2115std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
2116 auto [suffix, repl] = ctx.arg.thinLTOObjectSuffixReplace;
2117 if (path.consume_back(Suffix: suffix))
2118 return (path + repl).str();
2119 return std::string(path);
2120}
2121
2122template class elf::ObjFile<ELF32LE>;
2123template class elf::ObjFile<ELF32BE>;
2124template class elf::ObjFile<ELF64LE>;
2125template class elf::ObjFile<ELF64BE>;
2126
2127template void SharedFile::parse<ELF32LE>();
2128template void SharedFile::parse<ELF32BE>();
2129template void SharedFile::parse<ELF64LE>();
2130template void SharedFile::parse<ELF64BE>();
2131