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