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