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.
demangle(StringRef symName)30 static std::string demangle(StringRef symName) {
31   if (elf::config->demangle)
32     return demangleItanium(symName);
33   return std::string(symName);
34 }
35 
toString(const elf::Symbol & sym)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 
toELFString(const Archive::Symbol & b)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 *, std::pair<const InputFile *, const InputFile *>>
68     elf::backwardReferences;
69 
getSymVA(const Symbol & sym,int64_t & addend)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 
getVA(int64_t addend) const154 uint64_t Symbol::getVA(int64_t addend) const {
155   uint64_t outVA = getSymVA(*this, addend);
156   return outVA + addend;
157 }
158 
getGotVA() const159 uint64_t Symbol::getGotVA() const {
160   if (gotInIgot)
161     return in.igotPlt->getVA() + getGotPltOffset();
162   return in.got->getVA() + getGotOffset();
163 }
164 
getGotOffset() const165 uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
166 
getGotPltVA() const167 uint64_t Symbol::getGotPltVA() const {
168   if (isInIplt)
169     return in.igotPlt->getVA() + getGotPltOffset();
170   return in.gotPlt->getVA() + getGotPltOffset();
171 }
172 
getGotPltOffset() const173 uint64_t Symbol::getGotPltOffset() const {
174   if (isInIplt)
175     return pltIndex * config->wordsize;
176   return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
177 }
178 
getPltVA() const179 uint64_t Symbol::getPltVA() const {
180   uint64_t outVA = isInIplt
181                        ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
182                        : in.plt->getVA() + in.plt->headerSize +
183                              pltIndex * target->pltEntrySize;
184 
185   // While linking microMIPS code PLT code are always microMIPS
186   // code. Set the less-significant bit to track that fact.
187   // See detailed comment in the `getSymVA` function.
188   if (config->emachine == EM_MIPS && isMicroMips())
189     outVA |= 1;
190   return outVA;
191 }
192 
getSize() const193 uint64_t Symbol::getSize() const {
194   if (const auto *dr = dyn_cast<Defined>(this))
195     return dr->size;
196   return cast<SharedSymbol>(this)->size;
197 }
198 
getOutputSection() const199 OutputSection *Symbol::getOutputSection() const {
200   if (auto *s = dyn_cast<Defined>(this)) {
201     if (auto *sec = s->section)
202       return sec->repl->getOutputSection();
203     return nullptr;
204   }
205   return nullptr;
206 }
207 
208 // If a symbol name contains '@', the characters after that is
209 // a symbol version name. This function parses that.
parseSymbolVersion()210 void Symbol::parseSymbolVersion() {
211   StringRef s = getName();
212   size_t pos = s.find('@');
213   if (pos == 0 || pos == StringRef::npos)
214     return;
215   StringRef verstr = s.substr(pos + 1);
216   if (verstr.empty())
217     return;
218 
219   // Truncate the symbol name so that it doesn't include the version string.
220   nameSize = pos;
221 
222   // If this is not in this DSO, it is not a definition.
223   if (!isDefined())
224     return;
225 
226   // '@@' in a symbol name means the default version.
227   // It is usually the most recent one.
228   bool isDefault = (verstr[0] == '@');
229   if (isDefault)
230     verstr = verstr.substr(1);
231 
232   for (const VersionDefinition &ver : namedVersionDefs()) {
233     if (ver.name != verstr)
234       continue;
235 
236     if (isDefault)
237       versionId = ver.id;
238     else
239       versionId = ver.id | VERSYM_HIDDEN;
240     return;
241   }
242 
243   // It is an error if the specified version is not defined.
244   // Usually version script is not provided when linking executable,
245   // but we may still want to override a versioned symbol from DSO,
246   // so we do not report error in this case. We also do not error
247   // if the symbol has a local version as it won't be in the dynamic
248   // symbol table.
249   if (config->shared && versionId != VER_NDX_LOCAL)
250     error(toString(file) + ": symbol " + s + " has undefined version " +
251           verstr);
252 }
253 
fetch() const254 void Symbol::fetch() const {
255   if (auto *sym = dyn_cast<LazyArchive>(this)) {
256     cast<ArchiveFile>(sym->file)->fetch(sym->sym);
257     return;
258   }
259 
260   if (auto *sym = dyn_cast<LazyObject>(this)) {
261     dyn_cast<LazyObjFile>(sym->file)->fetch();
262     return;
263   }
264 
265   llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
266 }
267 
getMemberBuffer()268 MemoryBufferRef LazyArchive::getMemberBuffer() {
269   Archive::Child c =
270       CHECK(sym.getMember(),
271             "could not get the member for symbol " + toELFString(sym));
272 
273   return CHECK(c.getMemoryBufferRef(),
274                "could not get the buffer for the member defining symbol " +
275                    toELFString(sym));
276 }
277 
computeBinding() const278 uint8_t Symbol::computeBinding() const {
279   if (config->relocatable)
280     return binding;
281   if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
282       (versionId == VER_NDX_LOCAL && isDefined()))
283     return STB_LOCAL;
284   if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
285     return STB_GLOBAL;
286   return binding;
287 }
288 
includeInDynsym() const289 bool Symbol::includeInDynsym() const {
290   if (!config->hasDynSymTab)
291     return false;
292   if (computeBinding() == STB_LOCAL)
293     return false;
294   if (!isDefined() && !isCommon())
295     // This should unconditionally return true, unfortunately glibc -static-pie
296     // expects undefined weak symbols not to exist in .dynsym, e.g.
297     // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
298     // __pthread_initialize_minimal reference in csu/libc-start.c.
299     return !(config->noDynamicLinker && isUndefWeak());
300 
301   return exportDynamic || inDynamicList;
302 }
303 
304 // Print out a log message for --trace-symbol.
printTraceSymbol(const Symbol * sym)305 void elf::printTraceSymbol(const Symbol *sym) {
306   std::string s;
307   if (sym->isUndefined())
308     s = ": reference to ";
309   else if (sym->isLazy())
310     s = ": lazy definition of ";
311   else if (sym->isShared())
312     s = ": shared definition of ";
313   else if (sym->isCommon())
314     s = ": common definition of ";
315   else
316     s = ": definition of ";
317 
318   message(toString(sym->file) + s + sym->getName());
319 }
320 
maybeWarnUnorderableSymbol(const Symbol * sym)321 void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
322   if (!config->warnSymbolOrdering)
323     return;
324 
325   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
326   // is emitted. It makes sense to not warn on undefined symbols.
327   //
328   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
329   // but we don't have to be compatible here.
330   if (sym->isUndefined() &&
331       config->unresolvedSymbols == UnresolvedPolicy::Ignore)
332     return;
333 
334   const InputFile *file = sym->file;
335   auto *d = dyn_cast<Defined>(sym);
336 
337   auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
338 
339   if (sym->isUndefined())
340     report(": unable to order undefined symbol: ");
341   else if (sym->isShared())
342     report(": unable to order shared symbol: ");
343   else if (d && !d->section)
344     report(": unable to order absolute symbol: ");
345   else if (d && isa<OutputSection>(d->section))
346     report(": unable to order synthetic symbol: ");
347   else if (d && !d->section->repl->isLive())
348     report(": unable to order discarded symbol: ");
349 }
350 
351 // Returns true if a symbol can be replaced at load-time by a symbol
352 // with the same name defined in other ELF executable or DSO.
computeIsPreemptible(const Symbol & sym)353 bool elf::computeIsPreemptible(const Symbol &sym) {
354   assert(!sym.isLocal());
355 
356   // Only symbols with default visibility that appear in dynsym can be
357   // preempted. Symbols with protected visibility cannot be preempted.
358   if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
359     return false;
360 
361   // At this point copy relocations have not been created yet, so any
362   // symbol that is not defined locally is preemptible.
363   if (!sym.isDefined())
364     return true;
365 
366   if (!config->shared)
367     return false;
368 
369   // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
370   // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
371   // in the dynamic list.
372   if (config->symbolic || (config->bsymbolicFunctions && sym.isFunc()))
373     return sym.inDynamicList;
374   return true;
375 }
376 
reportBackrefs()377 void elf::reportBackrefs() {
378   for (auto &it : backwardReferences) {
379     const Symbol &sym = *it.first;
380     std::string to = toString(it.second.second);
381     // Some libraries have known problems and can cause noise. Filter them out
382     // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
383     bool exclude = false;
384     for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
385       if (pat.match(to)) {
386         exclude = true;
387         break;
388       }
389     if (!exclude)
390       warn("backward reference detected: " + sym.getName() + " in " +
391            toString(it.second.first) + " refers to " + to);
392   }
393 }
394 
getMinVisibility(uint8_t va,uint8_t vb)395 static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
396   if (va == STV_DEFAULT)
397     return vb;
398   if (vb == STV_DEFAULT)
399     return va;
400   return std::min(va, vb);
401 }
402 
403 // Merge symbol properties.
404 //
405 // When we have many symbols of the same name, we choose one of them,
406 // and that's the result of symbol resolution. However, symbols that
407 // were not chosen still affect some symbol properties.
mergeProperties(const Symbol & other)408 void Symbol::mergeProperties(const Symbol &other) {
409   if (other.exportDynamic)
410     exportDynamic = true;
411   if (other.isUsedInRegularObj)
412     isUsedInRegularObj = true;
413 
414   // DSO symbols do not affect visibility in the output.
415   if (!other.isShared())
416     visibility = getMinVisibility(visibility, other.visibility);
417 }
418 
resolve(const Symbol & other)419 void Symbol::resolve(const Symbol &other) {
420   mergeProperties(other);
421 
422   if (isPlaceholder()) {
423     replace(other);
424     return;
425   }
426 
427   switch (other.kind()) {
428   case Symbol::UndefinedKind:
429     resolveUndefined(cast<Undefined>(other));
430     break;
431   case Symbol::CommonKind:
432     resolveCommon(cast<CommonSymbol>(other));
433     break;
434   case Symbol::DefinedKind:
435     resolveDefined(cast<Defined>(other));
436     break;
437   case Symbol::LazyArchiveKind:
438     resolveLazy(cast<LazyArchive>(other));
439     break;
440   case Symbol::LazyObjectKind:
441     resolveLazy(cast<LazyObject>(other));
442     break;
443   case Symbol::SharedKind:
444     resolveShared(cast<SharedSymbol>(other));
445     break;
446   case Symbol::PlaceholderKind:
447     llvm_unreachable("bad symbol kind");
448   }
449 }
450 
resolveUndefined(const Undefined & other)451 void Symbol::resolveUndefined(const Undefined &other) {
452   // An undefined symbol with non default visibility must be satisfied
453   // in the same DSO.
454   //
455   // If this is a non-weak defined symbol in a discarded section, override the
456   // existing undefined symbol for better error message later.
457   if ((isShared() && other.visibility != STV_DEFAULT) ||
458       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
459     replace(other);
460     return;
461   }
462 
463   if (traced)
464     printTraceSymbol(&other);
465 
466   if (isLazy()) {
467     // An undefined weak will not fetch archive members. See comment on Lazy in
468     // Symbols.h for the details.
469     if (other.binding == STB_WEAK) {
470       binding = STB_WEAK;
471       type = other.type;
472       return;
473     }
474 
475     // Do extra check for --warn-backrefs.
476     //
477     // --warn-backrefs is an option to prevent an undefined reference from
478     // fetching an archive member written earlier in the command line. It can be
479     // used to keep compatibility with GNU linkers to some degree.
480     // I'll explain the feature and why you may find it useful in this comment.
481     //
482     // lld's symbol resolution semantics is more relaxed than traditional Unix
483     // linkers. For example,
484     //
485     //   ld.lld foo.a bar.o
486     //
487     // succeeds even if bar.o contains an undefined symbol that has to be
488     // resolved by some object file in foo.a. Traditional Unix linkers don't
489     // allow this kind of backward reference, as they visit each file only once
490     // from left to right in the command line while resolving all undefined
491     // symbols at the moment of visiting.
492     //
493     // In the above case, since there's no undefined symbol when a linker visits
494     // foo.a, no files are pulled out from foo.a, and because the linker forgets
495     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
496     // that could have been resolved otherwise.
497     //
498     // That lld accepts more relaxed form means that (besides it'd make more
499     // sense) you can accidentally write a command line or a build file that
500     // works only with lld, even if you have a plan to distribute it to wider
501     // users who may be using GNU linkers. With --warn-backrefs, you can detect
502     // a library order that doesn't work with other Unix linkers.
503     //
504     // The option is also useful to detect cyclic dependencies between static
505     // archives. Again, lld accepts
506     //
507     //   ld.lld foo.a bar.a
508     //
509     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
510     // handled as an error.
511     //
512     // Here is how the option works. We assign a group ID to each file. A file
513     // with a smaller group ID can pull out object files from an archive file
514     // with an equal or greater group ID. Otherwise, it is a reverse dependency
515     // and an error.
516     //
517     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
518     // files within the same --{start,end}-group get the same group ID. E.g.
519     //
520     //   ld.lld A B --start-group C D --end-group E
521     //
522     // A forms group 0. B form group 1. C and D (including their member object
523     // files) form group 2. E forms group 3. I think that you can see how this
524     // group assignment rule simulates the traditional linker's semantics.
525     bool backref = config->warnBackrefs && other.file &&
526                    file->groupId < other.file->groupId;
527     fetch();
528 
529     // We don't report backward references to weak symbols as they can be
530     // overridden later.
531     //
532     // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
533     // sandwich), where def2 may or may not be the same as def1. We don't want
534     // to warn for this case, so dismiss the warning if we see a subsequent lazy
535     // definition. this->file needs to be saved because in the case of LTO it
536     // may be reset to nullptr or be replaced with a file named lto.tmp.
537     if (backref && !isWeak())
538       backwardReferences.try_emplace(this, std::make_pair(other.file, file));
539     return;
540   }
541 
542   // Undefined symbols in a SharedFile do not change the binding.
543   if (dyn_cast_or_null<SharedFile>(other.file))
544     return;
545 
546   if (isUndefined() || isShared()) {
547     // The binding will be weak if there is at least one reference and all are
548     // weak. The binding has one opportunity to change to weak: if the first
549     // reference is weak.
550     if (other.binding != STB_WEAK || !referenced)
551       binding = other.binding;
552   }
553 }
554 
555 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
556 // foo@@VER. We want to effectively ignore foo, so give precedence to
557 // foo@@VER.
558 // FIXME: If users can transition to using
559 // .symver foo,foo@@@VER
560 // we can delete this hack.
compareVersion(StringRef a,StringRef b)561 static int compareVersion(StringRef a, StringRef b) {
562   bool x = a.contains("@@");
563   bool y = b.contains("@@");
564   if (!x && y)
565     return 1;
566   if (x && !y)
567     return -1;
568   return 0;
569 }
570 
571 // Compare two symbols. Return 1 if the new symbol should win, -1 if
572 // the new symbol should lose, or 0 if there is a conflict.
compare(const Symbol * other) const573 int Symbol::compare(const Symbol *other) const {
574   assert(other->isDefined() || other->isCommon());
575 
576   if (!isDefined() && !isCommon())
577     return 1;
578 
579   if (int cmp = compareVersion(getName(), other->getName()))
580     return cmp;
581 
582   if (other->isWeak())
583     return -1;
584 
585   if (isWeak())
586     return 1;
587 
588   if (isCommon() && other->isCommon()) {
589     if (config->warnCommon)
590       warn("multiple common of " + getName());
591     return 0;
592   }
593 
594   if (isCommon()) {
595     if (config->warnCommon)
596       warn("common " + getName() + " is overridden");
597     return 1;
598   }
599 
600   if (other->isCommon()) {
601     if (config->warnCommon)
602       warn("common " + getName() + " is overridden");
603     return -1;
604   }
605 
606   auto *oldSym = cast<Defined>(this);
607   auto *newSym = cast<Defined>(other);
608 
609   if (dyn_cast_or_null<BitcodeFile>(other->file))
610     return 0;
611 
612   if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
613       newSym->binding == STB_GLOBAL)
614     return -1;
615 
616   return 0;
617 }
618 
reportDuplicate(Symbol * sym,InputFile * newFile,InputSectionBase * errSec,uint64_t errOffset)619 static void reportDuplicate(Symbol *sym, InputFile *newFile,
620                             InputSectionBase *errSec, uint64_t errOffset) {
621   if (config->allowMultipleDefinition)
622     return;
623 
624   Defined *d = cast<Defined>(sym);
625   if (!d->section || !errSec) {
626     error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
627           toString(sym->file) + "\n>>> defined in " + toString(newFile));
628     return;
629   }
630 
631   // Construct and print an error message in the form of:
632   //
633   //   ld.lld: error: duplicate symbol: foo
634   //   >>> defined at bar.c:30
635   //   >>>            bar.o (/home/alice/src/bar.o)
636   //   >>> defined at baz.c:563
637   //   >>>            baz.o in archive libbaz.a
638   auto *sec1 = cast<InputSectionBase>(d->section);
639   std::string src1 = sec1->getSrcMsg(*sym, d->value);
640   std::string obj1 = sec1->getObjMsg(d->value);
641   std::string src2 = errSec->getSrcMsg(*sym, errOffset);
642   std::string obj2 = errSec->getObjMsg(errOffset);
643 
644   std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
645   if (!src1.empty())
646     msg += src1 + "\n>>>            ";
647   msg += obj1 + "\n>>> defined at ";
648   if (!src2.empty())
649     msg += src2 + "\n>>>            ";
650   msg += obj2;
651   error(msg);
652 }
653 
resolveCommon(const CommonSymbol & other)654 void Symbol::resolveCommon(const CommonSymbol &other) {
655   int cmp = compare(&other);
656   if (cmp < 0)
657     return;
658 
659   if (cmp > 0) {
660     if (auto *s = dyn_cast<SharedSymbol>(this)) {
661       // Increase st_size if the shared symbol has a larger st_size. The shared
662       // symbol may be created from common symbols. The fact that some object
663       // files were linked into a shared object first should not change the
664       // regular rule that picks the largest st_size.
665       uint64_t size = s->size;
666       replace(other);
667       if (size > cast<CommonSymbol>(this)->size)
668         cast<CommonSymbol>(this)->size = size;
669     } else {
670       replace(other);
671     }
672     return;
673   }
674 
675   CommonSymbol *oldSym = cast<CommonSymbol>(this);
676 
677   oldSym->alignment = std::max(oldSym->alignment, other.alignment);
678   if (oldSym->size < other.size) {
679     oldSym->file = other.file;
680     oldSym->size = other.size;
681   }
682 }
683 
resolveDefined(const Defined & other)684 void Symbol::resolveDefined(const Defined &other) {
685   int cmp = compare(&other);
686   if (cmp > 0)
687     replace(other);
688   else if (cmp == 0)
689     reportDuplicate(this, other.file,
690                     dyn_cast_or_null<InputSectionBase>(other.section),
691                     other.value);
692 }
693 
resolveLazy(const LazyT & other)694 template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
695   if (!isUndefined()) {
696     // See the comment in resolveUndefined().
697     if (isDefined())
698       backwardReferences.erase(this);
699     return;
700   }
701 
702   // An undefined weak will not fetch archive members. See comment on Lazy in
703   // Symbols.h for the details.
704   if (isWeak()) {
705     uint8_t ty = type;
706     replace(other);
707     type = ty;
708     binding = STB_WEAK;
709     return;
710   }
711 
712   other.fetch();
713 }
714 
resolveShared(const SharedSymbol & other)715 void Symbol::resolveShared(const SharedSymbol &other) {
716   if (isCommon()) {
717     // See the comment in resolveCommon() above.
718     if (other.size > cast<CommonSymbol>(this)->size)
719       cast<CommonSymbol>(this)->size = other.size;
720     return;
721   }
722   if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
723     // An undefined symbol with non default visibility must be satisfied
724     // in the same DSO.
725     uint8_t bind = binding;
726     replace(other);
727     binding = bind;
728   } else if (traced)
729     printTraceSymbol(&other);
730 }
731