xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision ba03bcbc)
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 the dynamic list is present, it specifies preemptable symbols in a DSO.
369   if (config->hasDynamicList)
370     return sym.inDynamicList;
371 
372   // -Bsymbolic means that definitions are not preempted.
373   if (config->bsymbolic || (config->bsymbolicFunctions && sym.isFunc()))
374     return false;
375   return true;
376 }
377 
378 void elf::reportBackrefs() {
379   for (auto &it : backwardReferences) {
380     const Symbol &sym = *it.first;
381     warn("backward reference detected: " + sym.getName() + " in " +
382          toString(it.second) + " refers to " + toString(sym.file));
383   }
384 }
385 
386 static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
387   if (va == STV_DEFAULT)
388     return vb;
389   if (vb == STV_DEFAULT)
390     return va;
391   return std::min(va, vb);
392 }
393 
394 // Merge symbol properties.
395 //
396 // When we have many symbols of the same name, we choose one of them,
397 // and that's the result of symbol resolution. However, symbols that
398 // were not chosen still affect some symbol properties.
399 void Symbol::mergeProperties(const Symbol &other) {
400   if (other.exportDynamic)
401     exportDynamic = true;
402   if (other.isUsedInRegularObj)
403     isUsedInRegularObj = true;
404 
405   // DSO symbols do not affect visibility in the output.
406   if (!other.isShared())
407     visibility = getMinVisibility(visibility, other.visibility);
408 }
409 
410 void Symbol::resolve(const Symbol &other) {
411   mergeProperties(other);
412 
413   if (isPlaceholder()) {
414     replace(other);
415     return;
416   }
417 
418   switch (other.kind()) {
419   case Symbol::UndefinedKind:
420     resolveUndefined(cast<Undefined>(other));
421     break;
422   case Symbol::CommonKind:
423     resolveCommon(cast<CommonSymbol>(other));
424     break;
425   case Symbol::DefinedKind:
426     resolveDefined(cast<Defined>(other));
427     break;
428   case Symbol::LazyArchiveKind:
429     resolveLazy(cast<LazyArchive>(other));
430     break;
431   case Symbol::LazyObjectKind:
432     resolveLazy(cast<LazyObject>(other));
433     break;
434   case Symbol::SharedKind:
435     resolveShared(cast<SharedSymbol>(other));
436     break;
437   case Symbol::PlaceholderKind:
438     llvm_unreachable("bad symbol kind");
439   }
440 }
441 
442 void Symbol::resolveUndefined(const Undefined &other) {
443   // An undefined symbol with non default visibility must be satisfied
444   // in the same DSO.
445   //
446   // If this is a non-weak defined symbol in a discarded section, override the
447   // existing undefined symbol for better error message later.
448   if ((isShared() && other.visibility != STV_DEFAULT) ||
449       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
450     replace(other);
451     return;
452   }
453 
454   if (traced)
455     printTraceSymbol(&other);
456 
457   if (isLazy()) {
458     // An undefined weak will not fetch archive members. See comment on Lazy in
459     // Symbols.h for the details.
460     if (other.binding == STB_WEAK) {
461       binding = STB_WEAK;
462       type = other.type;
463       return;
464     }
465 
466     // Do extra check for --warn-backrefs.
467     //
468     // --warn-backrefs is an option to prevent an undefined reference from
469     // fetching an archive member written earlier in the command line. It can be
470     // used to keep compatibility with GNU linkers to some degree.
471     // I'll explain the feature and why you may find it useful in this comment.
472     //
473     // lld's symbol resolution semantics is more relaxed than traditional Unix
474     // linkers. For example,
475     //
476     //   ld.lld foo.a bar.o
477     //
478     // succeeds even if bar.o contains an undefined symbol that has to be
479     // resolved by some object file in foo.a. Traditional Unix linkers don't
480     // allow this kind of backward reference, as they visit each file only once
481     // from left to right in the command line while resolving all undefined
482     // symbols at the moment of visiting.
483     //
484     // In the above case, since there's no undefined symbol when a linker visits
485     // foo.a, no files are pulled out from foo.a, and because the linker forgets
486     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
487     // that could have been resolved otherwise.
488     //
489     // That lld accepts more relaxed form means that (besides it'd make more
490     // sense) you can accidentally write a command line or a build file that
491     // works only with lld, even if you have a plan to distribute it to wider
492     // users who may be using GNU linkers. With --warn-backrefs, you can detect
493     // a library order that doesn't work with other Unix linkers.
494     //
495     // The option is also useful to detect cyclic dependencies between static
496     // archives. Again, lld accepts
497     //
498     //   ld.lld foo.a bar.a
499     //
500     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
501     // handled as an error.
502     //
503     // Here is how the option works. We assign a group ID to each file. A file
504     // with a smaller group ID can pull out object files from an archive file
505     // with an equal or greater group ID. Otherwise, it is a reverse dependency
506     // and an error.
507     //
508     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
509     // files within the same --{start,end}-group get the same group ID. E.g.
510     //
511     //   ld.lld A B --start-group C D --end-group E
512     //
513     // A forms group 0. B form group 1. C and D (including their member object
514     // files) form group 2. E forms group 3. I think that you can see how this
515     // group assignment rule simulates the traditional linker's semantics.
516     bool backref = config->warnBackrefs && other.file &&
517                    file->groupId < other.file->groupId;
518     if (backref) {
519       // Some libraries have known problems and can cause noise. Filter them out
520       // with --warn-backrefs-exclude=.
521       StringRef name =
522           !file->archiveName.empty() ? file->archiveName : file->getName();
523       for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
524         if (pat.match(name)) {
525           backref = false;
526           break;
527         }
528     }
529     fetch();
530 
531     // We don't report backward references to weak symbols as they can be
532     // overridden later.
533     //
534     // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
535     // sandwich), where def2 may or may not be the same as def1. We don't want
536     // to warn for this case, so dismiss the warning if we see a subsequent lazy
537     // definition.
538     if (backref && !isWeak())
539       backwardReferences.try_emplace(this, other.file);
540     return;
541   }
542 
543   // Undefined symbols in a SharedFile do not change the binding.
544   if (dyn_cast_or_null<SharedFile>(other.file))
545     return;
546 
547   if (isUndefined() || isShared()) {
548     // The binding will be weak if there is at least one reference and all are
549     // weak. The binding has one opportunity to change to weak: if the first
550     // reference is weak.
551     if (other.binding != STB_WEAK || !referenced)
552       binding = other.binding;
553   }
554 }
555 
556 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
557 // foo@@VER. We want to effectively ignore foo, so give precedence to
558 // foo@@VER.
559 // FIXME: If users can transition to using
560 // .symver foo,foo@@@VER
561 // we can delete this hack.
562 static int compareVersion(StringRef a, StringRef b) {
563   bool x = a.contains("@@");
564   bool y = b.contains("@@");
565   if (!x && y)
566     return 1;
567   if (x && !y)
568     return -1;
569   return 0;
570 }
571 
572 // Compare two symbols. Return 1 if the new symbol should win, -1 if
573 // the new symbol should lose, or 0 if there is a conflict.
574 int Symbol::compare(const Symbol *other) const {
575   assert(other->isDefined() || other->isCommon());
576 
577   if (!isDefined() && !isCommon())
578     return 1;
579 
580   if (int cmp = compareVersion(getName(), other->getName()))
581     return cmp;
582 
583   if (other->isWeak())
584     return -1;
585 
586   if (isWeak())
587     return 1;
588 
589   if (isCommon() && other->isCommon()) {
590     if (config->warnCommon)
591       warn("multiple common of " + getName());
592     return 0;
593   }
594 
595   if (isCommon()) {
596     if (config->warnCommon)
597       warn("common " + getName() + " is overridden");
598     return 1;
599   }
600 
601   if (other->isCommon()) {
602     if (config->warnCommon)
603       warn("common " + getName() + " is overridden");
604     return -1;
605   }
606 
607   auto *oldSym = cast<Defined>(this);
608   auto *newSym = cast<Defined>(other);
609 
610   if (dyn_cast_or_null<BitcodeFile>(other->file))
611     return 0;
612 
613   if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
614       newSym->binding == STB_GLOBAL)
615     return -1;
616 
617   return 0;
618 }
619 
620 static void reportDuplicate(Symbol *sym, InputFile *newFile,
621                             InputSectionBase *errSec, uint64_t errOffset) {
622   if (config->allowMultipleDefinition)
623     return;
624 
625   Defined *d = cast<Defined>(sym);
626   if (!d->section || !errSec) {
627     error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
628           toString(sym->file) + "\n>>> defined in " + toString(newFile));
629     return;
630   }
631 
632   // Construct and print an error message in the form of:
633   //
634   //   ld.lld: error: duplicate symbol: foo
635   //   >>> defined at bar.c:30
636   //   >>>            bar.o (/home/alice/src/bar.o)
637   //   >>> defined at baz.c:563
638   //   >>>            baz.o in archive libbaz.a
639   auto *sec1 = cast<InputSectionBase>(d->section);
640   std::string src1 = sec1->getSrcMsg(*sym, d->value);
641   std::string obj1 = sec1->getObjMsg(d->value);
642   std::string src2 = errSec->getSrcMsg(*sym, errOffset);
643   std::string obj2 = errSec->getObjMsg(errOffset);
644 
645   std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
646   if (!src1.empty())
647     msg += src1 + "\n>>>            ";
648   msg += obj1 + "\n>>> defined at ";
649   if (!src2.empty())
650     msg += src2 + "\n>>>            ";
651   msg += obj2;
652   error(msg);
653 }
654 
655 void Symbol::resolveCommon(const CommonSymbol &other) {
656   int cmp = compare(&other);
657   if (cmp < 0)
658     return;
659 
660   if (cmp > 0) {
661     if (auto *s = dyn_cast<SharedSymbol>(this)) {
662       // Increase st_size if the shared symbol has a larger st_size. The shared
663       // symbol may be created from common symbols. The fact that some object
664       // files were linked into a shared object first should not change the
665       // regular rule that picks the largest st_size.
666       uint64_t size = s->size;
667       replace(other);
668       if (size > cast<CommonSymbol>(this)->size)
669         cast<CommonSymbol>(this)->size = size;
670     } else {
671       replace(other);
672     }
673     return;
674   }
675 
676   CommonSymbol *oldSym = cast<CommonSymbol>(this);
677 
678   oldSym->alignment = std::max(oldSym->alignment, other.alignment);
679   if (oldSym->size < other.size) {
680     oldSym->file = other.file;
681     oldSym->size = other.size;
682   }
683 }
684 
685 void Symbol::resolveDefined(const Defined &other) {
686   int cmp = compare(&other);
687   if (cmp > 0)
688     replace(other);
689   else if (cmp == 0)
690     reportDuplicate(this, other.file,
691                     dyn_cast_or_null<InputSectionBase>(other.section),
692                     other.value);
693 }
694 
695 template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
696   if (!isUndefined()) {
697     // See the comment in resolveUndefined().
698     if (isDefined())
699       backwardReferences.erase(this);
700     return;
701   }
702 
703   // An undefined weak will not fetch archive members. See comment on Lazy in
704   // Symbols.h for the details.
705   if (isWeak()) {
706     uint8_t ty = type;
707     replace(other);
708     type = ty;
709     binding = STB_WEAK;
710     return;
711   }
712 
713   other.fetch();
714 }
715 
716 void Symbol::resolveShared(const SharedSymbol &other) {
717   if (isCommon()) {
718     // See the comment in resolveCommon() above.
719     if (other.size > cast<CommonSymbol>(this)->size)
720       cast<CommonSymbol>(this)->size = other.size;
721     return;
722   }
723   if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
724     // An undefined symbol with non default visibility must be satisfied
725     // in the same DSO.
726     uint8_t bind = binding;
727     replace(other);
728     binding = bind;
729   } else if (traced)
730     printTraceSymbol(&other);
731 }
732