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