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