xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision d67b25e7)
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 
99     // In the typical case, this is actually very simple and boils
100     // down to adding together 3 numbers:
101     // 1. The address of the output section.
102     // 2. The offset of the input section within the output section.
103     // 3. The offset within the input section (this addition happens
104     //    inside InputSection::getOffset).
105     //
106     // If you understand the data structures involved with this next
107     // line (and how they get built), then you have a pretty good
108     // understanding of the linker.
109     uint64_t va = isec->getVA(offset);
110     if (d.isSection())
111       va -= addend;
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.needsCopy))
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   return getSymVA(*this, addend) + addend;
156 }
157 
158 uint64_t Symbol::getGotVA() const {
159   if (gotInIgot)
160     return in.igotPlt->getVA() + getGotPltOffset();
161   return in.got->getVA() + getGotOffset();
162 }
163 
164 uint64_t Symbol::getGotOffset() const {
165   return gotIndex * target->gotEntrySize;
166 }
167 
168 uint64_t Symbol::getGotPltVA() const {
169   if (isInIplt)
170     return in.igotPlt->getVA() + getGotPltOffset();
171   return in.gotPlt->getVA() + getGotPltOffset();
172 }
173 
174 uint64_t Symbol::getGotPltOffset() const {
175   if (isInIplt)
176     return pltIndex * target->gotEntrySize;
177   return (pltIndex + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
178 }
179 
180 uint64_t Symbol::getPltVA() const {
181   uint64_t outVA = isInIplt
182                        ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
183                        : in.plt->getVA() + in.plt->headerSize +
184                              pltIndex * target->pltEntrySize;
185 
186   // While linking microMIPS code PLT code are always microMIPS
187   // code. Set the less-significant bit to track that fact.
188   // See detailed comment in the `getSymVA` function.
189   if (config->emachine == EM_MIPS && isMicroMips())
190     outVA |= 1;
191   return outVA;
192 }
193 
194 uint64_t Symbol::getSize() const {
195   if (const auto *dr = dyn_cast<Defined>(this))
196     return dr->size;
197   return cast<SharedSymbol>(this)->size;
198 }
199 
200 OutputSection *Symbol::getOutputSection() const {
201   if (auto *s = dyn_cast<Defined>(this)) {
202     if (auto *sec = s->section)
203       return sec->getOutputSection();
204     return nullptr;
205   }
206   return nullptr;
207 }
208 
209 // If a symbol name contains '@', the characters after that is
210 // a symbol version name. This function parses that.
211 void Symbol::parseSymbolVersion() {
212   // Return if localized by a local: pattern in a version script.
213   if (versionId == VER_NDX_LOCAL)
214     return;
215   StringRef s = getName();
216   size_t pos = s.find('@');
217   if (pos == StringRef::npos)
218     return;
219   StringRef verstr = s.substr(pos + 1);
220   if (verstr.empty())
221     return;
222 
223   // Truncate the symbol name so that it doesn't include the version string.
224   nameSize = pos;
225 
226   // If this is not in this DSO, it is not a definition.
227   if (!isDefined())
228     return;
229 
230   // '@@' in a symbol name means the default version.
231   // It is usually the most recent one.
232   bool isDefault = (verstr[0] == '@');
233   if (isDefault)
234     verstr = verstr.substr(1);
235 
236   for (const VersionDefinition &ver : namedVersionDefs()) {
237     if (ver.name != verstr)
238       continue;
239 
240     if (isDefault)
241       versionId = ver.id;
242     else
243       versionId = ver.id | VERSYM_HIDDEN;
244     return;
245   }
246 
247   // It is an error if the specified version is not defined.
248   // Usually version script is not provided when linking executable,
249   // but we may still want to override a versioned symbol from DSO,
250   // so we do not report error in this case. We also do not error
251   // if the symbol has a local version as it won't be in the dynamic
252   // symbol table.
253   if (config->shared && versionId != VER_NDX_LOCAL)
254     error(toString(file) + ": symbol " + s + " has undefined version " +
255           verstr);
256 }
257 
258 void Symbol::extract() const {
259   if (auto *sym = dyn_cast<LazyArchive>(this))
260     cast<ArchiveFile>(sym->file)->extract(sym->sym);
261   else
262     cast<LazyObjFile>(this->file)->extract();
263 }
264 
265 MemoryBufferRef LazyArchive::getMemberBuffer() {
266   Archive::Child c =
267       CHECK(sym.getMember(),
268             "could not get the member for symbol " + toELFString(sym));
269 
270   return CHECK(c.getMemoryBufferRef(),
271                "could not get the buffer for the member defining symbol " +
272                    toELFString(sym));
273 }
274 
275 uint8_t Symbol::computeBinding() const {
276   if (config->relocatable)
277     return binding;
278   if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
279       (versionId == VER_NDX_LOCAL && !isLazy()))
280     return STB_LOCAL;
281   if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
282     return STB_GLOBAL;
283   return binding;
284 }
285 
286 bool Symbol::includeInDynsym() const {
287   if (!config->hasDynSymTab)
288     return false;
289   if (computeBinding() == STB_LOCAL)
290     return false;
291   if (!isDefined() && !isCommon())
292     // This should unconditionally return true, unfortunately glibc -static-pie
293     // expects undefined weak symbols not to exist in .dynsym, e.g.
294     // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
295     // __pthread_initialize_minimal reference in csu/libc-start.c.
296     return !(config->noDynamicLinker && isUndefWeak());
297 
298   return exportDynamic || inDynamicList;
299 }
300 
301 // Print out a log message for --trace-symbol.
302 void elf::printTraceSymbol(const Symbol *sym) {
303   std::string s;
304   if (sym->isUndefined())
305     s = ": reference to ";
306   else if (sym->isLazy())
307     s = ": lazy definition of ";
308   else if (sym->isShared())
309     s = ": shared definition of ";
310   else if (sym->isCommon())
311     s = ": common definition of ";
312   else
313     s = ": definition of ";
314 
315   message(toString(sym->file) + s + sym->getName());
316 }
317 
318 static void recordWhyExtract(const InputFile *reference,
319                              const InputFile &extracted, const Symbol &sym) {
320   whyExtract.emplace_back(toString(reference), &extracted, sym);
321 }
322 
323 void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
324   if (!config->warnSymbolOrdering)
325     return;
326 
327   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
328   // is emitted. It makes sense to not warn on undefined symbols.
329   //
330   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
331   // but we don't have to be compatible here.
332   if (sym->isUndefined() &&
333       config->unresolvedSymbols == UnresolvedPolicy::Ignore)
334     return;
335 
336   const InputFile *file = sym->file;
337   auto *d = dyn_cast<Defined>(sym);
338 
339   auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
340 
341   if (sym->isUndefined())
342     report(": unable to order undefined symbol: ");
343   else if (sym->isShared())
344     report(": unable to order shared symbol: ");
345   else if (d && !d->section)
346     report(": unable to order absolute symbol: ");
347   else if (d && isa<OutputSection>(d->section))
348     report(": unable to order synthetic symbol: ");
349   else if (d && !d->section->repl->isLive())
350     report(": unable to order discarded symbol: ");
351 }
352 
353 // Returns true if a symbol can be replaced at load-time by a symbol
354 // with the same name defined in other ELF executable or DSO.
355 bool elf::computeIsPreemptible(const Symbol &sym) {
356   assert(!sym.isLocal());
357 
358   // Only symbols with default visibility that appear in dynsym can be
359   // preempted. Symbols with protected visibility cannot be preempted.
360   if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
361     return false;
362 
363   // At this point copy relocations have not been created yet, so any
364   // symbol that is not defined locally is preemptible.
365   if (!sym.isDefined())
366     return true;
367 
368   if (!config->shared)
369     return false;
370 
371   // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
372   // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
373   // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
374   // -Bsymbolic-functions.
375   if (config->symbolic ||
376       (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
377       (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
378        sym.binding != STB_WEAK))
379     return sym.inDynamicList;
380   return true;
381 }
382 
383 void elf::reportBackrefs() {
384   for (auto &it : backwardReferences) {
385     const Symbol &sym = *it.first;
386     std::string to = toString(it.second.second);
387     // Some libraries have known problems and can cause noise. Filter them out
388     // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
389     bool exclude = false;
390     for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
391       if (pat.match(to)) {
392         exclude = true;
393         break;
394       }
395     if (!exclude)
396       warn("backward reference detected: " + sym.getName() + " in " +
397            toString(it.second.first) + " refers to " + to);
398   }
399 }
400 
401 static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
402   if (va == STV_DEFAULT)
403     return vb;
404   if (vb == STV_DEFAULT)
405     return va;
406   return std::min(va, vb);
407 }
408 
409 // Merge symbol properties.
410 //
411 // When we have many symbols of the same name, we choose one of them,
412 // and that's the result of symbol resolution. However, symbols that
413 // were not chosen still affect some symbol properties.
414 void Symbol::mergeProperties(const Symbol &other) {
415   if (other.exportDynamic)
416     exportDynamic = true;
417   if (other.isUsedInRegularObj)
418     isUsedInRegularObj = true;
419 
420   // DSO symbols do not affect visibility in the output.
421   if (!other.isShared())
422     visibility = getMinVisibility(visibility, other.visibility);
423 }
424 
425 void Symbol::resolve(const Symbol &other) {
426   mergeProperties(other);
427 
428   if (isPlaceholder()) {
429     replace(other);
430     return;
431   }
432 
433   switch (other.kind()) {
434   case Symbol::UndefinedKind:
435     resolveUndefined(cast<Undefined>(other));
436     break;
437   case Symbol::CommonKind:
438     resolveCommon(cast<CommonSymbol>(other));
439     break;
440   case Symbol::DefinedKind:
441     resolveDefined(cast<Defined>(other));
442     break;
443   case Symbol::LazyArchiveKind:
444     resolveLazy(cast<LazyArchive>(other));
445     break;
446   case Symbol::LazyObjectKind:
447     resolveLazy(cast<LazyObject>(other));
448     break;
449   case Symbol::SharedKind:
450     resolveShared(cast<SharedSymbol>(other));
451     break;
452   case Symbol::PlaceholderKind:
453     llvm_unreachable("bad symbol kind");
454   }
455 }
456 
457 void Symbol::resolveUndefined(const Undefined &other) {
458   // An undefined symbol with non default visibility must be satisfied
459   // in the same DSO.
460   //
461   // If this is a non-weak defined symbol in a discarded section, override the
462   // existing undefined symbol for better error message later.
463   if ((isShared() && other.visibility != STV_DEFAULT) ||
464       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
465     replace(other);
466     return;
467   }
468 
469   if (traced)
470     printTraceSymbol(&other);
471 
472   if (isLazy()) {
473     // An undefined weak will not extract archive members. See comment on Lazy
474     // in Symbols.h for the details.
475     if (other.binding == STB_WEAK) {
476       binding = STB_WEAK;
477       type = other.type;
478       return;
479     }
480 
481     // Do extra check for --warn-backrefs.
482     //
483     // --warn-backrefs is an option to prevent an undefined reference from
484     // extracting an archive member written earlier in the command line. It can
485     // be used to keep compatibility with GNU linkers to some degree. I'll
486     // explain the feature and why you may find it useful in this comment.
487     //
488     // lld's symbol resolution semantics is more relaxed than traditional Unix
489     // linkers. For example,
490     //
491     //   ld.lld foo.a bar.o
492     //
493     // succeeds even if bar.o contains an undefined symbol that has to be
494     // resolved by some object file in foo.a. Traditional Unix linkers don't
495     // allow this kind of backward reference, as they visit each file only once
496     // from left to right in the command line while resolving all undefined
497     // symbols at the moment of visiting.
498     //
499     // In the above case, since there's no undefined symbol when a linker visits
500     // foo.a, no files are pulled out from foo.a, and because the linker forgets
501     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
502     // that could have been resolved otherwise.
503     //
504     // That lld accepts more relaxed form means that (besides it'd make more
505     // sense) you can accidentally write a command line or a build file that
506     // works only with lld, even if you have a plan to distribute it to wider
507     // users who may be using GNU linkers. With --warn-backrefs, you can detect
508     // a library order that doesn't work with other Unix linkers.
509     //
510     // The option is also useful to detect cyclic dependencies between static
511     // archives. Again, lld accepts
512     //
513     //   ld.lld foo.a bar.a
514     //
515     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
516     // handled as an error.
517     //
518     // Here is how the option works. We assign a group ID to each file. A file
519     // with a smaller group ID can pull out object files from an archive file
520     // with an equal or greater group ID. Otherwise, it is a reverse dependency
521     // and an error.
522     //
523     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
524     // files within the same --{start,end}-group get the same group ID. E.g.
525     //
526     //   ld.lld A B --start-group C D --end-group E
527     //
528     // A forms group 0. B form group 1. C and D (including their member object
529     // files) form group 2. E forms group 3. I think that you can see how this
530     // group assignment rule simulates the traditional linker's semantics.
531     bool backref = config->warnBackrefs && other.file &&
532                    file->groupId < other.file->groupId;
533     extract();
534 
535     if (!config->whyExtract.empty())
536       recordWhyExtract(other.file, *file, *this);
537 
538     // We don't report backward references to weak symbols as they can be
539     // overridden later.
540     //
541     // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
542     // sandwich), where def2 may or may not be the same as def1. We don't want
543     // to warn for this case, so dismiss the warning if we see a subsequent lazy
544     // definition. this->file needs to be saved because in the case of LTO it
545     // may be reset to nullptr or be replaced with a file named lto.tmp.
546     if (backref && !isWeak())
547       backwardReferences.try_emplace(this, std::make_pair(other.file, file));
548     return;
549   }
550 
551   // Undefined symbols in a SharedFile do not change the binding.
552   if (dyn_cast_or_null<SharedFile>(other.file))
553     return;
554 
555   if (isUndefined() || isShared()) {
556     // The binding will be weak if there is at least one reference and all are
557     // weak. The binding has one opportunity to change to weak: if the first
558     // reference is weak.
559     if (other.binding != STB_WEAK || !referenced)
560       binding = other.binding;
561   }
562 }
563 
564 // Compare two symbols. Return 1 if the new symbol should win, -1 if
565 // the new symbol should lose, or 0 if there is a conflict.
566 int Symbol::compare(const Symbol *other) const {
567   assert(other->isDefined() || other->isCommon());
568 
569   if (!isDefined() && !isCommon())
570     return 1;
571 
572   // .symver foo,foo@@VER unfortunately creates two defined symbols: foo and
573   // foo@@VER. In GNU ld, if foo and foo@@VER are in the same file, foo is
574   // ignored. In our implementation, when this is foo, this->getName() may still
575   // contain @@, return 1 in this case as well.
576   if (file == other->file) {
577     if (other->getName().contains("@@"))
578       return 1;
579     if (getName().contains("@@"))
580       return -1;
581   }
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>
696 static void replaceCommon(Symbol &oldSym, const LazyT &newSym) {
697   backwardReferences.erase(&oldSym);
698   oldSym.replace(newSym);
699   newSym.extract();
700 }
701 
702 template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
703   // For common objects, we want to look for global or weak definitions that
704   // should be extracted as the canonical definition instead.
705   if (isCommon() && elf::config->fortranCommon) {
706     if (auto *laSym = dyn_cast<LazyArchive>(&other)) {
707       ArchiveFile *archive = cast<ArchiveFile>(laSym->file);
708       const Archive::Symbol &archiveSym = laSym->sym;
709       if (archive->shouldExtractForCommon(archiveSym)) {
710         replaceCommon(*this, other);
711         return;
712       }
713     } else if (auto *loSym = dyn_cast<LazyObject>(&other)) {
714       LazyObjFile *obj = cast<LazyObjFile>(loSym->file);
715       if (obj->shouldExtractForCommon(loSym->getName())) {
716         replaceCommon(*this, other);
717         return;
718       }
719     }
720   }
721 
722   if (!isUndefined()) {
723     // See the comment in resolveUndefined().
724     if (isDefined())
725       backwardReferences.erase(this);
726     return;
727   }
728 
729   // An undefined weak will not extract archive members. See comment on Lazy in
730   // Symbols.h for the details.
731   if (isWeak()) {
732     uint8_t ty = type;
733     replace(other);
734     type = ty;
735     binding = STB_WEAK;
736     return;
737   }
738 
739   const InputFile *oldFile = file;
740   other.extract();
741   if (!config->whyExtract.empty())
742     recordWhyExtract(oldFile, *file, *this);
743 }
744 
745 void Symbol::resolveShared(const SharedSymbol &other) {
746   if (isCommon()) {
747     // See the comment in resolveCommon() above.
748     if (other.size > cast<CommonSymbol>(this)->size)
749       cast<CommonSymbol>(this)->size = other.size;
750     return;
751   }
752   if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
753     // An undefined symbol with non default visibility must be satisfied
754     // in the same DSO.
755     uint8_t bind = binding;
756     replace(other);
757     binding = bind;
758   } else if (traced)
759     printTraceSymbol(&other);
760 }
761