1//===- Symbols.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 "Symbols.h"
10#include "Driver.h"
11#include "InputFiles.h"
12#include "InputSection.h"
13#include "OutputSections.h"
14#include "SymbolTable.h"
15#include "SyntheticSections.h"
16#include "Target.h"
17#include "Writer.h"
18#include "lld/Common/Strings.h"
19#include "llvm/Demangle/Demangle.h"
20#include "llvm/Support/Compiler.h"
21#include <cstring>
22
23using namespace llvm;
24using namespace llvm::object;
25using namespace llvm::ELF;
26using namespace lld;
27using namespace lld::elf;
28
29static_assert(sizeof(SymbolUnion) <= 64, "SymbolUnion too large");
30
31template <typename T> struct AssertSymbol {
32 static_assert(std::is_trivially_destructible<T>(),
33 "Symbol types must be trivially destructible");
34 static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
35 static_assert(alignof(T) <= alignof(SymbolUnion),
36 "SymbolUnion not aligned enough");
37};
38
39[[maybe_unused]] static inline void assertSymbols() {
40 AssertSymbol<Defined>();
41 AssertSymbol<CommonSymbol>();
42 AssertSymbol<Undefined>();
43 AssertSymbol<SharedSymbol>();
44 AssertSymbol<LazySymbol>();
45}
46
47// Returns a symbol for an error message.
48static std::string maybeDemangleSymbol(Ctx &ctx, StringRef symName) {
49 return ctx.arg.demangle ? demangle(MangledName: symName.str()) : symName.str();
50}
51
52std::string elf::toStr(Ctx &ctx, const elf::Symbol &sym) {
53 StringRef name = sym.getName();
54 std::string ret = maybeDemangleSymbol(ctx, symName: name);
55
56 const char *suffix = sym.getVersionSuffix();
57 if (*suffix == '@')
58 ret += suffix;
59 return ret;
60}
61
62const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
63 const Symbol *sym) {
64 return s << toStr(ctx&: s.ctx, sym: *sym);
65}
66
67static uint64_t getSymVA(Ctx &ctx, const Symbol &sym, int64_t addend) {
68 switch (sym.kind()) {
69 case Symbol::DefinedKind: {
70 auto &d = cast<Defined>(Val: sym);
71 SectionBase *isec = d.section;
72
73 // This is an absolute symbol.
74 if (!isec)
75 return d.value;
76
77 assert(isec != &InputSection::discarded);
78
79 uint64_t offset = d.value;
80
81 // An object in an SHF_MERGE section might be referenced via a
82 // section symbol (as a hack for reducing the number of local
83 // symbols).
84 // Depending on the addend, the reference via a section symbol
85 // refers to a different object in the merge section.
86 // Since the objects in the merge section are not necessarily
87 // contiguous in the output, the addend can thus affect the final
88 // VA in a non-linear way.
89 // To make this work, we incorporate the addend into the section
90 // offset (and zero out the addend for later processing) so that
91 // we find the right object in the section.
92 if (d.isSection()) {
93 offset += addend;
94 if (auto *ms = dyn_cast<MergeInputSection>(Val: isec);
95 ms && offset >= ms->content().size()) {
96 if (offset > ms->content().size())
97 Err(ctx) << ms << ": offset 0x" << Twine::utohexstr(Val: offset)
98 << " is outside the section";
99 return 0;
100 }
101 }
102
103 // In the typical case, this is actually very simple and boils
104 // down to adding together 3 numbers:
105 // 1. The address of the output section.
106 // 2. The offset of the input section within the output section.
107 // 3. The offset within the input section (this addition happens
108 // inside InputSection::getOffset).
109 //
110 // If you understand the data structures involved with this next
111 // line (and how they get built), then you have a pretty good
112 // understanding of the linker.
113 uint64_t va = isec->getVA(offset);
114 if (d.isSection())
115 va -= addend;
116
117 // MIPS relocatable files can mix regular and microMIPS code.
118 // Linker needs to distinguish such code. To do so microMIPS
119 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
120 // field. Unfortunately, the `MIPS::relocate()` method has
121 // a symbol value only. To pass type of the symbol (regular/microMIPS)
122 // to that routine as well as other places where we write
123 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
124 // field etc) do the same trick as compiler uses to mark microMIPS
125 // for CPU - set the less-significant bit.
126 if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx) &&
127 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.hasFlag(bit: NEEDS_COPY)))
128 va |= 1;
129
130 if (d.isTls() && !ctx.arg.relocatable) {
131 // Use the address of the TLS segment's first section rather than the
132 // segment's address, because segment addresses aren't initialized until
133 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
134 // for Android relocation packing requires knowing TLS symbol addresses
135 // during section finalization.)
136 if (!ctx.tlsPhdr || !ctx.tlsPhdr->firstSec) {
137 Err(ctx) << d.file
138 << " has an STT_TLS symbol but doesn't have a PT_TLS segment";
139 return 0;
140 }
141 return va - ctx.tlsPhdr->firstSec->addr;
142 }
143 return va;
144 }
145 case Symbol::SharedKind:
146 case Symbol::UndefinedKind:
147 return 0;
148 case Symbol::LazyKind:
149 llvm_unreachable("lazy symbol reached writer");
150 case Symbol::CommonKind:
151 llvm_unreachable("common symbol reached writer");
152 case Symbol::PlaceholderKind:
153 llvm_unreachable("placeholder symbol reached writer");
154 }
155 llvm_unreachable("invalid symbol kind");
156}
157
158uint64_t Symbol::getVA(Ctx &ctx, int64_t addend) const {
159 return getSymVA(ctx, sym: *this, addend) + addend;
160}
161
162uint64_t Symbol::getGotVA(Ctx &ctx) const {
163 if (gotInIgot)
164 return ctx.in.igotPlt->getVA() + getGotPltOffset(ctx);
165 return ctx.in.got->getVA() + getGotOffset(ctx);
166}
167
168uint64_t Symbol::getGotOffset(Ctx &ctx) const {
169 return getGotIdx(ctx) * ctx.target->gotEntrySize;
170}
171
172uint64_t Symbol::getGotPltVA(Ctx &ctx) const {
173 if (isInIplt)
174 return ctx.in.igotPlt->getVA() + getGotPltOffset(ctx);
175 return ctx.in.gotPlt->getVA() + getGotPltOffset(ctx);
176}
177
178uint64_t Symbol::getGotPltOffset(Ctx &ctx) const {
179 if (isInIplt)
180 return getPltIdx(ctx) * ctx.target->gotEntrySize;
181 return (getPltIdx(ctx) + ctx.target->gotPltHeaderEntriesNum) *
182 ctx.target->gotEntrySize;
183}
184
185uint64_t Symbol::getPltOffset(Ctx &ctx) const {
186 if (isInIplt)
187 return getPltIdx(ctx) * ctx.target->ipltEntrySize;
188 return ctx.in.plt->headerSize + getPltIdx(ctx) * ctx.target->pltEntrySize;
189}
190
191uint64_t Symbol::getPltVA(Ctx &ctx) const {
192 uint64_t outVA = (isInIplt ? ctx.in.iplt->getVA() : ctx.in.plt->getVA()) +
193 getPltOffset(ctx);
194
195 // While linking microMIPS code PLT code are always microMIPS
196 // code. Set the less-significant bit to track that fact.
197 // See detailed comment in the `getSymVA` function.
198 if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx))
199 outVA |= 1;
200 return outVA;
201}
202
203uint64_t Symbol::getSize() const {
204 if (const auto *dr = dyn_cast<Defined>(Val: this))
205 return dr->size;
206 return cast<SharedSymbol>(Val: this)->size;
207}
208
209OutputSection *Symbol::getOutputSection() const {
210 if (auto *s = dyn_cast<Defined>(Val: this)) {
211 if (auto *sec = s->section)
212 return sec->getOutputSection();
213 return nullptr;
214 }
215 return nullptr;
216}
217
218// If a symbol name contains '@', the characters after that is
219// a symbol version name. This function parses that.
220void Symbol::parseSymbolVersion(Ctx &ctx) {
221 // Return if localized by a local: pattern in a version script.
222 if (versionId == VER_NDX_LOCAL)
223 return;
224 StringRef s = getName();
225 size_t pos = s.find(C: '@');
226 if (pos == StringRef::npos)
227 return;
228 StringRef verstr = s.substr(Start: pos + 1);
229
230 // Truncate the symbol name so that it doesn't include the version string.
231 nameSize = pos;
232
233 if (verstr.empty())
234 return;
235
236 // If this is not in this DSO, it is not a definition.
237 if (!isDefined())
238 return;
239
240 // '@@' in a symbol name means the default version.
241 // It is usually the most recent one.
242 bool isDefault = (verstr[0] == '@');
243 if (isDefault)
244 verstr = verstr.substr(Start: 1);
245
246 for (const VersionDefinition &ver : namedVersionDefs(ctx)) {
247 if (ver.name != verstr)
248 continue;
249
250 // Like GNU ld, localize a versioned symbol (foo@v1 or foo@@v1) if a
251 // local: pattern in its own node v1 matches foo and no global: pattern
252 // does.
253 StringRef base = s.take_front(N: pos);
254 std::string demangled = demangle(MangledName: base);
255 auto matches = [&](ArrayRef<SymbolVersion> pats) {
256 for (const SymbolVersion &pat : pats) {
257 StringRef name = pat.isExternCpp ? StringRef(demangled) : base;
258 if (pat.hasWildcard ? SingleStringMatcher(pat.name).match(s: name)
259 : pat.name == name)
260 return true;
261 }
262 return false;
263 };
264 if (!matches(ver.nonLocalPatterns) && matches(ver.localPatterns))
265 versionId = VER_NDX_LOCAL;
266 else
267 versionId = isDefault ? ver.id : ver.id | VERSYM_HIDDEN;
268 return;
269 }
270
271 // It is an error if the specified version is not defined.
272 // Usually version script is not provided when linking executable,
273 // but we may still want to override a versioned symbol from DSO,
274 // so we do not report error in this case. We also do not error
275 // if the symbol has a local version as it won't be in the dynamic
276 // symbol table.
277 if (ctx.arg.shared && versionId != VER_NDX_LOCAL)
278 ErrAlways(ctx) << file << ": symbol " << s << " has undefined version "
279 << verstr;
280}
281
282void Symbol::extract(Ctx &ctx) const {
283 assert(file->lazy);
284 file->lazy = false;
285 parseFile(ctx, file);
286}
287
288uint8_t Symbol::computeBinding(Ctx &ctx) const {
289 auto v = visibility();
290 if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
291 return STB_LOCAL;
292 if (binding == STB_GNU_UNIQUE && !ctx.arg.gnuUnique)
293 return STB_GLOBAL;
294 return binding;
295}
296
297// Print out a log message for --trace-symbol.
298void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
299 std::string s;
300 if (sym.isUndefined())
301 s = ": reference to ";
302 else if (sym.isLazy())
303 s = ": lazy definition of ";
304 else if (sym.isShared())
305 s = ": shared definition of ";
306 else if (sym.isCommon())
307 s = ": common definition of ";
308 else
309 s = ": definition of ";
310
311 Msg(ctx&: sym.file->ctx) << sym.file << s << name;
312}
313
314static void recordWhyExtract(Ctx &ctx, const InputFile *reference,
315 const InputFile &extracted, const Symbol &sym) {
316 ctx.whyExtractRecords.emplace_back(Args: toStr(ctx, f: reference), Args: &extracted, Args: sym);
317}
318
319void elf::maybeWarnUnorderableSymbol(Ctx &ctx, const Symbol *sym) {
320 if (!ctx.arg.warnSymbolOrdering)
321 return;
322
323 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning is
324 // emitted. It makes sense to not warn on undefined symbols (excluding those
325 // demoted by demoteSymbols).
326 //
327 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
328 // but we don't have to be compatible here.
329 if (sym->isUndefined() && !cast<Undefined>(Val: sym)->discardedSecIdx &&
330 ctx.arg.unresolvedSymbols == UnresolvedPolicy::Ignore)
331 return;
332
333 const InputFile *file = sym->file;
334 auto report = [&](StringRef s) { Warn(ctx) << file << s << sym->getName(); };
335 if (auto *d = dyn_cast<Defined>(Val: sym)) {
336 if (!d->section)
337 report(": unable to order absolute symbol: ");
338 else if (isa<OutputSection>(Val: d->section))
339 report(": unable to order synthetic symbol: ");
340 else if (!d->section->isLive())
341 report(": unable to order discarded symbol: ");
342 } else if (sym->isUndefined()) {
343 if (cast<Undefined>(Val: sym)->discardedSecIdx)
344 report(": unable to order discarded symbol: ");
345 else
346 report(": unable to order undefined symbol: ");
347 } else {
348 assert(sym->isShared());
349 report(": unable to order shared symbol: ");
350 }
351}
352
353// Returns true if a symbol can be replaced at load-time by a symbol
354// with the same name defined in other ELF executable or DSO.
355bool elf::computeIsPreemptible(Ctx &ctx, const Symbol &sym) {
356 assert(!sym.isLocal() || sym.isPlaceholder());
357
358 // Only symbols with default visibility that appear in dynsym can be
359 // preempted. Symbols with protected visibility cannot be preempted.
360 if (sym.visibility() != STV_DEFAULT)
361 return false;
362
363 // At this point copy relocations have not been created yet.
364 // Shared symbols are preemptible. Undefined symbols are preemptible
365 // when zDynamicUndefined (default in dynamic linking). Weakness is not
366 // checked, though undefined non-weak would typically trigger relocation
367 // errors unless options like -z undefs are used.
368 if (!sym.isDefined())
369 return !sym.isUndefined() || ctx.arg.zDynamicUndefined;
370
371 if (!ctx.arg.shared)
372 return false;
373
374 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
375 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
376 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
377 // -Bsymbolic-functions.
378 if (ctx.arg.symbolic ||
379 (ctx.arg.bsymbolic == BsymbolicKind::NonWeak &&
380 sym.binding != STB_WEAK) ||
381 (ctx.arg.bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
382 (ctx.arg.bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
383 sym.binding != STB_WEAK))
384 return sym.inDynamicList;
385 return true;
386}
387
388void elf::parseVersionAndComputeIsPreemptible(Ctx &ctx) {
389 // Symbol themselves might know their versions because symbols
390 // can contain versions in the form of <name>@<version>.
391 // Let them parse and update their names to exclude version suffix.
392 // In addition, compute isExported and isPreemptible.
393 for (Symbol *sym : ctx.symtab->getSymbols()) {
394 if (sym->hasVersionSuffix)
395 sym->parseSymbolVersion(ctx);
396 if (sym->computeBinding(ctx) == STB_LOCAL) {
397 sym->isExported = false;
398 continue;
399 }
400 if (!sym->isDefined() && !sym->isCommon()) {
401 sym->isPreemptible = computeIsPreemptible(ctx, sym: *sym);
402 } else if (ctx.arg.exportDynamic &&
403 (sym->isUsedInRegularObj || !sym->ltoCanOmit)) {
404 sym->isExported = true;
405 sym->isPreemptible = computeIsPreemptible(ctx, sym: *sym);
406 }
407 }
408}
409
410// Merge symbol properties.
411//
412// When we have many symbols of the same name, we choose one of them,
413// and that's the result of symbol resolution. However, symbols that
414// were not chosen still affect some symbol properties.
415void Symbol::mergeProperties(const Symbol &other) {
416 // DSO symbols do not affect visibility in the output.
417 if (!other.isShared() && other.visibility() != STV_DEFAULT) {
418 uint8_t v = visibility(), ov = other.visibility();
419 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
420 }
421}
422
423void Symbol::resolve(Ctx &ctx, const Undefined &other) {
424 if (other.visibility() != STV_DEFAULT) {
425 uint8_t v = visibility(), ov = other.visibility();
426 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
427 }
428 // An undefined symbol with non default visibility must be satisfied
429 // in the same DSO.
430 //
431 // If this is a non-weak defined symbol in a discarded section, override the
432 // existing undefined symbol for better error message later.
433 if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
434 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
435 other.overwrite(sym&: *this);
436 return;
437 }
438
439 if (traced)
440 printTraceSymbol(sym: other, name: getName());
441
442 if (isLazy()) {
443 // An undefined weak will not extract archive members. See comment on Lazy
444 // in Symbols.h for the details.
445 if (other.binding == STB_WEAK) {
446 binding = STB_WEAK;
447 type = other.type;
448 return;
449 }
450
451 // Do extra check for --warn-backrefs.
452 //
453 // --warn-backrefs is an option to prevent an undefined reference from
454 // extracting an archive member written earlier in the command line. It can
455 // be used to keep compatibility with GNU linkers to some degree. I'll
456 // explain the feature and why you may find it useful in this comment.
457 //
458 // lld's symbol resolution semantics is more relaxed than traditional Unix
459 // linkers. For example,
460 //
461 // ld.lld foo.a bar.o
462 //
463 // succeeds even if bar.o contains an undefined symbol that has to be
464 // resolved by some object file in foo.a. Traditional Unix linkers don't
465 // allow this kind of backward reference, as they visit each file only once
466 // from left to right in the command line while resolving all undefined
467 // symbols at the moment of visiting.
468 //
469 // In the above case, since there's no undefined symbol when a linker visits
470 // foo.a, no files are pulled out from foo.a, and because the linker forgets
471 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
472 // that could have been resolved otherwise.
473 //
474 // That lld accepts more relaxed form means that (besides it'd make more
475 // sense) you can accidentally write a command line or a build file that
476 // works only with lld, even if you have a plan to distribute it to wider
477 // users who may be using GNU linkers. With --warn-backrefs, you can detect
478 // a library order that doesn't work with other Unix linkers.
479 //
480 // The option is also useful to detect cyclic dependencies between static
481 // archives. Again, lld accepts
482 //
483 // ld.lld foo.a bar.a
484 //
485 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
486 // handled as an error.
487 //
488 // Here is how the option works. We assign a group ID to each file. A file
489 // with a smaller group ID can pull out object files from an archive file
490 // with an equal or greater group ID. Otherwise, it is a reverse dependency
491 // and an error.
492 //
493 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
494 // files within the same --{start,end}-group get the same group ID. E.g.
495 //
496 // ld.lld A B --start-group C D --end-group E
497 //
498 // A forms group 0. B form group 1. C and D (including their member object
499 // files) form group 2. E forms group 3. I think that you can see how this
500 // group assignment rule simulates the traditional linker's semantics.
501 bool backref = ctx.arg.warnBackrefs && file->groupId < other.file->groupId;
502 extract(ctx);
503
504 if (!ctx.arg.whyExtract.empty())
505 recordWhyExtract(ctx, reference: other.file, extracted: *file, sym: *this);
506
507 // We don't report backward references to weak symbols as they can be
508 // overridden later.
509 //
510 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
511 // sandwich), where def2 may or may not be the same as def1. We don't want
512 // to warn for this case, so dismiss the warning if we see a subsequent lazy
513 // definition. this->file needs to be saved because in the case of LTO it
514 // may be reset to internalFile or be replaced with a file named lto.tmp.
515 if (backref && !isWeak())
516 ctx.backwardReferences.try_emplace(Key: this,
517 Args: std::make_pair(x: other.file, y&: file));
518 return;
519 }
520
521 // Undefined symbols in a SharedFile do not change the binding.
522 if (isa<SharedFile>(Val: other.file))
523 return;
524
525 if (isUndefined() || isShared()) {
526 // The binding will be weak if there is at least one reference and all are
527 // weak. The binding has one opportunity to change to weak: if the first
528 // reference is weak.
529 if (other.binding != STB_WEAK || !referenced)
530 binding = other.binding;
531 // -u creates a placeholder Undefined (internalFile, STT_NOTYPE).
532 // Adopt the real file and type from the object file's undefined.
533 if (file == ctx.internalFile) {
534 file = other.file;
535 type = other.type;
536 }
537 }
538}
539
540// Compare two symbols. Return true if the new symbol should win.
541bool Symbol::shouldReplace(Ctx &ctx, const Defined &other) const {
542 if (LLVM_UNLIKELY(isCommon())) {
543 if (ctx.arg.warnCommon)
544 Warn(ctx) << "common " << getName() << " is overridden";
545 return !other.isWeak();
546 }
547 if (!isDefined())
548 return true;
549
550 // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
551 // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
552 // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
553 // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
554 // an existing STB_WEAK, there may be discarded section errors because the
555 // selected copy may be in a non-prevailing COMDAT.
556 return !isGlobal() && other.isGlobal();
557}
558
559void elf::reportDuplicate(Ctx &ctx, const Symbol &sym, const InputFile *newFile,
560 InputSectionBase *errSec, uint64_t errOffset) {
561 if (ctx.arg.allowMultipleDefinition)
562 return;
563 // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
564 // is sort of proto-comdat. There is actually no duplicate if we have
565 // full support for .gnu.linkonce.
566 const Defined *d = dyn_cast<Defined>(Val: &sym);
567 if (!d || d->getName() == "__x86.get_pc_thunk.bx")
568 return;
569 // Allow absolute symbols with the same value for GNU ld compatibility.
570 if (!d->section && !errSec && errOffset && d->value == errOffset)
571 return;
572 if (!d->section || !errSec) {
573 Err(ctx) << "duplicate symbol: " << &sym << "\n>>> defined in " << sym.file
574 << "\n>>> defined in " << newFile;
575 return;
576 }
577
578 // Construct and print an error message in the form of:
579 //
580 // ld.lld: error: duplicate symbol: foo
581 // >>> defined at bar.c:30
582 // >>> bar.o (/home/alice/src/bar.o)
583 // >>> defined at baz.c:563
584 // >>> baz.o in archive libbaz.a
585 auto *sec1 = cast<InputSectionBase>(Val: d->section);
586 auto diag = Err(ctx);
587 diag << "duplicate symbol: " << &sym << "\n>>> defined at ";
588 auto tell = diag.tell();
589 diag << sec1->getSrcMsg(sym, offset: d->value);
590 if (tell != diag.tell())
591 diag << "\n>>> ";
592 diag << sec1->getObjMsg(offset: d->value) << "\n>>> defined at ";
593 tell = diag.tell();
594 diag << errSec->getSrcMsg(sym, offset: errOffset);
595 if (tell != diag.tell())
596 diag << "\n>>> ";
597 diag << errSec->getObjMsg(offset: errOffset);
598}
599
600void Symbol::checkDuplicate(Ctx &ctx, const Defined &other) const {
601 if (!isWeak() && !other.isWeak())
602 reportDuplicate(ctx, sym: *this, newFile: other.file,
603 errSec: dyn_cast_or_null<InputSectionBase>(Val: other.section),
604 errOffset: other.value);
605}
606
607void Symbol::resolve(Ctx &ctx, const CommonSymbol &other) {
608 if (other.visibility() != STV_DEFAULT) {
609 uint8_t v = visibility(), ov = other.visibility();
610 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
611 }
612 if (isDefined() && !isWeak()) {
613 if (ctx.arg.warnCommon)
614 Warn(ctx) << "common " << getName() << " is overridden";
615 return;
616 }
617
618 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(Val: this)) {
619 if (ctx.arg.warnCommon)
620 Warn(ctx) << "multiple common of " << getName();
621 oldSym->alignment = std::max(a: oldSym->alignment, b: other.alignment);
622 if (oldSym->size < other.size) {
623 oldSym->file = other.file;
624 oldSym->size = other.size;
625 }
626 return;
627 }
628
629 if (auto *s = dyn_cast<SharedSymbol>(Val: this)) {
630 // Increase st_size if the shared symbol has a larger st_size. The shared
631 // symbol may be created from common symbols. The fact that some object
632 // files were linked into a shared object first should not change the
633 // regular rule that picks the largest st_size.
634 uint64_t size = s->size;
635 other.overwrite(sym&: *this);
636 if (size > cast<CommonSymbol>(Val: this)->size)
637 cast<CommonSymbol>(Val: this)->size = size;
638 } else {
639 other.overwrite(sym&: *this);
640 }
641}
642
643void Symbol::resolve(Ctx &ctx, const Defined &other) {
644 if (other.visibility() != STV_DEFAULT) {
645 uint8_t v = visibility(), ov = other.visibility();
646 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
647 }
648 if (shouldReplace(ctx, other))
649 other.overwrite(sym&: *this);
650}
651
652void Symbol::resolve(Ctx &ctx, const LazySymbol &other) {
653 if (isPlaceholder()) {
654 other.overwrite(sym&: *this);
655 return;
656 }
657
658 if (LLVM_UNLIKELY(!isUndefined())) {
659 // See the comment in resolve(Ctx &, const Undefined &).
660 if (isDefined()) {
661 ctx.backwardReferences.erase(Val: this);
662 } else if (isCommon() && ctx.arg.fortranCommon &&
663 other.file->shouldExtractForCommon(name: getName())) {
664 // For common objects, we want to look for global or weak definitions that
665 // should be extracted as the canonical definition instead.
666 ctx.backwardReferences.erase(Val: this);
667 other.overwrite(sym&: *this);
668 other.extract(ctx);
669 }
670 return;
671 }
672
673 // An undefined weak will not extract archive members. See comment on Lazy in
674 // Symbols.h for the details.
675 if (isWeak()) {
676 uint8_t ty = type;
677 other.overwrite(sym&: *this);
678 type = ty;
679 binding = STB_WEAK;
680 return;
681 }
682
683 const InputFile *oldFile = file;
684 other.extract(ctx);
685 if (!ctx.arg.whyExtract.empty())
686 recordWhyExtract(ctx, reference: oldFile, extracted: *file, sym: *this);
687}
688
689void Symbol::resolve(Ctx &ctx, const SharedSymbol &other) {
690 isExported = true;
691 if (isPlaceholder()) {
692 other.overwrite(sym&: *this);
693 return;
694 }
695 if (isCommon()) {
696 // See the comment in resolveCommon() above.
697 if (other.size > cast<CommonSymbol>(Val: this)->size)
698 cast<CommonSymbol>(Val: this)->size = other.size;
699 return;
700 }
701 if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
702 // An undefined symbol with non default visibility must be satisfied
703 // in the same DSO.
704 uint8_t bind = binding;
705 other.overwrite(sym&: *this);
706 binding = bind;
707 } else if (traced)
708 printTraceSymbol(sym: other, name: getName());
709}
710
711void Defined::overwrite(Symbol &sym) const {
712 if (isa_and_nonnull<SharedFile>(Val: sym.file))
713 sym.versionId = VER_NDX_GLOBAL;
714 Symbol::overwrite(sym, k: DefinedKind);
715 auto &s = static_cast<Defined &>(sym);
716 s.value = value;
717 s.size = size;
718 s.section = section;
719}
720