[mlir] Attempt to resolve edge cases in PassPipeline textual format (#118877)
[llvm-project.git] / lld / ELF / Symbols.cpp
blobce1e89f2d080112120dda5601f286b08ca6af405
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 //===----------------------------------------------------------------------===//
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/ErrorHandler.h"
19 #include "llvm/Demangle/Demangle.h"
20 #include "llvm/Support/Compiler.h"
21 #include <cstring>
23 using namespace llvm;
24 using namespace llvm::object;
25 using namespace llvm::ELF;
26 using namespace lld;
27 using namespace lld::elf;
29 static_assert(sizeof(SymbolUnion) <= 64, "SymbolUnion too large");
31 template <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");
39 LLVM_ATTRIBUTE_UNUSED static inline void assertSymbols() {
40 AssertSymbol<Defined>();
41 AssertSymbol<CommonSymbol>();
42 AssertSymbol<Undefined>();
43 AssertSymbol<SharedSymbol>();
44 AssertSymbol<LazySymbol>();
47 // Returns a symbol for an error message.
48 static std::string maybeDemangleSymbol(Ctx &ctx, StringRef symName) {
49 return ctx.arg.demangle ? demangle(symName.str()) : symName.str();
52 std::string elf::toStr(Ctx &ctx, const elf::Symbol &sym) {
53 StringRef name = sym.getName();
54 std::string ret = maybeDemangleSymbol(ctx, name);
56 const char *suffix = sym.getVersionSuffix();
57 if (*suffix == '@')
58 ret += suffix;
59 return ret;
62 const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
63 const Symbol *sym) {
64 return s << toStr(s.ctx, *sym);
67 static uint64_t getSymVA(Ctx &ctx, const Symbol &sym, int64_t addend) {
68 switch (sym.kind()) {
69 case Symbol::DefinedKind: {
70 auto &d = cast<Defined>(sym);
71 SectionBase *isec = d.section;
73 // This is an absolute symbol.
74 if (!isec)
75 return d.value;
77 assert(isec != &InputSection::discarded);
79 uint64_t offset = d.value;
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;
95 // In the typical case, this is actually very simple and boils
96 // down to adding together 3 numbers:
97 // 1. The address of the output section.
98 // 2. The offset of the input section within the output section.
99 // 3. The offset within the input section (this addition happens
100 // inside InputSection::getOffset).
102 // If you understand the data structures involved with this next
103 // line (and how they get built), then you have a pretty good
104 // understanding of the linker.
105 uint64_t va = isec->getVA(offset);
106 if (d.isSection())
107 va -= addend;
109 // MIPS relocatable files can mix regular and microMIPS code.
110 // Linker needs to distinguish such code. To do so microMIPS
111 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
112 // field. Unfortunately, the `MIPS::relocate()` method has
113 // a symbol value only. To pass type of the symbol (regular/microMIPS)
114 // to that routine as well as other places where we write
115 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
116 // field etc) do the same trick as compiler uses to mark microMIPS
117 // for CPU - set the less-significant bit.
118 if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx) &&
119 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.hasFlag(NEEDS_COPY)))
120 va |= 1;
122 if (d.isTls() && !ctx.arg.relocatable) {
123 // Use the address of the TLS segment's first section rather than the
124 // segment's address, because segment addresses aren't initialized until
125 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
126 // for Android relocation packing requires knowing TLS symbol addresses
127 // during section finalization.)
128 if (!ctx.tlsPhdr || !ctx.tlsPhdr->firstSec) {
129 Err(ctx) << d.file
130 << " has an STT_TLS symbol but doesn't have a PT_TLS segment";
131 return 0;
133 return va - ctx.tlsPhdr->firstSec->addr;
135 return va;
137 case Symbol::SharedKind:
138 case Symbol::UndefinedKind:
139 return 0;
140 case Symbol::LazyKind:
141 llvm_unreachable("lazy symbol reached writer");
142 case Symbol::CommonKind:
143 llvm_unreachable("common symbol reached writer");
144 case Symbol::PlaceholderKind:
145 llvm_unreachable("placeholder symbol reached writer");
147 llvm_unreachable("invalid symbol kind");
150 uint64_t Symbol::getVA(Ctx &ctx, int64_t addend) const {
151 return getSymVA(ctx, *this, addend) + addend;
154 uint64_t Symbol::getGotVA(Ctx &ctx) const {
155 if (gotInIgot)
156 return ctx.in.igotPlt->getVA() + getGotPltOffset(ctx);
157 return ctx.in.got->getVA() + getGotOffset(ctx);
160 uint64_t Symbol::getGotOffset(Ctx &ctx) const {
161 return getGotIdx(ctx) * ctx.target->gotEntrySize;
164 uint64_t Symbol::getGotPltVA(Ctx &ctx) const {
165 if (isInIplt)
166 return ctx.in.igotPlt->getVA() + getGotPltOffset(ctx);
167 return ctx.in.gotPlt->getVA() + getGotPltOffset(ctx);
170 uint64_t Symbol::getGotPltOffset(Ctx &ctx) const {
171 if (isInIplt)
172 return getPltIdx(ctx) * ctx.target->gotEntrySize;
173 return (getPltIdx(ctx) + ctx.target->gotPltHeaderEntriesNum) *
174 ctx.target->gotEntrySize;
177 uint64_t Symbol::getPltVA(Ctx &ctx) const {
178 uint64_t outVA = isInIplt ? ctx.in.iplt->getVA() +
179 getPltIdx(ctx) * ctx.target->ipltEntrySize
180 : ctx.in.plt->getVA() + ctx.in.plt->headerSize +
181 getPltIdx(ctx) * ctx.target->pltEntrySize;
183 // While linking microMIPS code PLT code are always microMIPS
184 // code. Set the less-significant bit to track that fact.
185 // See detailed comment in the `getSymVA` function.
186 if (ctx.arg.emachine == EM_MIPS && isMicroMips(ctx))
187 outVA |= 1;
188 return outVA;
191 uint64_t Symbol::getSize() const {
192 if (const auto *dr = dyn_cast<Defined>(this))
193 return dr->size;
194 return cast<SharedSymbol>(this)->size;
197 OutputSection *Symbol::getOutputSection() const {
198 if (auto *s = dyn_cast<Defined>(this)) {
199 if (auto *sec = s->section)
200 return sec->getOutputSection();
201 return nullptr;
203 return nullptr;
206 // If a symbol name contains '@', the characters after that is
207 // a symbol version name. This function parses that.
208 void Symbol::parseSymbolVersion(Ctx &ctx) {
209 // Return if localized by a local: pattern in a version script.
210 if (versionId == VER_NDX_LOCAL)
211 return;
212 StringRef s = getName();
213 size_t pos = s.find('@');
214 if (pos == StringRef::npos)
215 return;
216 StringRef verstr = s.substr(pos + 1);
218 // Truncate the symbol name so that it doesn't include the version string.
219 nameSize = pos;
221 if (verstr.empty())
222 return;
224 // If this is not in this DSO, it is not a definition.
225 if (!isDefined())
226 return;
228 // '@@' in a symbol name means the default version.
229 // It is usually the most recent one.
230 bool isDefault = (verstr[0] == '@');
231 if (isDefault)
232 verstr = verstr.substr(1);
234 for (const VersionDefinition &ver : namedVersionDefs(ctx)) {
235 if (ver.name != verstr)
236 continue;
238 if (isDefault)
239 versionId = ver.id;
240 else
241 versionId = ver.id | VERSYM_HIDDEN;
242 return;
245 // It is an error if the specified version is not defined.
246 // Usually version script is not provided when linking executable,
247 // but we may still want to override a versioned symbol from DSO,
248 // so we do not report error in this case. We also do not error
249 // if the symbol has a local version as it won't be in the dynamic
250 // symbol table.
251 if (ctx.arg.shared && versionId != VER_NDX_LOCAL)
252 ErrAlways(ctx) << file << ": symbol " << s << " has undefined version "
253 << verstr;
256 void Symbol::extract(Ctx &ctx) const {
257 if (file->lazy) {
258 file->lazy = false;
259 parseFile(ctx, file);
263 uint8_t Symbol::computeBinding(Ctx &ctx) const {
264 auto v = visibility();
265 if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
266 return STB_LOCAL;
267 if (binding == STB_GNU_UNIQUE && !ctx.arg.gnuUnique)
268 return STB_GLOBAL;
269 return binding;
272 bool Symbol::includeInDynsym(Ctx &ctx) const {
273 if (computeBinding(ctx) == STB_LOCAL)
274 return false;
275 if (!isDefined() && !isCommon())
276 // This should unconditionally return true, unfortunately glibc -static-pie
277 // expects undefined weak symbols not to exist in .dynsym, e.g.
278 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
279 // __pthread_initialize_minimal reference in csu/libc-start.c.
280 return !(isUndefWeak() && ctx.arg.noDynamicLinker);
282 return exportDynamic ||
283 (ctx.arg.exportDynamic && (isUsedInRegularObj || !ltoCanOmit));
286 // Print out a log message for --trace-symbol.
287 void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
288 std::string s;
289 if (sym.isUndefined())
290 s = ": reference to ";
291 else if (sym.isLazy())
292 s = ": lazy definition of ";
293 else if (sym.isShared())
294 s = ": shared definition of ";
295 else if (sym.isCommon())
296 s = ": common definition of ";
297 else
298 s = ": definition of ";
300 Msg(sym.file->ctx) << sym.file << s << name;
303 static void recordWhyExtract(Ctx &ctx, const InputFile *reference,
304 const InputFile &extracted, const Symbol &sym) {
305 ctx.whyExtractRecords.emplace_back(toStr(ctx, reference), &extracted, sym);
308 void elf::maybeWarnUnorderableSymbol(Ctx &ctx, const Symbol *sym) {
309 if (!ctx.arg.warnSymbolOrdering)
310 return;
312 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning is
313 // emitted. It makes sense to not warn on undefined symbols (excluding those
314 // demoted by demoteSymbols).
316 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
317 // but we don't have to be compatible here.
318 if (sym->isUndefined() && !cast<Undefined>(sym)->discardedSecIdx &&
319 ctx.arg.unresolvedSymbols == UnresolvedPolicy::Ignore)
320 return;
322 const InputFile *file = sym->file;
323 auto *d = dyn_cast<Defined>(sym);
325 auto report = [&](StringRef s) { Warn(ctx) << file << s << sym->getName(); };
327 if (sym->isUndefined()) {
328 if (cast<Undefined>(sym)->discardedSecIdx)
329 report(": unable to order discarded symbol: ");
330 else
331 report(": unable to order undefined symbol: ");
332 } else if (sym->isShared())
333 report(": unable to order shared symbol: ");
334 else if (d && !d->section)
335 report(": unable to order absolute symbol: ");
336 else if (d && isa<OutputSection>(d->section))
337 report(": unable to order synthetic symbol: ");
338 else if (d && !d->section->isLive())
339 report(": unable to order discarded symbol: ");
342 // Returns true if a symbol can be replaced at load-time by a symbol
343 // with the same name defined in other ELF executable or DSO.
344 bool elf::computeIsPreemptible(Ctx &ctx, const Symbol &sym) {
345 assert(!sym.isLocal() || sym.isPlaceholder());
347 // Only symbols with default visibility that appear in dynsym can be
348 // preempted. Symbols with protected visibility cannot be preempted.
349 if (sym.visibility() != STV_DEFAULT)
350 return false;
352 // At this point copy relocations have not been created yet, so any
353 // symbol that is not defined locally is preemptible.
354 if (!sym.isDefined())
355 return true;
357 if (!ctx.arg.shared)
358 return false;
360 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
361 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
362 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
363 // -Bsymbolic-functions.
364 if (ctx.arg.symbolic ||
365 (ctx.arg.bsymbolic == BsymbolicKind::NonWeak &&
366 sym.binding != STB_WEAK) ||
367 (ctx.arg.bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
368 (ctx.arg.bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
369 sym.binding != STB_WEAK))
370 return sym.inDynamicList;
371 return true;
374 void elf::parseVersionAndComputeIsPreemptible(Ctx &ctx) {
375 // Symbol themselves might know their versions because symbols
376 // can contain versions in the form of <name>@<version>.
377 // Let them parse and update their names to exclude version suffix.
378 bool hasDynSymTab = ctx.arg.hasDynSymTab;
379 for (Symbol *sym : ctx.symtab->getSymbols()) {
380 if (sym->hasVersionSuffix)
381 sym->parseSymbolVersion(ctx);
382 sym->isExported = sym->includeInDynsym(ctx);
383 if (hasDynSymTab)
384 sym->isPreemptible = sym->isExported && computeIsPreemptible(ctx, *sym);
388 // Merge symbol properties.
390 // When we have many symbols of the same name, we choose one of them,
391 // and that's the result of symbol resolution. However, symbols that
392 // were not chosen still affect some symbol properties.
393 void Symbol::mergeProperties(const Symbol &other) {
394 // DSO symbols do not affect visibility in the output.
395 if (!other.isShared() && other.visibility() != STV_DEFAULT) {
396 uint8_t v = visibility(), ov = other.visibility();
397 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
401 void Symbol::resolve(Ctx &ctx, const Undefined &other) {
402 if (other.visibility() != STV_DEFAULT) {
403 uint8_t v = visibility(), ov = other.visibility();
404 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
406 // An undefined symbol with non default visibility must be satisfied
407 // in the same DSO.
409 // If this is a non-weak defined symbol in a discarded section, override the
410 // existing undefined symbol for better error message later.
411 if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
412 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
413 other.overwrite(*this);
414 return;
417 if (traced)
418 printTraceSymbol(other, getName());
420 if (isLazy()) {
421 // An undefined weak will not extract archive members. See comment on Lazy
422 // in Symbols.h for the details.
423 if (other.binding == STB_WEAK) {
424 binding = STB_WEAK;
425 type = other.type;
426 return;
429 // Do extra check for --warn-backrefs.
431 // --warn-backrefs is an option to prevent an undefined reference from
432 // extracting an archive member written earlier in the command line. It can
433 // be used to keep compatibility with GNU linkers to some degree. I'll
434 // explain the feature and why you may find it useful in this comment.
436 // lld's symbol resolution semantics is more relaxed than traditional Unix
437 // linkers. For example,
439 // ld.lld foo.a bar.o
441 // succeeds even if bar.o contains an undefined symbol that has to be
442 // resolved by some object file in foo.a. Traditional Unix linkers don't
443 // allow this kind of backward reference, as they visit each file only once
444 // from left to right in the command line while resolving all undefined
445 // symbols at the moment of visiting.
447 // In the above case, since there's no undefined symbol when a linker visits
448 // foo.a, no files are pulled out from foo.a, and because the linker forgets
449 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
450 // that could have been resolved otherwise.
452 // That lld accepts more relaxed form means that (besides it'd make more
453 // sense) you can accidentally write a command line or a build file that
454 // works only with lld, even if you have a plan to distribute it to wider
455 // users who may be using GNU linkers. With --warn-backrefs, you can detect
456 // a library order that doesn't work with other Unix linkers.
458 // The option is also useful to detect cyclic dependencies between static
459 // archives. Again, lld accepts
461 // ld.lld foo.a bar.a
463 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
464 // handled as an error.
466 // Here is how the option works. We assign a group ID to each file. A file
467 // with a smaller group ID can pull out object files from an archive file
468 // with an equal or greater group ID. Otherwise, it is a reverse dependency
469 // and an error.
471 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
472 // files within the same --{start,end}-group get the same group ID. E.g.
474 // ld.lld A B --start-group C D --end-group E
476 // A forms group 0. B form group 1. C and D (including their member object
477 // files) form group 2. E forms group 3. I think that you can see how this
478 // group assignment rule simulates the traditional linker's semantics.
479 bool backref = ctx.arg.warnBackrefs && file->groupId < other.file->groupId;
480 extract(ctx);
482 if (!ctx.arg.whyExtract.empty())
483 recordWhyExtract(ctx, other.file, *file, *this);
485 // We don't report backward references to weak symbols as they can be
486 // overridden later.
488 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
489 // sandwich), where def2 may or may not be the same as def1. We don't want
490 // to warn for this case, so dismiss the warning if we see a subsequent lazy
491 // definition. this->file needs to be saved because in the case of LTO it
492 // may be reset to internalFile or be replaced with a file named lto.tmp.
493 if (backref && !isWeak())
494 ctx.backwardReferences.try_emplace(this,
495 std::make_pair(other.file, file));
496 return;
499 // Undefined symbols in a SharedFile do not change the binding.
500 if (isa<SharedFile>(other.file))
501 return;
503 if (isUndefined() || isShared()) {
504 // The binding will be weak if there is at least one reference and all are
505 // weak. The binding has one opportunity to change to weak: if the first
506 // reference is weak.
507 if (other.binding != STB_WEAK || !referenced)
508 binding = other.binding;
512 // Compare two symbols. Return true if the new symbol should win.
513 bool Symbol::shouldReplace(Ctx &ctx, const Defined &other) const {
514 if (LLVM_UNLIKELY(isCommon())) {
515 if (ctx.arg.warnCommon)
516 Warn(ctx) << "common " << getName() << " is overridden";
517 return !other.isWeak();
519 if (!isDefined())
520 return true;
522 // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
523 // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
524 // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
525 // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
526 // an existing STB_WEAK, there may be discarded section errors because the
527 // selected copy may be in a non-prevailing COMDAT.
528 return !isGlobal() && other.isGlobal();
531 void elf::reportDuplicate(Ctx &ctx, const Symbol &sym, const InputFile *newFile,
532 InputSectionBase *errSec, uint64_t errOffset) {
533 if (ctx.arg.allowMultipleDefinition)
534 return;
535 // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
536 // is sort of proto-comdat. There is actually no duplicate if we have
537 // full support for .gnu.linkonce.
538 const Defined *d = dyn_cast<Defined>(&sym);
539 if (!d || d->getName() == "__x86.get_pc_thunk.bx")
540 return;
541 // Allow absolute symbols with the same value for GNU ld compatibility.
542 if (!d->section && !errSec && errOffset && d->value == errOffset)
543 return;
544 if (!d->section || !errSec) {
545 Err(ctx) << "duplicate symbol: " << &sym << "\n>>> defined in " << sym.file
546 << "\n>>> defined in " << newFile;
547 return;
550 // Construct and print an error message in the form of:
552 // ld.lld: error: duplicate symbol: foo
553 // >>> defined at bar.c:30
554 // >>> bar.o (/home/alice/src/bar.o)
555 // >>> defined at baz.c:563
556 // >>> baz.o in archive libbaz.a
557 auto *sec1 = cast<InputSectionBase>(d->section);
558 auto diag = Err(ctx);
559 diag << "duplicate symbol: " << &sym << "\n>>> defined at ";
560 auto tell = diag.tell();
561 diag << sec1->getSrcMsg(sym, d->value);
562 if (tell != diag.tell())
563 diag << "\n>>> ";
564 diag << sec1->getObjMsg(d->value) << "\n>>> defined at ";
565 tell = diag.tell();
566 diag << errSec->getSrcMsg(sym, errOffset);
567 if (tell != diag.tell())
568 diag << "\n>>> ";
569 diag << errSec->getObjMsg(errOffset);
572 void Symbol::checkDuplicate(Ctx &ctx, const Defined &other) const {
573 if (isDefined() && !isWeak() && !other.isWeak())
574 reportDuplicate(ctx, *this, other.file,
575 dyn_cast_or_null<InputSectionBase>(other.section),
576 other.value);
579 void Symbol::resolve(Ctx &ctx, const CommonSymbol &other) {
580 if (other.visibility() != STV_DEFAULT) {
581 uint8_t v = visibility(), ov = other.visibility();
582 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
584 if (isDefined() && !isWeak()) {
585 if (ctx.arg.warnCommon)
586 Warn(ctx) << "common " << getName() << " is overridden";
587 return;
590 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
591 if (ctx.arg.warnCommon)
592 Warn(ctx) << "multiple common of " << getName();
593 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
594 if (oldSym->size < other.size) {
595 oldSym->file = other.file;
596 oldSym->size = other.size;
598 return;
601 if (auto *s = dyn_cast<SharedSymbol>(this)) {
602 // Increase st_size if the shared symbol has a larger st_size. The shared
603 // symbol may be created from common symbols. The fact that some object
604 // files were linked into a shared object first should not change the
605 // regular rule that picks the largest st_size.
606 uint64_t size = s->size;
607 other.overwrite(*this);
608 if (size > cast<CommonSymbol>(this)->size)
609 cast<CommonSymbol>(this)->size = size;
610 } else {
611 other.overwrite(*this);
615 void Symbol::resolve(Ctx &ctx, const Defined &other) {
616 if (other.visibility() != STV_DEFAULT) {
617 uint8_t v = visibility(), ov = other.visibility();
618 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
620 if (shouldReplace(ctx, other))
621 other.overwrite(*this);
624 void Symbol::resolve(Ctx &ctx, const LazySymbol &other) {
625 if (isPlaceholder()) {
626 other.overwrite(*this);
627 return;
630 if (LLVM_UNLIKELY(!isUndefined())) {
631 // See the comment in resolve(Ctx &, const Undefined &).
632 if (isDefined()) {
633 ctx.backwardReferences.erase(this);
634 } else if (isCommon() && ctx.arg.fortranCommon &&
635 other.file->shouldExtractForCommon(getName())) {
636 // For common objects, we want to look for global or weak definitions that
637 // should be extracted as the canonical definition instead.
638 ctx.backwardReferences.erase(this);
639 other.overwrite(*this);
640 other.extract(ctx);
642 return;
645 // An undefined weak will not extract archive members. See comment on Lazy in
646 // Symbols.h for the details.
647 if (isWeak()) {
648 uint8_t ty = type;
649 other.overwrite(*this);
650 type = ty;
651 binding = STB_WEAK;
652 return;
655 const InputFile *oldFile = file;
656 other.extract(ctx);
657 if (!ctx.arg.whyExtract.empty())
658 recordWhyExtract(ctx, oldFile, *file, *this);
661 void Symbol::resolve(Ctx &ctx, const SharedSymbol &other) {
662 exportDynamic = true;
663 if (isPlaceholder()) {
664 other.overwrite(*this);
665 return;
667 if (isCommon()) {
668 // See the comment in resolveCommon() above.
669 if (other.size > cast<CommonSymbol>(this)->size)
670 cast<CommonSymbol>(this)->size = other.size;
671 return;
673 if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
674 // An undefined symbol with non default visibility must be satisfied
675 // in the same DSO.
676 uint8_t bind = binding;
677 other.overwrite(*this);
678 binding = bind;
679 } else if (traced)
680 printTraceSymbol(other, getName());
683 void Defined::overwrite(Symbol &sym) const {
684 if (isa_and_nonnull<SharedFile>(sym.file))
685 sym.versionId = VER_NDX_GLOBAL;
686 Symbol::overwrite(sym, DefinedKind);
687 auto &s = static_cast<Defined &>(sym);
688 s.value = value;
689 s.size = size;
690 s.section = section;