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::getPltVA(Ctx &ctx) const {
186 uint64_t outVA = isInIplt ? ctx.in.iplt->getVA() +
187 getPltIdx(ctx) * ctx.target->ipltEntrySize
188 : ctx.in.plt->getVA() + ctx.in.plt->headerSize +
189 getPltIdx(ctx) * ctx.target->pltEntrySize;
190
191 // While linking microMIPS code PLT code are always microMIPS
192 // code. Set the less-significant bit to track that fact.
193 // See detailed comment in the `getSymVA` function.
194 if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx))
195 outVA |= 1;
196 return outVA;
197}
198
199uint64_t Symbol::getSize() const {
200 if (const auto *dr = dyn_cast<Defined>(Val: this))
201 return dr->size;
202 return cast<SharedSymbol>(Val: this)->size;
203}
204
205OutputSection *Symbol::getOutputSection() const {
206 if (auto *s = dyn_cast<Defined>(Val: this)) {
207 if (auto *sec = s->section)
208 return sec->getOutputSection();
209 return nullptr;
210 }
211 return nullptr;
212}
213
214// If a symbol name contains '@', the characters after that is
215// a symbol version name. This function parses that.
216void Symbol::parseSymbolVersion(Ctx &ctx) {
217 // Return if localized by a local: pattern in a version script.
218 if (versionId == VER_NDX_LOCAL)
219 return;
220 StringRef s = getName();
221 size_t pos = s.find(C: '@');
222 if (pos == StringRef::npos)
223 return;
224 StringRef verstr = s.substr(Start: pos + 1);
225
226 // Truncate the symbol name so that it doesn't include the version string.
227 nameSize = pos;
228
229 if (verstr.empty())
230 return;
231
232 // If this is not in this DSO, it is not a definition.
233 if (!isDefined())
234 return;
235
236 // '@@' in a symbol name means the default version.
237 // It is usually the most recent one.
238 bool isDefault = (verstr[0] == '@');
239 if (isDefault)
240 verstr = verstr.substr(Start: 1);
241
242 for (const VersionDefinition &ver : namedVersionDefs(ctx)) {
243 if (ver.name != verstr)
244 continue;
245
246 // Like GNU ld, localize a versioned symbol (foo@v1 or foo@@v1) if a
247 // local: pattern in its own node v1 matches foo and no global: pattern
248 // does.
249 StringRef base = s.take_front(N: pos);
250 std::string demangled = demangle(MangledName: base);
251 auto matches = [&](ArrayRef<SymbolVersion> pats) {
252 for (const SymbolVersion &pat : pats) {
253 StringRef name = pat.isExternCpp ? StringRef(demangled) : base;
254 if (pat.hasWildcard ? SingleStringMatcher(pat.name).match(s: name)
255 : pat.name == name)
256 return true;
257 }
258 return false;
259 };
260 if (!matches(ver.nonLocalPatterns) && matches(ver.localPatterns))
261 versionId = VER_NDX_LOCAL;
262 else
263 versionId = isDefault ? ver.id : ver.id | VERSYM_HIDDEN;
264 return;
265 }
266
267 // It is an error if the specified version is not defined.
268 // Usually version script is not provided when linking executable,
269 // but we may still want to override a versioned symbol from DSO,
270 // so we do not report error in this case. We also do not error
271 // if the symbol has a local version as it won't be in the dynamic
272 // symbol table.
273 if (ctx.arg.shared && versionId != VER_NDX_LOCAL)
274 ErrAlways(ctx) << file << ": symbol " << s << " has undefined version "
275 << verstr;
276}
277
278void Symbol::extract(Ctx &ctx) const {
279 assert(file->lazy);
280 file->lazy = false;
281 parseFile(ctx, file);
282}
283
284uint8_t Symbol::computeBinding(Ctx &ctx) const {
285 auto v = visibility();
286 if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
287 return STB_LOCAL;
288 if (binding == STB_GNU_UNIQUE && !ctx.arg.gnuUnique)
289 return STB_GLOBAL;
290 return binding;
291}
292
293// Print out a log message for --trace-symbol.
294void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
295 std::string s;
296 if (sym.isUndefined())
297 s = ": reference to ";
298 else if (sym.isLazy())
299 s = ": lazy definition of ";
300 else if (sym.isShared())
301 s = ": shared definition of ";
302 else if (sym.isCommon())
303 s = ": common definition of ";
304 else
305 s = ": definition of ";
306
307 Msg(ctx&: sym.file->ctx) << sym.file << s << name;
308}
309
310static void recordWhyExtract(Ctx &ctx, const InputFile *reference,
311 const InputFile &extracted, const Symbol &sym) {
312 ctx.whyExtractRecords.emplace_back(Args: toStr(ctx, f: reference), Args: &extracted, Args: sym);
313}
314
315void elf::maybeWarnUnorderableSymbol(Ctx &ctx, const Symbol *sym) {
316 if (!ctx.arg.warnSymbolOrdering)
317 return;
318
319 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning is
320 // emitted. It makes sense to not warn on undefined symbols (excluding those
321 // demoted by demoteSymbols).
322 //
323 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
324 // but we don't have to be compatible here.
325 if (sym->isUndefined() && !cast<Undefined>(Val: sym)->discardedSecIdx &&
326 ctx.arg.unresolvedSymbols == UnresolvedPolicy::Ignore)
327 return;
328
329 const InputFile *file = sym->file;
330 auto report = [&](StringRef s) { Warn(ctx) << file << s << sym->getName(); };
331 if (auto *d = dyn_cast<Defined>(Val: sym)) {
332 if (!d->section)
333 report(": unable to order absolute symbol: ");
334 else if (isa<OutputSection>(Val: d->section))
335 report(": unable to order synthetic symbol: ");
336 else if (!d->section->isLive())
337 report(": unable to order discarded symbol: ");
338 } else if (sym->isUndefined()) {
339 if (cast<Undefined>(Val: sym)->discardedSecIdx)
340 report(": unable to order discarded symbol: ");
341 else
342 report(": unable to order undefined symbol: ");
343 } else {
344 assert(sym->isShared());
345 report(": unable to order shared symbol: ");
346 }
347}
348
349// Returns true if a symbol can be replaced at load-time by a symbol
350// with the same name defined in other ELF executable or DSO.
351bool elf::computeIsPreemptible(Ctx &ctx, const Symbol &sym) {
352 assert(!sym.isLocal() || sym.isPlaceholder());
353
354 // Only symbols with default visibility that appear in dynsym can be
355 // preempted. Symbols with protected visibility cannot be preempted.
356 if (sym.visibility() != STV_DEFAULT)
357 return false;
358
359 // At this point copy relocations have not been created yet.
360 // Shared symbols are preemptible. Undefined symbols are preemptible
361 // when zDynamicUndefined (default in dynamic linking). Weakness is not
362 // checked, though undefined non-weak would typically trigger relocation
363 // errors unless options like -z undefs are used.
364 if (!sym.isDefined())
365 return !sym.isUndefined() || ctx.arg.zDynamicUndefined;
366
367 if (!ctx.arg.shared)
368 return false;
369
370 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
371 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
372 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
373 // -Bsymbolic-functions.
374 if (ctx.arg.symbolic ||
375 (ctx.arg.bsymbolic == BsymbolicKind::NonWeak &&
376 sym.binding != STB_WEAK) ||
377 (ctx.arg.bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
378 (ctx.arg.bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
379 sym.binding != STB_WEAK))
380 return sym.inDynamicList;
381 return true;
382}
383
384void elf::parseVersionAndComputeIsPreemptible(Ctx &ctx) {
385 // Symbol themselves might know their versions because symbols
386 // can contain versions in the form of <name>@<version>.
387 // Let them parse and update their names to exclude version suffix.
388 // In addition, compute isExported and isPreemptible.
389 for (Symbol *sym : ctx.symtab->getSymbols()) {
390 if (sym->hasVersionSuffix)
391 sym->parseSymbolVersion(ctx);
392 if (sym->computeBinding(ctx) == STB_LOCAL) {
393 sym->isExported = false;
394 continue;
395 }
396 if (!sym->isDefined() && !sym->isCommon()) {
397 sym->isPreemptible = computeIsPreemptible(ctx, sym: *sym);
398 } else if (ctx.arg.exportDynamic &&
399 (sym->isUsedInRegularObj || !sym->ltoCanOmit)) {
400 sym->isExported = true;
401 sym->isPreemptible = computeIsPreemptible(ctx, sym: *sym);
402 }
403 }
404}
405
406// Merge symbol properties.
407//
408// When we have many symbols of the same name, we choose one of them,
409// and that's the result of symbol resolution. However, symbols that
410// were not chosen still affect some symbol properties.
411void Symbol::mergeProperties(const Symbol &other) {
412 // DSO symbols do not affect visibility in the output.
413 if (!other.isShared() && other.visibility() != STV_DEFAULT) {
414 uint8_t v = visibility(), ov = other.visibility();
415 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
416 }
417}
418
419void Symbol::resolve(Ctx &ctx, const Undefined &other) {
420 if (other.visibility() != STV_DEFAULT) {
421 uint8_t v = visibility(), ov = other.visibility();
422 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
423 }
424 // An undefined symbol with non default visibility must be satisfied
425 // in the same DSO.
426 //
427 // If this is a non-weak defined symbol in a discarded section, override the
428 // existing undefined symbol for better error message later.
429 if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
430 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
431 other.overwrite(sym&: *this);
432 return;
433 }
434
435 if (traced)
436 printTraceSymbol(sym: other, name: getName());
437
438 if (isLazy()) {
439 // An undefined weak will not extract archive members. See comment on Lazy
440 // in Symbols.h for the details.
441 if (other.binding == STB_WEAK) {
442 binding = STB_WEAK;
443 type = other.type;
444 return;
445 }
446
447 // Do extra check for --warn-backrefs.
448 //
449 // --warn-backrefs is an option to prevent an undefined reference from
450 // extracting an archive member written earlier in the command line. It can
451 // be used to keep compatibility with GNU linkers to some degree. I'll
452 // explain the feature and why you may find it useful in this comment.
453 //
454 // lld's symbol resolution semantics is more relaxed than traditional Unix
455 // linkers. For example,
456 //
457 // ld.lld foo.a bar.o
458 //
459 // succeeds even if bar.o contains an undefined symbol that has to be
460 // resolved by some object file in foo.a. Traditional Unix linkers don't
461 // allow this kind of backward reference, as they visit each file only once
462 // from left to right in the command line while resolving all undefined
463 // symbols at the moment of visiting.
464 //
465 // In the above case, since there's no undefined symbol when a linker visits
466 // foo.a, no files are pulled out from foo.a, and because the linker forgets
467 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
468 // that could have been resolved otherwise.
469 //
470 // That lld accepts more relaxed form means that (besides it'd make more
471 // sense) you can accidentally write a command line or a build file that
472 // works only with lld, even if you have a plan to distribute it to wider
473 // users who may be using GNU linkers. With --warn-backrefs, you can detect
474 // a library order that doesn't work with other Unix linkers.
475 //
476 // The option is also useful to detect cyclic dependencies between static
477 // archives. Again, lld accepts
478 //
479 // ld.lld foo.a bar.a
480 //
481 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
482 // handled as an error.
483 //
484 // Here is how the option works. We assign a group ID to each file. A file
485 // with a smaller group ID can pull out object files from an archive file
486 // with an equal or greater group ID. Otherwise, it is a reverse dependency
487 // and an error.
488 //
489 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
490 // files within the same --{start,end}-group get the same group ID. E.g.
491 //
492 // ld.lld A B --start-group C D --end-group E
493 //
494 // A forms group 0. B form group 1. C and D (including their member object
495 // files) form group 2. E forms group 3. I think that you can see how this
496 // group assignment rule simulates the traditional linker's semantics.
497 bool backref = ctx.arg.warnBackrefs && file->groupId < other.file->groupId;
498 extract(ctx);
499
500 if (!ctx.arg.whyExtract.empty())
501 recordWhyExtract(ctx, reference: other.file, extracted: *file, sym: *this);
502
503 // We don't report backward references to weak symbols as they can be
504 // overridden later.
505 //
506 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
507 // sandwich), where def2 may or may not be the same as def1. We don't want
508 // to warn for this case, so dismiss the warning if we see a subsequent lazy
509 // definition. this->file needs to be saved because in the case of LTO it
510 // may be reset to internalFile or be replaced with a file named lto.tmp.
511 if (backref && !isWeak())
512 ctx.backwardReferences.try_emplace(Key: this,
513 Args: std::make_pair(x: other.file, y&: file));
514 return;
515 }
516
517 // Undefined symbols in a SharedFile do not change the binding.
518 if (isa<SharedFile>(Val: other.file))
519 return;
520
521 if (isUndefined() || isShared()) {
522 // The binding will be weak if there is at least one reference and all are
523 // weak. The binding has one opportunity to change to weak: if the first
524 // reference is weak.
525 if (other.binding != STB_WEAK || !referenced)
526 binding = other.binding;
527 // -u creates a placeholder Undefined (internalFile, STT_NOTYPE).
528 // Adopt the real file and type from the object file's undefined.
529 if (file == ctx.internalFile) {
530 file = other.file;
531 type = other.type;
532 }
533 }
534}
535
536// Compare two symbols. Return true if the new symbol should win.
537bool Symbol::shouldReplace(Ctx &ctx, const Defined &other) const {
538 if (LLVM_UNLIKELY(isCommon())) {
539 if (ctx.arg.warnCommon)
540 Warn(ctx) << "common " << getName() << " is overridden";
541 return !other.isWeak();
542 }
543 if (!isDefined())
544 return true;
545
546 // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
547 // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
548 // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
549 // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
550 // an existing STB_WEAK, there may be discarded section errors because the
551 // selected copy may be in a non-prevailing COMDAT.
552 return !isGlobal() && other.isGlobal();
553}
554
555void elf::reportDuplicate(Ctx &ctx, const Symbol &sym, const InputFile *newFile,
556 InputSectionBase *errSec, uint64_t errOffset) {
557 if (ctx.arg.allowMultipleDefinition)
558 return;
559 // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
560 // is sort of proto-comdat. There is actually no duplicate if we have
561 // full support for .gnu.linkonce.
562 const Defined *d = dyn_cast<Defined>(Val: &sym);
563 if (!d || d->getName() == "__x86.get_pc_thunk.bx")
564 return;
565 // Allow absolute symbols with the same value for GNU ld compatibility.
566 if (!d->section && !errSec && errOffset && d->value == errOffset)
567 return;
568 if (!d->section || !errSec) {
569 Err(ctx) << "duplicate symbol: " << &sym << "\n>>> defined in " << sym.file
570 << "\n>>> defined in " << newFile;
571 return;
572 }
573
574 // Construct and print an error message in the form of:
575 //
576 // ld.lld: error: duplicate symbol: foo
577 // >>> defined at bar.c:30
578 // >>> bar.o (/home/alice/src/bar.o)
579 // >>> defined at baz.c:563
580 // >>> baz.o in archive libbaz.a
581 auto *sec1 = cast<InputSectionBase>(Val: d->section);
582 auto diag = Err(ctx);
583 diag << "duplicate symbol: " << &sym << "\n>>> defined at ";
584 auto tell = diag.tell();
585 diag << sec1->getSrcMsg(sym, offset: d->value);
586 if (tell != diag.tell())
587 diag << "\n>>> ";
588 diag << sec1->getObjMsg(offset: d->value) << "\n>>> defined at ";
589 tell = diag.tell();
590 diag << errSec->getSrcMsg(sym, offset: errOffset);
591 if (tell != diag.tell())
592 diag << "\n>>> ";
593 diag << errSec->getObjMsg(offset: errOffset);
594}
595
596void Symbol::checkDuplicate(Ctx &ctx, const Defined &other) const {
597 if (!isWeak() && !other.isWeak())
598 reportDuplicate(ctx, sym: *this, newFile: other.file,
599 errSec: dyn_cast_or_null<InputSectionBase>(Val: other.section),
600 errOffset: other.value);
601}
602
603void Symbol::resolve(Ctx &ctx, const CommonSymbol &other) {
604 if (other.visibility() != STV_DEFAULT) {
605 uint8_t v = visibility(), ov = other.visibility();
606 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
607 }
608 if (isDefined() && !isWeak()) {
609 if (ctx.arg.warnCommon)
610 Warn(ctx) << "common " << getName() << " is overridden";
611 return;
612 }
613
614 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(Val: this)) {
615 if (ctx.arg.warnCommon)
616 Warn(ctx) << "multiple common of " << getName();
617 oldSym->alignment = std::max(a: oldSym->alignment, b: other.alignment);
618 if (oldSym->size < other.size) {
619 oldSym->file = other.file;
620 oldSym->size = other.size;
621 }
622 return;
623 }
624
625 if (auto *s = dyn_cast<SharedSymbol>(Val: this)) {
626 // Increase st_size if the shared symbol has a larger st_size. The shared
627 // symbol may be created from common symbols. The fact that some object
628 // files were linked into a shared object first should not change the
629 // regular rule that picks the largest st_size.
630 uint64_t size = s->size;
631 other.overwrite(sym&: *this);
632 if (size > cast<CommonSymbol>(Val: this)->size)
633 cast<CommonSymbol>(Val: this)->size = size;
634 } else {
635 other.overwrite(sym&: *this);
636 }
637}
638
639void Symbol::resolve(Ctx &ctx, const Defined &other) {
640 if (other.visibility() != STV_DEFAULT) {
641 uint8_t v = visibility(), ov = other.visibility();
642 setVisibility(v == STV_DEFAULT ? ov : std::min(a: v, b: ov));
643 }
644 if (shouldReplace(ctx, other))
645 other.overwrite(sym&: *this);
646}
647
648void Symbol::resolve(Ctx &ctx, const LazySymbol &other) {
649 if (isPlaceholder()) {
650 other.overwrite(sym&: *this);
651 return;
652 }
653
654 if (LLVM_UNLIKELY(!isUndefined())) {
655 // See the comment in resolve(Ctx &, const Undefined &).
656 if (isDefined()) {
657 ctx.backwardReferences.erase(Val: this);
658 } else if (isCommon() && ctx.arg.fortranCommon &&
659 other.file->shouldExtractForCommon(name: getName())) {
660 // For common objects, we want to look for global or weak definitions that
661 // should be extracted as the canonical definition instead.
662 ctx.backwardReferences.erase(Val: this);
663 other.overwrite(sym&: *this);
664 other.extract(ctx);
665 }
666 return;
667 }
668
669 // An undefined weak will not extract archive members. See comment on Lazy in
670 // Symbols.h for the details.
671 if (isWeak()) {
672 uint8_t ty = type;
673 other.overwrite(sym&: *this);
674 type = ty;
675 binding = STB_WEAK;
676 return;
677 }
678
679 const InputFile *oldFile = file;
680 other.extract(ctx);
681 if (!ctx.arg.whyExtract.empty())
682 recordWhyExtract(ctx, reference: oldFile, extracted: *file, sym: *this);
683}
684
685void Symbol::resolve(Ctx &ctx, const SharedSymbol &other) {
686 isExported = true;
687 if (isPlaceholder()) {
688 other.overwrite(sym&: *this);
689 return;
690 }
691 if (isCommon()) {
692 // See the comment in resolveCommon() above.
693 if (other.size > cast<CommonSymbol>(Val: this)->size)
694 cast<CommonSymbol>(Val: this)->size = other.size;
695 return;
696 }
697 if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
698 // An undefined symbol with non default visibility must be satisfied
699 // in the same DSO.
700 uint8_t bind = binding;
701 other.overwrite(sym&: *this);
702 binding = bind;
703 } else if (traced)
704 printTraceSymbol(sym: other, name: getName());
705}
706
707void Defined::overwrite(Symbol &sym) const {
708 if (isa_and_nonnull<SharedFile>(Val: sym.file))
709 sym.versionId = VER_NDX_GLOBAL;
710 Symbol::overwrite(sym, k: DefinedKind);
711 auto &s = static_cast<Defined &>(sym);
712 s.value = value;
713 s.size = size;
714 s.section = section;
715}
716