xref: /llvm-project/lld/ELF/Symbols.cpp (revision f10441ad003236ef3b9e5415a571d2be0c0ce5ce)
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/ErrorHandler.h"
19 #include "llvm/Demangle/Demangle.h"
20 #include "llvm/Support/Compiler.h"
21 #include <cstring>
22 
23 using namespace llvm;
24 using namespace llvm::object;
25 using namespace llvm::ELF;
26 using namespace lld;
27 using namespace lld::elf;
28 
29 static_assert(sizeof(SymbolUnion) <= 64, "SymbolUnion too large");
30 
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");
37 };
38 
39 LLVM_ATTRIBUTE_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.
48 static std::string maybeDemangleSymbol(Ctx &ctx, StringRef symName) {
49   return ctx.arg.demangle ? demangle(symName.str()) : symName.str();
50 }
51 
52 std::string elf::toStr(Ctx &ctx, const elf::Symbol &sym) {
53   StringRef name = sym.getName();
54   std::string ret = maybeDemangleSymbol(ctx, name);
55 
56   const char *suffix = sym.getVersionSuffix();
57   if (*suffix == '@')
58     ret += suffix;
59   return ret;
60 }
61 
62 const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
63                                      const Symbol *sym) {
64   return s << toStr(s.ctx, *sym);
65 }
66 
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;
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 
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).
101     //
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;
108 
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;
121 
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;
132       }
133       return va - ctx.tlsPhdr->firstSec->addr;
134     }
135     return va;
136   }
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");
146   }
147   llvm_unreachable("invalid symbol kind");
148 }
149 
150 uint64_t Symbol::getVA(Ctx &ctx, int64_t addend) const {
151   return getSymVA(ctx, *this, addend) + addend;
152 }
153 
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);
158 }
159 
160 uint64_t Symbol::getGotOffset(Ctx &ctx) const {
161   return getGotIdx(ctx) * ctx.target->gotEntrySize;
162 }
163 
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);
168 }
169 
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;
175 }
176 
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;
182 
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;
189 }
190 
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;
195 }
196 
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;
202   }
203   return nullptr;
204 }
205 
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);
217 
218   // Truncate the symbol name so that it doesn't include the version string.
219   nameSize = pos;
220 
221   if (verstr.empty())
222     return;
223 
224   // If this is not in this DSO, it is not a definition.
225   if (!isDefined())
226     return;
227 
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);
233 
234   for (const VersionDefinition &ver : namedVersionDefs(ctx)) {
235     if (ver.name != verstr)
236       continue;
237 
238     if (isDefault)
239       versionId = ver.id;
240     else
241       versionId = ver.id | VERSYM_HIDDEN;
242     return;
243   }
244 
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;
254 }
255 
256 void Symbol::extract(Ctx &ctx) const {
257   assert(file->lazy);
258   file->lazy = false;
259   parseFile(ctx, file);
260 }
261 
262 uint8_t Symbol::computeBinding(Ctx &ctx) const {
263   auto v = visibility();
264   if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
265     return STB_LOCAL;
266   if (binding == STB_GNU_UNIQUE && !ctx.arg.gnuUnique)
267     return STB_GLOBAL;
268   return binding;
269 }
270 
271 bool Symbol::includeInDynsym(Ctx &ctx) const {
272   if (computeBinding(ctx) == STB_LOCAL)
273     return false;
274   if (!isDefined() && !isCommon())
275     return true;
276 
277   return exportDynamic ||
278          (ctx.arg.exportDynamic && (isUsedInRegularObj || !ltoCanOmit));
279 }
280 
281 // Print out a log message for --trace-symbol.
282 void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
283   std::string s;
284   if (sym.isUndefined())
285     s = ": reference to ";
286   else if (sym.isLazy())
287     s = ": lazy definition of ";
288   else if (sym.isShared())
289     s = ": shared definition of ";
290   else if (sym.isCommon())
291     s = ": common definition of ";
292   else
293     s = ": definition of ";
294 
295   Msg(sym.file->ctx) << sym.file << s << name;
296 }
297 
298 static void recordWhyExtract(Ctx &ctx, const InputFile *reference,
299                              const InputFile &extracted, const Symbol &sym) {
300   ctx.whyExtractRecords.emplace_back(toStr(ctx, reference), &extracted, sym);
301 }
302 
303 void elf::maybeWarnUnorderableSymbol(Ctx &ctx, const Symbol *sym) {
304   if (!ctx.arg.warnSymbolOrdering)
305     return;
306 
307   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning is
308   // emitted. It makes sense to not warn on undefined symbols (excluding those
309   // demoted by demoteSymbols).
310   //
311   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
312   // but we don't have to be compatible here.
313   if (sym->isUndefined() && !cast<Undefined>(sym)->discardedSecIdx &&
314       ctx.arg.unresolvedSymbols == UnresolvedPolicy::Ignore)
315     return;
316 
317   const InputFile *file = sym->file;
318   auto *d = dyn_cast<Defined>(sym);
319 
320   auto report = [&](StringRef s) { Warn(ctx) << file << s << sym->getName(); };
321 
322   if (sym->isUndefined()) {
323     if (cast<Undefined>(sym)->discardedSecIdx)
324       report(": unable to order discarded symbol: ");
325     else
326       report(": unable to order undefined symbol: ");
327   } else if (sym->isShared())
328     report(": unable to order shared symbol: ");
329   else if (d && !d->section)
330     report(": unable to order absolute symbol: ");
331   else if (d && isa<OutputSection>(d->section))
332     report(": unable to order synthetic symbol: ");
333   else if (d && !d->section->isLive())
334     report(": unable to order discarded symbol: ");
335 }
336 
337 // Returns true if a symbol can be replaced at load-time by a symbol
338 // with the same name defined in other ELF executable or DSO.
339 bool elf::computeIsPreemptible(Ctx &ctx, const Symbol &sym) {
340   assert(!sym.isLocal() || sym.isPlaceholder());
341 
342   // Only symbols with default visibility that appear in dynsym can be
343   // preempted. Symbols with protected visibility cannot be preempted.
344   if (sym.visibility() != STV_DEFAULT)
345     return false;
346 
347   // At this point copy relocations have not been created yet, so any
348   // symbol that is not defined locally is preemptible.
349   if (!sym.isDefined())
350     return true;
351 
352   if (!ctx.arg.shared)
353     return false;
354 
355   // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
356   // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
357   // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
358   // -Bsymbolic-functions.
359   if (ctx.arg.symbolic ||
360       (ctx.arg.bsymbolic == BsymbolicKind::NonWeak &&
361        sym.binding != STB_WEAK) ||
362       (ctx.arg.bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
363       (ctx.arg.bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
364        sym.binding != STB_WEAK))
365     return sym.inDynamicList;
366   return true;
367 }
368 
369 void elf::parseVersionAndComputeIsPreemptible(Ctx &ctx) {
370   // Symbol themselves might know their versions because symbols
371   // can contain versions in the form of <name>@<version>.
372   // Let them parse and update their names to exclude version suffix.
373   bool hasDynsym = ctx.hasDynsym;
374   for (Symbol *sym : ctx.symtab->getSymbols()) {
375     if (sym->hasVersionSuffix)
376       sym->parseSymbolVersion(ctx);
377     if (hasDynsym) {
378       sym->isExported = sym->includeInDynsym(ctx);
379       sym->isPreemptible = sym->isExported && computeIsPreemptible(ctx, *sym);
380     }
381   }
382 }
383 
384 // Merge symbol properties.
385 //
386 // When we have many symbols of the same name, we choose one of them,
387 // and that's the result of symbol resolution. However, symbols that
388 // were not chosen still affect some symbol properties.
389 void Symbol::mergeProperties(const Symbol &other) {
390   // DSO symbols do not affect visibility in the output.
391   if (!other.isShared() && other.visibility() != STV_DEFAULT) {
392     uint8_t v = visibility(), ov = other.visibility();
393     setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
394   }
395 }
396 
397 void Symbol::resolve(Ctx &ctx, const Undefined &other) {
398   if (other.visibility() != STV_DEFAULT) {
399     uint8_t v = visibility(), ov = other.visibility();
400     setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
401   }
402   // An undefined symbol with non default visibility must be satisfied
403   // in the same DSO.
404   //
405   // If this is a non-weak defined symbol in a discarded section, override the
406   // existing undefined symbol for better error message later.
407   if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
408       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
409     other.overwrite(*this);
410     return;
411   }
412 
413   if (traced)
414     printTraceSymbol(other, getName());
415 
416   if (isLazy()) {
417     // An undefined weak will not extract archive members. See comment on Lazy
418     // in Symbols.h for the details.
419     if (other.binding == STB_WEAK) {
420       binding = STB_WEAK;
421       type = other.type;
422       return;
423     }
424 
425     // Do extra check for --warn-backrefs.
426     //
427     // --warn-backrefs is an option to prevent an undefined reference from
428     // extracting an archive member written earlier in the command line. It can
429     // be used to keep compatibility with GNU linkers to some degree. I'll
430     // explain the feature and why you may find it useful in this comment.
431     //
432     // lld's symbol resolution semantics is more relaxed than traditional Unix
433     // linkers. For example,
434     //
435     //   ld.lld foo.a bar.o
436     //
437     // succeeds even if bar.o contains an undefined symbol that has to be
438     // resolved by some object file in foo.a. Traditional Unix linkers don't
439     // allow this kind of backward reference, as they visit each file only once
440     // from left to right in the command line while resolving all undefined
441     // symbols at the moment of visiting.
442     //
443     // In the above case, since there's no undefined symbol when a linker visits
444     // foo.a, no files are pulled out from foo.a, and because the linker forgets
445     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
446     // that could have been resolved otherwise.
447     //
448     // That lld accepts more relaxed form means that (besides it'd make more
449     // sense) you can accidentally write a command line or a build file that
450     // works only with lld, even if you have a plan to distribute it to wider
451     // users who may be using GNU linkers. With --warn-backrefs, you can detect
452     // a library order that doesn't work with other Unix linkers.
453     //
454     // The option is also useful to detect cyclic dependencies between static
455     // archives. Again, lld accepts
456     //
457     //   ld.lld foo.a bar.a
458     //
459     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
460     // handled as an error.
461     //
462     // Here is how the option works. We assign a group ID to each file. A file
463     // with a smaller group ID can pull out object files from an archive file
464     // with an equal or greater group ID. Otherwise, it is a reverse dependency
465     // and an error.
466     //
467     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
468     // files within the same --{start,end}-group get the same group ID. E.g.
469     //
470     //   ld.lld A B --start-group C D --end-group E
471     //
472     // A forms group 0. B form group 1. C and D (including their member object
473     // files) form group 2. E forms group 3. I think that you can see how this
474     // group assignment rule simulates the traditional linker's semantics.
475     bool backref = ctx.arg.warnBackrefs && file->groupId < other.file->groupId;
476     extract(ctx);
477 
478     if (!ctx.arg.whyExtract.empty())
479       recordWhyExtract(ctx, other.file, *file, *this);
480 
481     // We don't report backward references to weak symbols as they can be
482     // overridden later.
483     //
484     // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
485     // sandwich), where def2 may or may not be the same as def1. We don't want
486     // to warn for this case, so dismiss the warning if we see a subsequent lazy
487     // definition. this->file needs to be saved because in the case of LTO it
488     // may be reset to internalFile or be replaced with a file named lto.tmp.
489     if (backref && !isWeak())
490       ctx.backwardReferences.try_emplace(this,
491                                          std::make_pair(other.file, file));
492     return;
493   }
494 
495   // Undefined symbols in a SharedFile do not change the binding.
496   if (isa<SharedFile>(other.file))
497     return;
498 
499   if (isUndefined() || isShared()) {
500     // The binding will be weak if there is at least one reference and all are
501     // weak. The binding has one opportunity to change to weak: if the first
502     // reference is weak.
503     if (other.binding != STB_WEAK || !referenced)
504       binding = other.binding;
505   }
506 }
507 
508 // Compare two symbols. Return true if the new symbol should win.
509 bool Symbol::shouldReplace(Ctx &ctx, const Defined &other) const {
510   if (LLVM_UNLIKELY(isCommon())) {
511     if (ctx.arg.warnCommon)
512       Warn(ctx) << "common " << getName() << " is overridden";
513     return !other.isWeak();
514   }
515   if (!isDefined())
516     return true;
517 
518   // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
519   // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
520   // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
521   // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
522   // an existing STB_WEAK, there may be discarded section errors because the
523   // selected copy may be in a non-prevailing COMDAT.
524   return !isGlobal() && other.isGlobal();
525 }
526 
527 void elf::reportDuplicate(Ctx &ctx, const Symbol &sym, const InputFile *newFile,
528                           InputSectionBase *errSec, uint64_t errOffset) {
529   if (ctx.arg.allowMultipleDefinition)
530     return;
531   // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
532   // is sort of proto-comdat. There is actually no duplicate if we have
533   // full support for .gnu.linkonce.
534   const Defined *d = dyn_cast<Defined>(&sym);
535   if (!d || d->getName() == "__x86.get_pc_thunk.bx")
536     return;
537   // Allow absolute symbols with the same value for GNU ld compatibility.
538   if (!d->section && !errSec && errOffset && d->value == errOffset)
539     return;
540   if (!d->section || !errSec) {
541     Err(ctx) << "duplicate symbol: " << &sym << "\n>>> defined in " << sym.file
542              << "\n>>> defined in " << newFile;
543     return;
544   }
545 
546   // Construct and print an error message in the form of:
547   //
548   //   ld.lld: error: duplicate symbol: foo
549   //   >>> defined at bar.c:30
550   //   >>>            bar.o (/home/alice/src/bar.o)
551   //   >>> defined at baz.c:563
552   //   >>>            baz.o in archive libbaz.a
553   auto *sec1 = cast<InputSectionBase>(d->section);
554   auto diag = Err(ctx);
555   diag << "duplicate symbol: " << &sym << "\n>>> defined at ";
556   auto tell = diag.tell();
557   diag << sec1->getSrcMsg(sym, d->value);
558   if (tell != diag.tell())
559     diag << "\n>>>            ";
560   diag << sec1->getObjMsg(d->value) << "\n>>> defined at ";
561   tell = diag.tell();
562   diag << errSec->getSrcMsg(sym, errOffset);
563   if (tell != diag.tell())
564     diag << "\n>>>            ";
565   diag << errSec->getObjMsg(errOffset);
566 }
567 
568 void Symbol::checkDuplicate(Ctx &ctx, const Defined &other) const {
569   if (isDefined() && !isWeak() && !other.isWeak())
570     reportDuplicate(ctx, *this, other.file,
571                     dyn_cast_or_null<InputSectionBase>(other.section),
572                     other.value);
573 }
574 
575 void Symbol::resolve(Ctx &ctx, const CommonSymbol &other) {
576   if (other.visibility() != STV_DEFAULT) {
577     uint8_t v = visibility(), ov = other.visibility();
578     setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
579   }
580   if (isDefined() && !isWeak()) {
581     if (ctx.arg.warnCommon)
582       Warn(ctx) << "common " << getName() << " is overridden";
583     return;
584   }
585 
586   if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
587     if (ctx.arg.warnCommon)
588       Warn(ctx) << "multiple common of " << getName();
589     oldSym->alignment = std::max(oldSym->alignment, other.alignment);
590     if (oldSym->size < other.size) {
591       oldSym->file = other.file;
592       oldSym->size = other.size;
593     }
594     return;
595   }
596 
597   if (auto *s = dyn_cast<SharedSymbol>(this)) {
598     // Increase st_size if the shared symbol has a larger st_size. The shared
599     // symbol may be created from common symbols. The fact that some object
600     // files were linked into a shared object first should not change the
601     // regular rule that picks the largest st_size.
602     uint64_t size = s->size;
603     other.overwrite(*this);
604     if (size > cast<CommonSymbol>(this)->size)
605       cast<CommonSymbol>(this)->size = size;
606   } else {
607     other.overwrite(*this);
608   }
609 }
610 
611 void Symbol::resolve(Ctx &ctx, const Defined &other) {
612   if (other.visibility() != STV_DEFAULT) {
613     uint8_t v = visibility(), ov = other.visibility();
614     setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
615   }
616   if (shouldReplace(ctx, other))
617     other.overwrite(*this);
618 }
619 
620 void Symbol::resolve(Ctx &ctx, const LazySymbol &other) {
621   if (isPlaceholder()) {
622     other.overwrite(*this);
623     return;
624   }
625 
626   if (LLVM_UNLIKELY(!isUndefined())) {
627     // See the comment in resolve(Ctx &, const Undefined &).
628     if (isDefined()) {
629       ctx.backwardReferences.erase(this);
630     } else if (isCommon() && ctx.arg.fortranCommon &&
631                other.file->shouldExtractForCommon(getName())) {
632       // For common objects, we want to look for global or weak definitions that
633       // should be extracted as the canonical definition instead.
634       ctx.backwardReferences.erase(this);
635       other.overwrite(*this);
636       other.extract(ctx);
637     }
638     return;
639   }
640 
641   // An undefined weak will not extract archive members. See comment on Lazy in
642   // Symbols.h for the details.
643   if (isWeak()) {
644     uint8_t ty = type;
645     other.overwrite(*this);
646     type = ty;
647     binding = STB_WEAK;
648     return;
649   }
650 
651   const InputFile *oldFile = file;
652   other.extract(ctx);
653   if (!ctx.arg.whyExtract.empty())
654     recordWhyExtract(ctx, oldFile, *file, *this);
655 }
656 
657 void Symbol::resolve(Ctx &ctx, const SharedSymbol &other) {
658   exportDynamic = true;
659   if (isPlaceholder()) {
660     other.overwrite(*this);
661     return;
662   }
663   if (isCommon()) {
664     // See the comment in resolveCommon() above.
665     if (other.size > cast<CommonSymbol>(this)->size)
666       cast<CommonSymbol>(this)->size = other.size;
667     return;
668   }
669   if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
670     // An undefined symbol with non default visibility must be satisfied
671     // in the same DSO.
672     uint8_t bind = binding;
673     other.overwrite(*this);
674     binding = bind;
675   } else if (traced)
676     printTraceSymbol(other, getName());
677 }
678 
679 void Defined::overwrite(Symbol &sym) const {
680   if (isa_and_nonnull<SharedFile>(sym.file))
681     sym.versionId = VER_NDX_GLOBAL;
682   Symbol::overwrite(sym, DefinedKind);
683   auto &s = static_cast<Defined &>(sym);
684   s.value = value;
685   s.size = size;
686   s.section = section;
687 }
688