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