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 if (file->aarch64PauthAbiCoreInfo) {
541 // Check for data mismatch.
542 if (file->aarch64PauthAbiCoreInfo) {
543 if (baInfo.Pauth.TagPlatform != file->aarch64PauthAbiCoreInfo->platform ||
544 baInfo.Pauth.TagSchema != file->aarch64PauthAbiCoreInfo->version)
545 Err(ctx) << file
546 << " GNU properties and build attributes have conflicting "
547 "AArch64 PAuth data";
548 }
549 if (baInfo.AndFeatures != file->andFeatures)
550 Err(ctx) << file
551 << " GNU properties and build attributes have conflicting "
552 "AArch64 PAuth data";
553 } else {
554 // When BuildAttributes are missing, PauthABI value defaults to (TagPlatform
555 // = 0, TagSchema = 0). GNU properties do not write PAuthAbiCoreInfo if GNU
556 // property is not present. To match this behaviour, we only write
557 // PAuthAbiCoreInfo when there is at least one non-zero value. The
558 // specification reserves TagPlatform = 0, TagSchema = 1 values to match the
559 // 'Invalid' GNU property section with platform = 0, version = 0.
560 if (baInfo.Pauth.TagPlatform || baInfo.Pauth.TagSchema) {
561 if (baInfo.Pauth.TagPlatform == 0 && baInfo.Pauth.TagSchema == 1)
562 file->aarch64PauthAbiCoreInfo = {0, 0};
563 else
564 file->aarch64PauthAbiCoreInfo = {baInfo.Pauth.TagPlatform,
565 baInfo.Pauth.TagSchema};
566 }
567 file->andFeatures = baInfo.AndFeatures;
568 }
569}
570
571template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
572 object::ELFFile<ELFT> obj = this->getObj();
573 // Read a section table. justSymbols is usually false.
574 if (this->justSymbols) {
575 initializeJustSymbols();
576 initializeSymbols(obj);
577 return;
578 }
579
580 // Handle dependent libraries and selection of section groups as these are not
581 // done in parallel.
582 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
583 StringRef shstrtab = CHECK2(obj.getSectionStringTable(objSections), this);
584 uint64_t size = objSections.size();
585 sections.resize(size);
586 for (size_t i = 0; i != size; ++i) {
587 const Elf_Shdr &sec = objSections[i];
588
589 if (LLVM_LIKELY(sec.sh_type == SHT_PROGBITS))
590 continue;
591 if (LLVM_LIKELY(sec.sh_type == SHT_GROUP)) {
592 StringRef signature = getShtGroupSignature(sections: objSections, sec);
593 ArrayRef<Elf_Word> entries =
594 CHECK2(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
595 if (entries.empty())
596 Fatal(ctx) << this << ": empty SHT_GROUP";
597
598 Elf_Word flag = entries[0];
599 if (flag && flag != GRP_COMDAT)
600 Fatal(ctx) << this << ": unsupported SHT_GROUP format";
601
602 bool keepGroup = !flag || ignoreComdats ||
603 ctx.symtab->comdatGroups
604 .try_emplace(CachedHashStringRef(signature), this)
605 .second;
606 if (keepGroup) {
607 if (!ctx.arg.resolveGroups)
608 sections[i] = createInputSection(
609 idx: i, sec, name: check(obj.getSectionName(sec, shstrtab)));
610 } else {
611 // Otherwise, discard group members.
612 for (uint32_t secIndex : entries.slice(1)) {
613 if (secIndex >= size)
614 Fatal(ctx) << this
615 << ": invalid section index in group: " << secIndex;
616 sections[secIndex] = &InputSection::discarded;
617 }
618 }
619 continue;
620 }
621
622 if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !ctx.arg.relocatable) {
623 StringRef name = check(obj.getSectionName(sec, shstrtab));
624 ArrayRef<char> data = CHECK2(
625 this->getObj().template getSectionContentsAsArray<char>(sec), this);
626 if (!data.empty() && data.back() != '\0') {
627 Err(ctx)
628 << this
629 << ": corrupted dependent libraries section (unterminated string): "
630 << name;
631 } else {
632 for (const char *d = data.begin(), *e = data.end(); d < e;) {
633 StringRef s(d);
634 addDependentLibrary(ctx, s, this);
635 d += s.size() + 1;
636 }
637 }
638 sections[i] = &InputSection::discarded;
639 continue;
640 }
641
642 switch (ctx.arg.emachine) {
643 case EM_ARM:
644 if (sec.sh_type == SHT_ARM_ATTRIBUTES) {
645 ARMAttributeParser attributes;
646 ArrayRef<uint8_t> contents =
647 check(this->getObj().getSectionContents(sec));
648 StringRef name = check(obj.getSectionName(sec, shstrtab));
649 sections[i] = &InputSection::discarded;
650 if (Error e = attributes.parse(section: contents, endian: ekind == ELF32LEKind
651 ? llvm::endianness::little
652 : llvm::endianness::big)) {
653 InputSection isec(*this, sec, name);
654 Warn(ctx) << &isec << ": " << std::move(e);
655 } else {
656 updateSupportedARMFeatures(ctx, attributes);
657 updateARMVFPArgs(ctx, attributes, this);
658
659 // FIXME: Retain the first attribute section we see. The eglibc ARM
660 // dynamic loaders require the presence of an attribute section for
661 // dlopen to work. In a full implementation we would merge all
662 // attribute sections.
663 if (ctx.in.attributes == nullptr) {
664 ctx.in.attributes =
665 std::make_unique<InputSection>(*this, sec, name);
666 sections[i] = ctx.in.attributes.get();
667 }
668 }
669 }
670 break;
671 case EM_AARCH64:
672 // Producing a static binary with MTE globals is not currently supported,
673 // remove all SHT_AARCH64_MEMTAG_GLOBALS_STATIC sections as they're unused
674 // medatada, and we don't want them to end up in the output file for
675 // static executables.
676 if (sec.sh_type == SHT_AARCH64_MEMTAG_GLOBALS_STATIC &&
677 !canHaveMemtagGlobals(ctx))
678 sections[i] = &InputSection::discarded;
679 break;
680 }
681 }
682
683 // Read a symbol table.
684 initializeSymbols(obj);
685}
686
687// Sections with SHT_GROUP and comdat bits define comdat section groups.
688// They are identified and deduplicated by group name. This function
689// returns a group name.
690template <class ELFT>
691StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
692 const Elf_Shdr &sec) {
693 typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
694 if (sec.sh_info >= symbols.size())
695 Fatal(ctx) << this << ": invalid symbol index";
696 const typename ELFT::Sym &sym = symbols[sec.sh_info];
697 return CHECK2(sym.getName(this->stringTable), this);
698}
699
700template <class ELFT>
701bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
702 // On a regular link we don't merge sections if -O0 (default is -O1). This
703 // sometimes makes the linker significantly faster, although the output will
704 // be bigger.
705 //
706 // Doing the same for -r would create a problem as it would combine sections
707 // with different sh_entsize. One option would be to just copy every SHF_MERGE
708 // section as is to the output. While this would produce a valid ELF file with
709 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
710 // they see two .debug_str. We could have separate logic for combining
711 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
712 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
713 // logic for -r.
714 if (ctx.arg.optimize == 0 && !ctx.arg.relocatable)
715 return false;
716
717 // A mergeable section with size 0 is useless because they don't have
718 // any data to merge. A mergeable string section with size 0 can be
719 // argued as invalid because it doesn't end with a null character.
720 // We'll avoid a mess by handling them as if they were non-mergeable.
721 if (sec.sh_size == 0)
722 return false;
723
724 // Check for sh_entsize. The ELF spec is not clear about the zero
725 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
726 // the section does not hold a table of fixed-size entries". We know
727 // that Rust 1.13 produces a string mergeable section with a zero
728 // sh_entsize. Here we just accept it rather than being picky about it.
729 uint64_t entSize = sec.sh_entsize;
730 if (entSize == 0)
731 return false;
732 if (sec.sh_size % entSize)
733 ErrAlways(ctx) << this << ":(" << name << "): SHF_MERGE section size ("
734 << uint64_t(sec.sh_size)
735 << ") must be a multiple of sh_entsize (" << entSize << ")";
736 if (sec.sh_flags & SHF_WRITE)
737 Err(ctx) << this << ":(" << name
738 << "): writable SHF_MERGE section is not supported";
739
740 return true;
741}
742
743// This is for --just-symbols.
744//
745// --just-symbols is a very minor feature that allows you to link your
746// output against other existing program, so that if you load both your
747// program and the other program into memory, your output can refer the
748// other program's symbols.
749//
750// When the option is given, we link "just symbols". The section table is
751// initialized with null pointers.
752template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
753 sections.resize(numELFShdrs);
754}
755
756static bool isKnownSpecificSectionType(uint32_t t, uint32_t flags) {
757 if (SHT_LOUSER <= t && t <= SHT_HIUSER && !(flags & SHF_ALLOC))
758 return true;
759 if (SHT_LOOS <= t && t <= SHT_HIOS && !(flags & SHF_OS_NONCONFORMING))
760 return true;
761 // Allow all processor-specific types. This is different from GNU ld.
762 return SHT_LOPROC <= t && t <= SHT_HIPROC;
763}
764
765template <class ELFT>
766void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
767 const llvm::object::ELFFile<ELFT> &obj) {
768 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
769 StringRef shstrtab = CHECK2(obj.getSectionStringTable(objSections), this);
770 uint64_t size = objSections.size();
771 SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups;
772 AArch64BuildAttrSubsections aarch64BAsubSections;
773 bool hasAArch64BuildAttributes = false;
774 for (size_t i = 0; i != size; ++i) {
775 if (this->sections[i] == &InputSection::discarded)
776 continue;
777 const Elf_Shdr &sec = objSections[i];
778 const uint32_t type = sec.sh_type;
779
780 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
781 // if -r is given, we'll let the final link discard such sections.
782 // This is compatible with GNU.
783 if ((sec.sh_flags & SHF_EXCLUDE) && !ctx.arg.relocatable) {
784 if (type == SHT_LLVM_CALL_GRAPH_PROFILE)
785 cgProfileSectionIndex = i;
786 if (type == SHT_LLVM_ADDRSIG) {
787 // We ignore the address-significance table if we know that the object
788 // file was created by objcopy or ld -r. This is because these tools
789 // will reorder the symbols in the symbol table, invalidating the data
790 // in the address-significance table, which refers to symbols by index.
791 if (sec.sh_link != 0)
792 this->addrsigSec = &sec;
793 else if (ctx.arg.icf == ICFLevel::Safe)
794 Warn(ctx) << this
795 << ": --icf=safe conservatively ignores "
796 "SHT_LLVM_ADDRSIG [index "
797 << i
798 << "] with sh_link=0 "
799 "(likely created using objcopy or ld -r)";
800 }
801 this->sections[i] = &InputSection::discarded;
802 continue;
803 }
804
805 // Processor-specific types that do not use the following switch statement.
806 //
807 // Extract Build Attributes section contents into aarch64BAsubSections.
808 // Input objects may contain both build Build Attributes and GNU
809 // properties. We delay processing Build Attributes until we have finished
810 // reading all sections so that we can check that these are consistent.
811 if (type == SHT_AARCH64_ATTRIBUTES && ctx.arg.emachine == EM_AARCH64) {
812 ArrayRef<uint8_t> contents = check(obj.getSectionContents(sec));
813 AArch64AttributeParser attributes;
814 if (Error e = attributes.parse(Section: contents, Endian: ELFT::Endianness)) {
815 StringRef name = check(obj.getSectionName(sec, shstrtab));
816 InputSection isec(*this, sec, name);
817 Warn(ctx) << &isec << ": " << std::move(e);
818 } else {
819 aarch64BAsubSections = extractBuildAttributesSubsections(attributes);
820 hasAArch64BuildAttributes = true;
821 }
822 this->sections[i] = &InputSection::discarded;
823 continue;
824 }
825 switch (type) {
826 case SHT_GROUP: {
827 if (!ctx.arg.relocatable)
828 sections[i] = &InputSection::discarded;
829 StringRef signature =
830 cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable));
831 ArrayRef<Elf_Word> entries =
832 cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec));
833 if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats ||
834 ctx.symtab->comdatGroups.find(Val: CachedHashStringRef(signature))
835 ->second == this)
836 selectedGroups.push_back(entries);
837 break;
838 }
839 case SHT_SYMTAB_SHNDX:
840 shndxTable = CHECK2(obj.getSHNDXTable(sec, objSections), this);
841 break;
842 case SHT_SYMTAB:
843 case SHT_STRTAB:
844 case SHT_REL:
845 case SHT_RELA:
846 case SHT_CREL:
847 case SHT_NULL:
848 break;
849 case SHT_PROGBITS:
850 case SHT_NOTE:
851 case SHT_NOBITS:
852 case SHT_INIT_ARRAY:
853 case SHT_FINI_ARRAY:
854 case SHT_PREINIT_ARRAY:
855 this->sections[i] =
856 createInputSection(idx: i, sec, name: check(obj.getSectionName(sec, shstrtab)));
857 break;
858 case SHT_LLVM_LTO:
859 // Discard .llvm.lto in a relocatable link that does not use the bitcode.
860 // The concatenated output does not properly reflect the linking
861 // semantics. In addition, since we do not use the bitcode wrapper format,
862 // the concatenated raw bitcode would be invalid.
863 if (ctx.arg.relocatable && !ctx.arg.fatLTOObjects) {
864 sections[i] = &InputSection::discarded;
865 break;
866 }
867 [[fallthrough]];
868 default:
869 this->sections[i] =
870 createInputSection(idx: i, sec, name: check(obj.getSectionName(sec, shstrtab)));
871 if (ctx.arg.rejectMismatch &&
872 !isKnownSpecificSectionType(type, sec.sh_flags))
873 Err(ctx) << this->sections[i] << ": unknown section type 0x"
874 << Twine::utohexstr(Val: type);
875 break;
876 }
877 }
878
879 // We have a second loop. It is used to:
880 // 1) handle SHF_LINK_ORDER sections.
881 // 2) create relocation sections. In some cases the section header index of a
882 // relocation section may be smaller than that of the relocated section. In
883 // such cases, the relocation section would attempt to reference a target
884 // section that has not yet been created. For simplicity, delay creation of
885 // relocation sections until now.
886 for (size_t i = 0; i != size; ++i) {
887 if (this->sections[i] == &InputSection::discarded)
888 continue;
889 const Elf_Shdr &sec = objSections[i];
890
891 if (isStaticRelSecType(sec.sh_type)) {
892 // Find a relocation target section and associate this section with that.
893 // Target may have been discarded if it is in a different section group
894 // and the group is discarded, even though it's a violation of the spec.
895 // We handle that situation gracefully by discarding dangling relocation
896 // sections.
897 const uint32_t info = sec.sh_info;
898 InputSectionBase *s = getRelocTarget(idx: i, info);
899 if (!s)
900 continue;
901
902 // ELF spec allows mergeable sections with relocations, but they are rare,
903 // and it is in practice hard to merge such sections by contents, because
904 // applying relocations at end of linking changes section contents. So, we
905 // simply handle such sections as non-mergeable ones. Degrading like this
906 // is acceptable because section merging is optional.
907 if (auto *ms = dyn_cast<MergeInputSection>(Val: s)) {
908 s = makeThreadLocal<InputSection>(args&: ms->file, args&: ms->name, args&: ms->type,
909 args&: ms->flags, args&: ms->addralign, args&: ms->entsize,
910 args: ms->contentMaybeDecompress());
911 sections[info] = s;
912 }
913
914 if (s->relSecIdx != 0)
915 ErrAlways(ctx) << s
916 << ": multiple relocation sections to one section are "
917 "not supported";
918 s->relSecIdx = i;
919
920 // Relocation sections are usually removed from the output, so return
921 // `nullptr` for the normal case. However, if -r or --emit-relocs is
922 // specified, we need to copy them to the output. (Some post link analysis
923 // tools specify --emit-relocs to obtain the information.)
924 if (ctx.arg.copyRelocs) {
925 auto *isec = makeThreadLocal<InputSection>(
926 *this, sec, check(obj.getSectionName(sec, shstrtab)));
927 // If the relocated section is discarded (due to /DISCARD/ or
928 // --gc-sections), the relocation section should be discarded as well.
929 s->dependentSections.push_back(NewVal: isec);
930 sections[i] = isec;
931 }
932 continue;
933 }
934
935 // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
936 // the flag.
937 if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
938 continue;
939
940 InputSectionBase *linkSec = nullptr;
941 if (sec.sh_link < size)
942 linkSec = this->sections[sec.sh_link];
943 if (!linkSec) {
944 ErrAlways(ctx) << this
945 << ": invalid sh_link index: " << uint32_t(sec.sh_link);
946 continue;
947 }
948
949 // A SHF_LINK_ORDER section is discarded if its linked-to section is
950 // discarded.
951 InputSection *isec = cast<InputSection>(this->sections[i]);
952 linkSec->dependentSections.push_back(NewVal: isec);
953 if (!isa<InputSection>(Val: linkSec))
954 ErrAlways(ctx)
955 << "a section " << isec->name
956 << " with SHF_LINK_ORDER should not refer a non-regular section: "
957 << linkSec;
958 }
959
960 // Handle AArch64 Build Attributes and GNU properties:
961 // - Err on mismatched values.
962 // - Store missing values as GNU properties.
963 if (hasAArch64BuildAttributes)
964 handleAArch64BAAndGnuProperties<ELFT>(this, ctx, aarch64BAsubSections);
965
966 for (ArrayRef<Elf_Word> entries : selectedGroups)
967 handleSectionGroup<ELFT>(this->sections, entries);
968}
969
970template <typename ELFT>
971static void parseGnuPropertyNote(Ctx &ctx, ELFFileBase &f,
972 uint32_t featureAndType,
973 ArrayRef<uint8_t> &desc, const uint8_t *base,
974 ArrayRef<uint8_t> *data = nullptr) {
975 auto err = [&](const uint8_t *place) -> ELFSyncStream {
976 auto diag = Err(ctx);
977 diag << &f << ":(" << ".note.gnu.property+0x"
978 << Twine::utohexstr(Val: place - base) << "): ";
979 return diag;
980 };
981
982 while (!desc.empty()) {
983 const uint8_t *place = desc.data();
984 if (desc.size() < 8)
985 return void(err(place) << "program property is too short");
986 uint32_t type = read32<ELFT::Endianness>(desc.data());
987 uint32_t size = read32<ELFT::Endianness>(desc.data() + 4);
988 desc = desc.slice(N: 8);
989 if (desc.size() < size)
990 return void(err(place) << "program property is too short");
991
992 if (type == featureAndType) {
993 // We found a FEATURE_1_AND field. There may be more than one of these
994 // in a .note.gnu.property section, for a relocatable object we
995 // accumulate the bits set.
996 if (size < 4)
997 return void(err(place) << "FEATURE_1_AND entry is too short");
998 f.andFeatures |= read32<ELFT::Endianness>(desc.data());
999 } else if (ctx.arg.emachine == EM_AARCH64 &&
1000 type == GNU_PROPERTY_AARCH64_FEATURE_PAUTH) {
1001 ArrayRef<uint8_t> contents = data ? *data : desc;
1002 if (f.aarch64PauthAbiCoreInfo) {
1003 return void(
1004 err(contents.data())
1005 << "multiple GNU_PROPERTY_AARCH64_FEATURE_PAUTH entries are "
1006 "not supported");
1007 } else if (size != 16) {
1008 return void(err(contents.data())
1009 << "GNU_PROPERTY_AARCH64_FEATURE_PAUTH entry "
1010 "is invalid: expected 16 bytes, but got "
1011 << size);
1012 }
1013 f.aarch64PauthAbiCoreInfo = {
1014 support::endian::read64<ELFT::Endianness>(&desc[0]),
1015 support::endian::read64<ELFT::Endianness>(&desc[8])};
1016 }
1017
1018 // Padding is present in the note descriptor, if necessary.
1019 desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
1020 }
1021}
1022// Read the following info from the .note.gnu.property section and write it to
1023// the corresponding fields in `ObjFile`:
1024// - Feature flags (32 bits) representing x86, AArch64 or RISC-V features for
1025// hardware-assisted call flow control;
1026// - AArch64 PAuth ABI core info (16 bytes).
1027template <class ELFT>
1028static void readGnuProperty(Ctx &ctx, const InputSection &sec,
1029 ObjFile<ELFT> &f) {
1030 using Elf_Nhdr = typename ELFT::Nhdr;
1031 using Elf_Note = typename ELFT::Note;
1032
1033 uint32_t featureAndType;
1034 switch (ctx.arg.emachine) {
1035 case EM_386:
1036 case EM_X86_64:
1037 featureAndType = GNU_PROPERTY_X86_FEATURE_1_AND;
1038 break;
1039 case EM_AARCH64:
1040 featureAndType = GNU_PROPERTY_AARCH64_FEATURE_1_AND;
1041 break;
1042 case EM_RISCV:
1043 featureAndType = GNU_PROPERTY_RISCV_FEATURE_1_AND;
1044 break;
1045 default:
1046 return;
1047 }
1048
1049 ArrayRef<uint8_t> data = sec.content();
1050 auto err = [&](const uint8_t *place) -> ELFSyncStream {
1051 auto diag = Err(ctx);
1052 diag << sec.file << ":(" << sec.name << "+0x"
1053 << Twine::utohexstr(Val: place - sec.content().data()) << "): ";
1054 return diag;
1055 };
1056 while (!data.empty()) {
1057 // Read one NOTE record.
1058 auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
1059 if (data.size() < sizeof(Elf_Nhdr) ||
1060 data.size() < nhdr->getSize(sec.addralign))
1061 return void(err(data.data()) << "data is too short");
1062
1063 Elf_Note note(*nhdr);
1064 if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
1065 data = data.slice(nhdr->getSize(sec.addralign));
1066 continue;
1067 }
1068
1069 // Read a body of a NOTE record, which consists of type-length-value fields.
1070 ArrayRef<uint8_t> desc = note.getDesc(sec.addralign);
1071 const uint8_t *base = sec.content().data();
1072 parseGnuPropertyNote<ELFT>(ctx, f, featureAndType, desc, base, &data);
1073
1074 // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
1075 data = data.slice(nhdr->getSize(sec.addralign));
1076 }
1077}
1078
1079template <class ELFT>
1080InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx, uint32_t info) {
1081 if (info < this->sections.size()) {
1082 InputSectionBase *target = this->sections[info];
1083
1084 // Strictly speaking, a relocation section must be included in the
1085 // group of the section it relocates. However, LLVM 3.3 and earlier
1086 // would fail to do so, so we gracefully handle that case.
1087 if (target == &InputSection::discarded)
1088 return nullptr;
1089
1090 if (target != nullptr)
1091 return target;
1092 }
1093
1094 Err(ctx) << this << ": relocation section (index " << idx
1095 << ") has invalid sh_info (" << info << ')';
1096 return nullptr;
1097}
1098
1099// The function may be called concurrently for different input files. For
1100// allocation, prefer makeThreadLocal which does not require holding a lock.
1101template <class ELFT>
1102InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
1103 const Elf_Shdr &sec,
1104 StringRef name) {
1105 if (name.starts_with(Prefix: ".n")) {
1106 // The GNU linker uses .note.GNU-stack section as a marker indicating
1107 // that the code in the object file does not expect that the stack is
1108 // executable (in terms of NX bit). If all input files have the marker,
1109 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
1110 // make the stack non-executable. Most object files have this section as
1111 // of 2017.
1112 //
1113 // But making the stack non-executable is a norm today for security
1114 // reasons. Failure to do so may result in a serious security issue.
1115 // Therefore, we make LLD always add PT_GNU_STACK unless it is
1116 // explicitly told to do otherwise (by -z execstack). Because the stack
1117 // executable-ness is controlled solely by command line options,
1118 // .note.GNU-stack sections are, with one exception, ignored. Report
1119 // an error if we encounter an executable .note.GNU-stack to force the
1120 // user to explicitly request an executable stack.
1121 if (name == ".note.GNU-stack") {
1122 if ((sec.sh_flags & SHF_EXECINSTR) && !ctx.arg.relocatable &&
1123 ctx.arg.zGnustack != GnuStackKind::Exec) {
1124 Err(ctx) << this
1125 << ": requires an executable stack, but -z execstack is not "
1126 "specified";
1127 }
1128 return &InputSection::discarded;
1129 }
1130
1131 // Object files that use processor features such as Intel Control-Flow
1132 // Enforcement (CET), AArch64 Branch Target Identification BTI or RISC-V
1133 // Zicfilp/Zicfiss extensions, use a .note.gnu.property section containing
1134 // a bitfield of feature bits like the GNU_PROPERTY_X86_FEATURE_1_IBT flag.
1135 //
1136 // Since we merge bitmaps from multiple object files to create a new
1137 // .note.gnu.property containing a single AND'ed bitmap, we discard an input
1138 // file's .note.gnu.property section.
1139 if (name == ".note.gnu.property") {
1140 readGnuProperty<ELFT>(ctx, InputSection(*this, sec, name), *this);
1141 return &InputSection::discarded;
1142 }
1143
1144 // Split stacks is a feature to support a discontiguous stack,
1145 // commonly used in the programming language Go. For the details,
1146 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
1147 // for split stack will include a .note.GNU-split-stack section.
1148 if (name == ".note.GNU-split-stack") {
1149 if (ctx.arg.relocatable) {
1150 ErrAlways(ctx) << "cannot mix split-stack and non-split-stack in a "
1151 "relocatable link";
1152 return &InputSection::discarded;
1153 }
1154 this->splitStack = true;
1155 return &InputSection::discarded;
1156 }
1157
1158 // An object file compiled for split stack, but where some of the
1159 // functions were compiled with the no_split_stack_attribute will
1160 // include a .note.GNU-no-split-stack section.
1161 if (name == ".note.GNU-no-split-stack") {
1162 this->someNoSplitStack = true;
1163 return &InputSection::discarded;
1164 }
1165
1166 // Strip existing .note.gnu.build-id sections so that the output won't have
1167 // more than one build-id. This is not usually a problem because input
1168 // object files normally don't have .build-id sections, but you can create
1169 // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
1170 // against it.
1171 if (name == ".note.gnu.build-id")
1172 return &InputSection::discarded;
1173 }
1174
1175 // The linker merges EH (exception handling) frames and creates a
1176 // .eh_frame_hdr section for runtime. So we handle them with a special
1177 // class. For relocatable outputs, they are just passed through.
1178 if (name == ".eh_frame" && !ctx.arg.relocatable)
1179 return makeThreadLocal<EhInputSection>(*this, sec, name);
1180
1181 if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name))
1182 return makeThreadLocal<MergeInputSection>(*this, sec, name);
1183 return makeThreadLocal<InputSection>(*this, sec, name);
1184}
1185
1186// Initialize symbols. symbols is a parallel array to the corresponding ELF
1187// symbol table.
1188template <class ELFT>
1189void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
1190 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1191 if (!symbols)
1192 symbols = std::make_unique<Symbol *[]>(numSymbols);
1193
1194 // Some entries have been filled by LazyObjFile.
1195 auto *symtab = ctx.symtab.get();
1196 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1197 if (!symbols[i])
1198 symbols[i] = symtab->insert(CHECK2(eSyms[i].getName(stringTable), this));
1199
1200 // Perform symbol resolution on non-local symbols.
1201 SmallVector<unsigned, 32> undefineds;
1202 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1203 const Elf_Sym &eSym = eSyms[i];
1204 uint32_t secIdx = eSym.st_shndx;
1205 if (secIdx == SHN_UNDEF) {
1206 undefineds.push_back(Elt: i);
1207 continue;
1208 }
1209
1210 uint8_t binding = eSym.getBinding();
1211 uint8_t stOther = eSym.st_other;
1212 uint8_t type = eSym.getType();
1213 uint64_t value = eSym.st_value;
1214 uint64_t size = eSym.st_size;
1215
1216 Symbol *sym = symbols[i];
1217 sym->isUsedInRegularObj = true;
1218 if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) {
1219 if (value == 0 || value >= UINT32_MAX)
1220 Err(ctx) << this << ": common symbol '" << sym->getName()
1221 << "' has invalid alignment: " << value;
1222 hasCommonSyms = true;
1223 sym->resolve(ctx, CommonSymbol{ctx, this, StringRef(), binding, stOther,
1224 type, value, size});
1225 continue;
1226 }
1227
1228 // Handle global defined symbols. Defined::section will be set in postParse.
1229 sym->resolve(ctx, Defined{ctx, this, StringRef(), binding, stOther, type,
1230 value, size, nullptr});
1231 }
1232
1233 // Undefined symbols (excluding those defined relative to non-prevailing
1234 // sections) can trigger recursive extract. Process defined symbols first so
1235 // that the relative order between a defined symbol and an undefined symbol
1236 // does not change the symbol resolution behavior. In addition, a set of
1237 // interconnected symbols will all be resolved to the same file, instead of
1238 // being resolved to different files.
1239 for (unsigned i : undefineds) {
1240 const Elf_Sym &eSym = eSyms[i];
1241 Symbol *sym = symbols[i];
1242 sym->resolve(ctx, Undefined{this, StringRef(), eSym.getBinding(),
1243 eSym.st_other, eSym.getType()});
1244 sym->isUsedInRegularObj = true;
1245 sym->referenced = true;
1246 }
1247}
1248
1249template <class ELFT>
1250void ObjFile<ELFT>::initSectionsAndLocalSyms(bool ignoreComdats) {
1251 if (!justSymbols)
1252 initializeSections(ignoreComdats, obj: getObj());
1253
1254 if (!firstGlobal)
1255 return;
1256 SymbolUnion *locals = makeThreadLocalN<SymbolUnion>(firstGlobal);
1257
1258 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1259 for (size_t i = 0, end = firstGlobal; i != end; ++i) {
1260 const Elf_Sym &eSym = eSyms[i];
1261 uint32_t secIdx = eSym.st_shndx;
1262 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1263 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1264 else if (secIdx >= SHN_LORESERVE)
1265 secIdx = 0;
1266 if (LLVM_UNLIKELY(secIdx >= sections.size())) {
1267 Err(ctx) << this << ": invalid section index: " << secIdx;
1268 secIdx = 0;
1269 }
1270 if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL))
1271 ErrAlways(ctx) << this << ": non-local symbol (" << i
1272 << ") found at index < .symtab's sh_info (" << end << ")";
1273
1274 InputSectionBase *sec = sections[secIdx];
1275 uint8_t type = eSym.getType();
1276 if (type == STT_FILE)
1277 sourceFile = CHECK2(eSym.getName(stringTable), this);
1278 unsigned stName = eSym.st_name;
1279 if (LLVM_UNLIKELY(stringTable.size() <= stName)) {
1280 Err(ctx) << this << ": invalid symbol name offset";
1281 stName = 0;
1282 }
1283 StringRef name(stringTable.data() + stName);
1284
1285 symbols[i] = reinterpret_cast<Symbol *>(locals + i);
1286 if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded)
1287 new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type,
1288 /*discardedSecIdx=*/secIdx);
1289 else
1290 new (symbols[i]) Defined(ctx, this, name, STB_LOCAL, eSym.st_other, type,
1291 eSym.st_value, eSym.st_size, sec);
1292 symbols[i]->isUsedInRegularObj = true;
1293 }
1294}
1295
1296// Called after all ObjFile::parse is called for all ObjFiles. This checks
1297// duplicate symbols and may do symbol property merge in the future.
1298template <class ELFT> void ObjFile<ELFT>::postParse() {
1299 static std::mutex mu;
1300 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1301 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1302 const Elf_Sym &eSym = eSyms[i];
1303 Symbol &sym = *symbols[i];
1304 uint32_t secIdx = eSym.st_shndx;
1305 uint8_t binding = eSym.getBinding();
1306 if (LLVM_UNLIKELY(binding != STB_GLOBAL && binding != STB_WEAK &&
1307 binding != STB_GNU_UNIQUE))
1308 Err(ctx) << this << ": symbol (" << i
1309 << ") has invalid binding: " << (int)binding;
1310
1311 // st_value of STT_TLS represents the assigned offset, not the actual
1312 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can
1313 // only be referenced by special TLS relocations. It is usually an error if
1314 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
1315 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS &&
1316 eSym.getType() != STT_NOTYPE)
1317 Err(ctx) << "TLS attribute mismatch: " << &sym << "\n>>> in " << sym.file
1318 << "\n>>> in " << this;
1319
1320 // Handle non-COMMON defined symbol below. !sym.file allows a symbol
1321 // assignment to redefine a symbol without an error.
1322 if (!sym.isDefined() || secIdx == SHN_UNDEF)
1323 continue;
1324 if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE)) {
1325 if (secIdx == SHN_COMMON)
1326 continue;
1327 if (secIdx == SHN_XINDEX)
1328 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1329 else
1330 secIdx = 0;
1331 }
1332
1333 if (LLVM_UNLIKELY(secIdx >= sections.size())) {
1334 Err(ctx) << this << ": invalid section index: " << secIdx;
1335 continue;
1336 }
1337 InputSectionBase *sec = sections[secIdx];
1338 if (sec == &InputSection::discarded) {
1339 if (sym.traced) {
1340 printTraceSymbol(sym: Undefined{this, sym.getName(), sym.binding,
1341 sym.stOther, sym.type, secIdx},
1342 name: sym.getName());
1343 }
1344 if (sym.file == this) {
1345 std::lock_guard<std::mutex> lock(mu);
1346 ctx.nonPrevailingSyms.emplace_back(&sym, secIdx);
1347 }
1348 continue;
1349 }
1350
1351 if (sym.file == this) {
1352 cast<Defined>(Val&: sym).section = sec;
1353 continue;
1354 }
1355
1356 if (sym.binding == STB_WEAK || binding == STB_WEAK)
1357 continue;
1358 std::lock_guard<std::mutex> lock(mu);
1359 ctx.duplicates.push_back(Elt: {&sym, this, sec, eSym.st_value});
1360 }
1361}
1362
1363// The handling of tentative definitions (COMMON symbols) in archives is murky.
1364// A tentative definition will be promoted to a global definition if there are
1365// no non-tentative definitions to dominate it. When we hold a tentative
1366// definition to a symbol and are inspecting archive members for inclusion
1367// there are 2 ways we can proceed:
1368//
1369// 1) Consider the tentative definition a 'real' definition (ie promotion from
1370// tentative to real definition has already happened) and not inspect
1371// archive members for Global/Weak definitions to replace the tentative
1372// definition. An archive member would only be included if it satisfies some
1373// other undefined symbol. This is the behavior Gold uses.
1374//
1375// 2) Consider the tentative definition as still undefined (ie the promotion to
1376// a real definition happens only after all symbol resolution is done).
1377// The linker searches archive members for STB_GLOBAL definitions to
1378// replace the tentative definition with. This is the behavior used by
1379// GNU ld.
1380//
1381// The second behavior is inherited from SysVR4, which based it on the FORTRAN
1382// COMMON BLOCK model. This behavior is needed for proper initialization in old
1383// (pre F90) FORTRAN code that is packaged into an archive.
1384//
1385// The following functions search archive members for definitions to replace
1386// tentative definitions (implementing behavior 2).
1387static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1388 StringRef archiveName) {
1389 IRSymtabFile symtabFile = check(e: readIRSymtab(MBRef: mb));
1390 for (const irsymtab::Reader::SymbolRef &sym :
1391 symtabFile.TheReader.symbols()) {
1392 if (sym.isGlobal() && sym.getName() == symName)
1393 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1394 }
1395 return false;
1396}
1397
1398template <class ELFT>
1399static bool isNonCommonDef(Ctx &ctx, ELFKind ekind, MemoryBufferRef mb,
1400 StringRef symName, StringRef archiveName) {
1401 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(ctx, ekind, mb, archiveName);
1402 obj->init();
1403 StringRef stringtable = obj->getStringTable();
1404
1405 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1406 Expected<StringRef> name = sym.getName(stringtable);
1407 if (name && name.get() == symName)
1408 return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1409 !sym.isCommon();
1410 }
1411 return false;
1412}
1413
1414static bool isNonCommonDef(Ctx &ctx, MemoryBufferRef mb, StringRef symName,
1415 StringRef archiveName) {
1416 switch (getELFKind(ctx, mb, archiveName)) {
1417 case ELF32LEKind:
1418 return isNonCommonDef<ELF32LE>(ctx, ekind: ELF32LEKind, mb, symName, archiveName);
1419 case ELF32BEKind:
1420 return isNonCommonDef<ELF32BE>(ctx, ekind: ELF32BEKind, mb, symName, archiveName);
1421 case ELF64LEKind:
1422 return isNonCommonDef<ELF64LE>(ctx, ekind: ELF64LEKind, mb, symName, archiveName);
1423 case ELF64BEKind:
1424 return isNonCommonDef<ELF64BE>(ctx, ekind: ELF64BEKind, mb, symName, archiveName);
1425 default:
1426 llvm_unreachable("getELFKind");
1427 }
1428}
1429
1430SharedFile::SharedFile(Ctx &ctx, MemoryBufferRef m, StringRef defaultSoName)
1431 : ELFFileBase(ctx, SharedKind, getELFKind(ctx, mb: m, archiveName: ""), m),
1432 soName(defaultSoName), isNeeded(!ctx.arg.asNeeded) {}
1433
1434// Parse the version definitions in the object file if present, and return a
1435// vector whose nth element contains a pointer to the Elf_Verdef for version
1436// identifier n. Version identifiers that are not definitions map to nullptr.
1437template <typename ELFT>
1438static SmallVector<const void *, 0>
1439parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
1440 if (!sec)
1441 return {};
1442
1443 // Build the Verdefs array by following the chain of Elf_Verdef objects
1444 // from the start of the .gnu.version_d section.
1445 SmallVector<const void *, 0> verdefs;
1446 const uint8_t *verdef = base + sec->sh_offset;
1447 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
1448 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1449 verdef += curVerdef->vd_next;
1450 unsigned verdefIndex = curVerdef->vd_ndx;
1451 if (verdefIndex >= verdefs.size())
1452 verdefs.resize(N: verdefIndex + 1);
1453 verdefs[verdefIndex] = curVerdef;
1454 }
1455 return verdefs;
1456}
1457
1458// Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1459// symbol. We detect fatal issues which would cause vulnerabilities, but do not
1460// implement sophisticated error checking like in llvm-readobj because the value
1461// of such diagnostics is low.
1462template <typename ELFT>
1463std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1464 const typename ELFT::Shdr *sec) {
1465 if (!sec)
1466 return {};
1467 std::vector<uint32_t> verneeds;
1468 ArrayRef<uint8_t> data = CHECK2(obj.getSectionContents(*sec), this);
1469 const uint8_t *verneedBuf = data.begin();
1470 for (unsigned i = 0; i != sec->sh_info; ++i) {
1471 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) {
1472 Err(ctx) << this << " has an invalid Verneed";
1473 break;
1474 }
1475 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1476 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1477 for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1478 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) {
1479 Err(ctx) << this << " has an invalid Vernaux";
1480 break;
1481 }
1482 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1483 if (aux->vna_name >= this->stringTable.size()) {
1484 Err(ctx) << this << " has a Vernaux with an invalid vna_name";
1485 break;
1486 }
1487 uint16_t version = aux->vna_other & VERSYM_VERSION;
1488 if (version >= verneeds.size())
1489 verneeds.resize(new_size: version + 1);
1490 verneeds[version] = aux->vna_name;
1491 vernauxBuf += aux->vna_next;
1492 }
1493 verneedBuf += vn->vn_next;
1494 }
1495 return verneeds;
1496}
1497
1498// Parse PT_GNU_PROPERTY segments in DSO. The process is similar to
1499// readGnuProperty, but we don't have the InputSection information.
1500template <typename ELFT>
1501void SharedFile::parseGnuAndFeatures(const ELFFile<ELFT> &obj) {
1502 if (ctx.arg.emachine != EM_AARCH64)
1503 return;
1504 const uint8_t *base = obj.base();
1505 auto phdrs = CHECK2(obj.program_headers(), this);
1506 for (auto phdr : phdrs) {
1507 if (phdr.p_type != PT_GNU_PROPERTY)
1508 continue;
1509 typename ELFT::Note note(
1510 *reinterpret_cast<const typename ELFT::Nhdr *>(base + phdr.p_offset));
1511 if (note.getType() != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU")
1512 continue;
1513
1514 ArrayRef<uint8_t> desc = note.getDesc(phdr.p_align);
1515 parseGnuPropertyNote<ELFT>(ctx, *this, GNU_PROPERTY_AARCH64_FEATURE_1_AND,
1516 desc, base);
1517 }
1518}
1519
1520// We do not usually care about alignments of data in shared object
1521// files because the loader takes care of it. However, if we promote a
1522// DSO symbol to point to .bss due to copy relocation, we need to keep
1523// the original alignment requirements. We infer it in this function.
1524template <typename ELFT>
1525static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1526 const typename ELFT::Sym &sym) {
1527 uint64_t ret = UINT64_MAX;
1528 if (sym.st_value)
1529 ret = 1ULL << llvm::countr_zero(Val: (uint64_t)sym.st_value);
1530 if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1531 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1532 return (ret > UINT32_MAX) ? 0 : ret;
1533}
1534
1535// Fully parse the shared object file.
1536//
1537// This function parses symbol versions. If a DSO has version information,
1538// the file has a ".gnu.version_d" section which contains symbol version
1539// definitions. Each symbol is associated to one version through a table in
1540// ".gnu.version" section. That table is a parallel array for the symbol
1541// table, and each table entry contains an index in ".gnu.version_d".
1542//
1543// The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1544// VER_NDX_GLOBAL. There's no table entry for these special versions in
1545// ".gnu.version_d".
1546//
1547// The file format for symbol versioning is perhaps a bit more complicated
1548// than necessary, but you can easily understand the code if you wrap your
1549// head around the data structure described above.
1550template <class ELFT> void SharedFile::parse() {
1551 using Elf_Dyn = typename ELFT::Dyn;
1552 using Elf_Shdr = typename ELFT::Shdr;
1553 using Elf_Sym = typename ELFT::Sym;
1554 using Elf_Verdef = typename ELFT::Verdef;
1555 using Elf_Versym = typename ELFT::Versym;
1556
1557 ArrayRef<Elf_Dyn> dynamicTags;
1558 const ELFFile<ELFT> obj = this->getObj<ELFT>();
1559 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
1560
1561 const Elf_Shdr *versymSec = nullptr;
1562 const Elf_Shdr *verdefSec = nullptr;
1563 const Elf_Shdr *verneedSec = nullptr;
1564 symbols = std::make_unique<Symbol *[]>(num: numSymbols);
1565
1566 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1567 for (const Elf_Shdr &sec : sections) {
1568 switch (sec.sh_type) {
1569 default:
1570 continue;
1571 case SHT_DYNAMIC:
1572 dynamicTags =
1573 CHECK2(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
1574 break;
1575 case SHT_GNU_versym:
1576 versymSec = &sec;
1577 break;
1578 case SHT_GNU_verdef:
1579 verdefSec = &sec;
1580 break;
1581 case SHT_GNU_verneed:
1582 verneedSec = &sec;
1583 break;
1584 }
1585 }
1586
1587 if (versymSec && numSymbols == 0) {
1588 ErrAlways(ctx) << "SHT_GNU_versym should be associated with symbol table";
1589 return;
1590 }
1591
1592 // Search for a DT_SONAME tag to initialize this->soName.
1593 for (const Elf_Dyn &dyn : dynamicTags) {
1594 if (dyn.d_tag == DT_NEEDED) {
1595 uint64_t val = dyn.getVal();
1596 if (val >= this->stringTable.size()) {
1597 Err(ctx) << this << ": invalid DT_NEEDED entry";
1598 return;
1599 }
1600 dtNeeded.push_back(Elt: this->stringTable.data() + val);
1601 } else if (dyn.d_tag == DT_SONAME) {
1602 uint64_t val = dyn.getVal();
1603 if (val >= this->stringTable.size()) {
1604 Err(ctx) << this << ": invalid DT_SONAME entry";
1605 return;
1606 }
1607 soName = this->stringTable.data() + val;
1608 }
1609 }
1610
1611 // DSOs are uniquified not by filename but by soname.
1612 StringSaver &ss = ctx.saver;
1613 DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
1614 bool wasInserted;
1615 std::tie(args&: it, args&: wasInserted) =
1616 ctx.symtab->soNames.try_emplace(Key: CachedHashStringRef(soName), Args: this);
1617
1618 // If a DSO appears more than once on the command line with and without
1619 // --as-needed, --no-as-needed takes precedence over --as-needed because a
1620 // user can add an extra DSO with --no-as-needed to force it to be added to
1621 // the dependency list.
1622 if (isNeeded)
1623 it->second->isNeeded.store(i: true, m: std::memory_order_relaxed);
1624 if (!wasInserted)
1625 return;
1626
1627 ctx.sharedFiles.push_back(Elt: this);
1628
1629 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1630 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1631 parseGnuAndFeatures<ELFT>(obj);
1632
1633 // Parse ".gnu.version" section which is a parallel array for the symbol
1634 // table. If a given file doesn't have a ".gnu.version" section, we use
1635 // VER_NDX_GLOBAL.
1636 size_t size = numSymbols - firstGlobal;
1637 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1638 if (versymSec) {
1639 ArrayRef<Elf_Versym> versym =
1640 CHECK2(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
1641 this)
1642 .slice(firstGlobal);
1643 for (size_t i = 0; i < size; ++i)
1644 versyms[i] = versym[i].vs_index;
1645 }
1646
1647 // System libraries can have a lot of symbols with versions. Using a
1648 // fixed buffer for computing the versions name (foo@ver) can save a
1649 // lot of allocations.
1650 SmallString<0> versionedNameBuffer;
1651
1652 // Add symbols to the symbol table.
1653 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1654 for (size_t i = 0, e = syms.size(); i != e; ++i) {
1655 const Elf_Sym &sym = syms[i];
1656
1657 // ELF spec requires that all local symbols precede weak or global
1658 // symbols in each symbol table, and the index of first non-local symbol
1659 // is stored to sh_info. If a local symbol appears after some non-local
1660 // symbol, that's a violation of the spec.
1661 StringRef name = CHECK2(sym.getName(stringTable), this);
1662 if (sym.getBinding() == STB_LOCAL) {
1663 Err(ctx) << this << ": invalid local symbol '" << name
1664 << "' in global part of symbol table";
1665 continue;
1666 }
1667
1668 const uint16_t ver = versyms[i], idx = ver & ~VERSYM_HIDDEN;
1669 if (sym.isUndefined()) {
1670 // Index 0 (VER_NDX_LOCAL) is used for unversioned undefined symbols.
1671 // GNU ld versions between 2.35 and 2.45 also generate VER_NDX_GLOBAL
1672 // for this case (https://sourceware.org/PR33577).
1673 if (ver != VER_NDX_LOCAL && ver != VER_NDX_GLOBAL) {
1674 if (idx >= verneeds.size()) {
1675 ErrAlways(ctx) << "corrupt input file: version need index " << idx
1676 << " for symbol " << name
1677 << " is out of bounds\n>>> defined in " << this;
1678 continue;
1679 }
1680 StringRef verName = stringTable.data() + verneeds[idx];
1681 versionedNameBuffer.clear();
1682 name = ss.save(S: (name + "@" + verName).toStringRef(Out&: versionedNameBuffer));
1683 }
1684 Symbol *s = ctx.symtab->addSymbol(
1685 newSym: Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1686 s->isExported = true;
1687 if (sym.getBinding() != STB_WEAK &&
1688 ctx.arg.unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1689 requiredSymbols.push_back(Elt: s);
1690 continue;
1691 }
1692
1693 if (ver == VER_NDX_LOCAL ||
1694 (ver != VER_NDX_GLOBAL && idx >= verdefs.size())) {
1695 // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the
1696 // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns
1697 // VER_NDX_LOCAL. Workaround this bug.
1698 if (ctx.arg.emachine == EM_MIPS && name == "_gp_disp")
1699 continue;
1700 ErrAlways(ctx) << "corrupt input file: version definition index " << idx
1701 << " for symbol " << name
1702 << " is out of bounds\n>>> defined in " << this;
1703 continue;
1704 }
1705
1706 uint32_t alignment = getAlignment<ELFT>(sections, sym);
1707 if (ver == idx) {
1708 auto *s = ctx.symtab->addSymbol(
1709 newSym: SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
1710 sym.getType(), sym.st_value, sym.st_size, alignment});
1711 s->dsoDefined = true;
1712 if (s->file == this)
1713 s->versionId = ver;
1714 }
1715
1716 // Also add the symbol with the versioned name to handle undefined symbols
1717 // with explicit versions.
1718 if (ver == VER_NDX_GLOBAL)
1719 continue;
1720
1721 StringRef verName =
1722 stringTable.data() +
1723 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1724 versionedNameBuffer.clear();
1725 name = (name + "@" + verName).toStringRef(Out&: versionedNameBuffer);
1726 auto *s = ctx.symtab->addSymbol(
1727 newSym: SharedSymbol{*this, ss.save(S: name), sym.getBinding(), sym.st_other,
1728 sym.getType(), sym.st_value, sym.st_size, alignment});
1729 s->dsoDefined = true;
1730 if (s->file == this)
1731 s->versionId = idx;
1732 }
1733}
1734
1735static ELFKind getBitcodeELFKind(const Triple &t) {
1736 if (t.isLittleEndian())
1737 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1738 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1739}
1740
1741static uint16_t getBitcodeMachineKind(Ctx &ctx, StringRef path,
1742 const Triple &t) {
1743 switch (t.getArch()) {
1744 case Triple::aarch64:
1745 case Triple::aarch64_be:
1746 return EM_AARCH64;
1747 case Triple::amdgcn:
1748 case Triple::r600:
1749 return EM_AMDGPU;
1750 case Triple::arm:
1751 case Triple::armeb:
1752 case Triple::thumb:
1753 case Triple::thumbeb:
1754 return EM_ARM;
1755 case Triple::avr:
1756 return EM_AVR;
1757 case Triple::hexagon:
1758 return EM_HEXAGON;
1759 case Triple::loongarch32:
1760 case Triple::loongarch64:
1761 return EM_LOONGARCH;
1762 case Triple::mips:
1763 case Triple::mipsel:
1764 case Triple::mips64:
1765 case Triple::mips64el:
1766 return EM_MIPS;
1767 case Triple::msp430:
1768 return EM_MSP430;
1769 case Triple::ppc:
1770 case Triple::ppcle:
1771 return EM_PPC;
1772 case Triple::ppc64:
1773 case Triple::ppc64le:
1774 return EM_PPC64;
1775 case Triple::riscv32:
1776 case Triple::riscv64:
1777 return EM_RISCV;
1778 case Triple::sparcv9:
1779 return EM_SPARCV9;
1780 case Triple::systemz:
1781 return EM_S390;
1782 case Triple::x86:
1783 return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1784 case Triple::x86_64:
1785 return EM_X86_64;
1786 default:
1787 ErrAlways(ctx) << path
1788 << ": could not infer e_machine from bitcode target triple "
1789 << t.str();
1790 return EM_NONE;
1791 }
1792}
1793
1794static uint8_t getOsAbi(const Triple &t) {
1795 switch (t.getOS()) {
1796 case Triple::AMDHSA:
1797 return ELF::ELFOSABI_AMDGPU_HSA;
1798 case Triple::AMDPAL:
1799 return ELF::ELFOSABI_AMDGPU_PAL;
1800 case Triple::Mesa3D:
1801 return ELF::ELFOSABI_AMDGPU_MESA3D;
1802 default:
1803 return ELF::ELFOSABI_NONE;
1804 }
1805}
1806
1807BitcodeFile::BitcodeFile(Ctx &ctx, MemoryBufferRef mb, StringRef archiveName,
1808 uint64_t offsetInArchive, bool lazy)
1809 : InputFile(ctx, BitcodeKind, mb) {
1810 this->archiveName = archiveName;
1811 this->lazy = lazy;
1812
1813 std::string path = mb.getBufferIdentifier().str();
1814 if (ctx.arg.thinLTOIndexOnly)
1815 path = replaceThinLTOSuffix(ctx, path: mb.getBufferIdentifier());
1816
1817 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1818 // name. If two archives define two members with the same name, this
1819 // causes a collision which result in only one of the objects being taken
1820 // into consideration at LTO time (which very likely causes undefined
1821 // symbols later in the link stage). So we append file offset to make
1822 // filename unique.
1823 StringSaver &ss = ctx.saver;
1824 StringRef name = archiveName.empty()
1825 ? ss.save(S: path)
1826 : ss.save(S: archiveName + "(" + path::filename(path) +
1827 " at " + utostr(X: offsetInArchive) + ")");
1828
1829 MemoryBufferRef mbref(mb.getBuffer(), name);
1830
1831 obj = CHECK2(lto::InputFile::create(mbref), this);
1832 obj->setArchivePathAndName(Path: archiveName, Name: mb.getBufferIdentifier());
1833
1834 Triple t(obj->getTargetTriple());
1835 ekind = getBitcodeELFKind(t);
1836 emachine = getBitcodeMachineKind(ctx, path: mb.getBufferIdentifier(), t);
1837 osabi = getOsAbi(t);
1838}
1839
1840static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1841 switch (gvVisibility) {
1842 case GlobalValue::DefaultVisibility:
1843 return STV_DEFAULT;
1844 case GlobalValue::HiddenVisibility:
1845 return STV_HIDDEN;
1846 case GlobalValue::ProtectedVisibility:
1847 return STV_PROTECTED;
1848 }
1849 llvm_unreachable("unknown visibility");
1850}
1851
1852static void createBitcodeSymbol(Ctx &ctx, Symbol *&sym,
1853 const lto::InputFile::Symbol &objSym,
1854 BitcodeFile &f) {
1855 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1856 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1857 uint8_t visibility = mapVisibility(gvVisibility: objSym.getVisibility());
1858
1859 if (!sym) {
1860 // Symbols can be duplicated in bitcode files because of '#include' and
1861 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1862 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1863 // this way LTO can reference the same string saver's copy rather than
1864 // keeping copies of its own.
1865 objSym.Name = ctx.uniqueSaver.save(S: objSym.getName());
1866 sym = ctx.symtab->insert(name: objSym.getName());
1867 }
1868
1869 if (objSym.isUndefined()) {
1870 Undefined newSym(&f, StringRef(), binding, visibility, type);
1871 sym->resolve(ctx, other: newSym);
1872 sym->referenced = true;
1873 return;
1874 }
1875
1876 if (objSym.isCommon()) {
1877 sym->resolve(ctx, other: CommonSymbol{ctx, &f, StringRef(), binding, visibility,
1878 STT_OBJECT, objSym.getCommonAlignment(),
1879 objSym.getCommonSize()});
1880 } else {
1881 Defined newSym(ctx, &f, StringRef(), binding, visibility, type, 0, 0,
1882 nullptr);
1883 // The definition can be omitted if all bitcode definitions satisfy
1884 // `canBeOmittedFromSymbolTable()` and isUsedInRegularObj is false.
1885 // The latter condition is tested in parseVersionAndComputeIsPreemptible.
1886 sym->ltoCanOmit = objSym.canBeOmittedFromSymbolTable() &&
1887 (!sym->isDefined() || sym->ltoCanOmit);
1888 sym->resolve(ctx, other: newSym);
1889 }
1890}
1891
1892void BitcodeFile::parse() {
1893 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
1894 keptComdats.push_back(
1895 x: s.second == Comdat::NoDeduplicate ||
1896 ctx.symtab->comdatGroups.try_emplace(Key: CachedHashStringRef(s.first), Args: this)
1897 .second);
1898 }
1899
1900 if (numSymbols == 0) {
1901 numSymbols = obj->symbols().size();
1902 symbols = std::make_unique<Symbol *[]>(num: numSymbols);
1903 }
1904 // Process defined symbols first. See the comment in
1905 // ObjFile<ELFT>::initializeSymbols.
1906 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols()))
1907 if (!irSym.isUndefined())
1908 createBitcodeSymbol(ctx, sym&: symbols[i], objSym: irSym, f&: *this);
1909 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols()))
1910 if (irSym.isUndefined())
1911 createBitcodeSymbol(ctx, sym&: symbols[i], objSym: irSym, f&: *this);
1912
1913 for (auto l : obj->getDependentLibraries())
1914 addDependentLibrary(ctx, specifier: l, f: this);
1915}
1916
1917void BitcodeFile::parseLazy() {
1918 numSymbols = obj->symbols().size();
1919 symbols = std::make_unique<Symbol *[]>(num: numSymbols);
1920 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols())) {
1921 // Symbols can be duplicated in bitcode files because of '#include' and
1922 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1923 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1924 // this way LTO can reference the same string saver's copy rather than
1925 // keeping copies of its own.
1926 irSym.Name = ctx.uniqueSaver.save(S: irSym.getName());
1927 if (!irSym.isUndefined()) {
1928 auto *sym = ctx.symtab->insert(name: irSym.getName());
1929 sym->resolve(ctx, other: LazySymbol{*this});
1930 symbols[i] = sym;
1931 }
1932 }
1933}
1934
1935void BitcodeFile::postParse() {
1936 for (auto [i, irSym] : llvm::enumerate(First: obj->symbols())) {
1937 const Symbol &sym = *symbols[i];
1938 if (sym.file == this || !sym.isDefined() || irSym.isUndefined() ||
1939 irSym.isCommon() || irSym.isWeak())
1940 continue;
1941 int c = irSym.getComdatIndex();
1942 if (c != -1 && !keptComdats[c])
1943 continue;
1944 reportDuplicate(ctx, sym, newFile: this, errSec: nullptr, errOffset: 0);
1945 }
1946}
1947
1948void BinaryFile::parse() {
1949 ArrayRef<uint8_t> data = arrayRefFromStringRef(Input: mb.getBuffer());
1950 auto *section =
1951 make<InputSection>(args: this, args: ".data", args: SHT_PROGBITS, args: SHF_ALLOC | SHF_WRITE,
1952 /*addralign=*/args: 8, /*entsize=*/args: 0, args&: data);
1953 sections.push_back(Elt: section);
1954
1955 // For each input file foo that is embedded to a result as a binary
1956 // blob, we define _binary_foo_{start,end,size} symbols, so that
1957 // user programs can access blobs by name. Non-alphanumeric
1958 // characters in a filename are replaced with underscore.
1959 std::string s = "_binary_" + mb.getBufferIdentifier().str();
1960 for (char &c : s)
1961 if (!isAlnum(C: c))
1962 c = '_';
1963
1964 llvm::StringSaver &ss = ctx.saver;
1965 ctx.symtab->addAndCheckDuplicate(
1966 ctx, newSym: Defined{ctx, this, ss.save(S: s + "_start"), STB_GLOBAL, STV_DEFAULT,
1967 STT_OBJECT, 0, 0, section});
1968 ctx.symtab->addAndCheckDuplicate(
1969 ctx, newSym: Defined{ctx, this, ss.save(S: s + "_end"), STB_GLOBAL, STV_DEFAULT,
1970 STT_OBJECT, data.size(), 0, section});
1971 ctx.symtab->addAndCheckDuplicate(
1972 ctx, newSym: Defined{ctx, this, ss.save(S: s + "_size"), STB_GLOBAL, STV_DEFAULT,
1973 STT_OBJECT, data.size(), 0, nullptr});
1974}
1975
1976InputFile *elf::createInternalFile(Ctx &ctx, StringRef name) {
1977 auto *file =
1978 make<InputFile>(args&: ctx, args: InputFile::InternalKind, args: MemoryBufferRef("", name));
1979 // References from an internal file do not lead to --warn-backrefs
1980 // diagnostics.
1981 file->groupId = 0;
1982 return file;
1983}
1984
1985std::unique_ptr<ELFFileBase> elf::createObjFile(Ctx &ctx, MemoryBufferRef mb,
1986 StringRef archiveName,
1987 bool lazy) {
1988 std::unique_ptr<ELFFileBase> f;
1989 switch (getELFKind(ctx, mb, archiveName)) {
1990 case ELF32LEKind:
1991 f = std::make_unique<ObjFile<ELF32LE>>(args&: ctx, args: ELF32LEKind, args&: mb, args&: archiveName);
1992 break;
1993 case ELF32BEKind:
1994 f = std::make_unique<ObjFile<ELF32BE>>(args&: ctx, args: ELF32BEKind, args&: mb, args&: archiveName);
1995 break;
1996 case ELF64LEKind:
1997 f = std::make_unique<ObjFile<ELF64LE>>(args&: ctx, args: ELF64LEKind, args&: mb, args&: archiveName);
1998 break;
1999 case ELF64BEKind:
2000 f = std::make_unique<ObjFile<ELF64BE>>(args&: ctx, args: ELF64BEKind, args&: mb, args&: archiveName);
2001 break;
2002 default:
2003 llvm_unreachable("getELFKind");
2004 }
2005 f->init();
2006 f->lazy = lazy;
2007 return f;
2008}
2009
2010template <class ELFT> void ObjFile<ELFT>::parseLazy() {
2011 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
2012 numSymbols = eSyms.size();
2013 symbols = std::make_unique<Symbol *[]>(numSymbols);
2014
2015 // resolve() may trigger this->extract() if an existing symbol is an undefined
2016 // symbol. If that happens, this function has served its purpose, and we can
2017 // exit from the loop early.
2018 auto *symtab = ctx.symtab.get();
2019 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
2020 if (eSyms[i].st_shndx == SHN_UNDEF)
2021 continue;
2022 symbols[i] = symtab->insert(CHECK2(eSyms[i].getName(stringTable), this));
2023 symbols[i]->resolve(ctx, LazySymbol{*this});
2024 if (!lazy)
2025 break;
2026 }
2027}
2028
2029bool InputFile::shouldExtractForCommon(StringRef name) const {
2030 if (isa<BitcodeFile>(Val: this))
2031 return isBitcodeNonCommonDef(mb, symName: name, archiveName);
2032
2033 return isNonCommonDef(ctx, mb, symName: name, archiveName);
2034}
2035
2036std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
2037 auto [suffix, repl] = ctx.arg.thinLTOObjectSuffixReplace;
2038 if (path.consume_back(Suffix: suffix))
2039 return (path + repl).str();
2040 return std::string(path);
2041}
2042
2043template class elf::ObjFile<ELF32LE>;
2044template class elf::ObjFile<ELF32BE>;
2045template class elf::ObjFile<ELF64LE>;
2046template class elf::ObjFile<ELF64BE>;
2047
2048template void SharedFile::parse<ELF32LE>();
2049template void SharedFile::parse<ELF32BE>();
2050template void SharedFile::parse<ELF64LE>();
2051template void SharedFile::parse<ELF64BE>();
2052