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