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