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