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