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