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