xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision 68f58a75)
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/Path.h"
20 #include <cstring>
21 
22 using namespace llvm;
23 using namespace llvm::object;
24 using namespace llvm::ELF;
25 
26 using namespace lld;
27 using namespace lld::elf;
28 
29 Defined *ElfSym::bss;
30 Defined *ElfSym::etext1;
31 Defined *ElfSym::etext2;
32 Defined *ElfSym::edata1;
33 Defined *ElfSym::edata2;
34 Defined *ElfSym::end1;
35 Defined *ElfSym::end2;
36 Defined *ElfSym::globalOffsetTable;
37 Defined *ElfSym::mipsGp;
38 Defined *ElfSym::mipsGpDisp;
39 Defined *ElfSym::mipsLocalGp;
40 Defined *ElfSym::relaIpltStart;
41 Defined *ElfSym::relaIpltEnd;
42 Defined *ElfSym::riscvGlobalPointer;
43 Defined *ElfSym::tlsModuleBase;
44 
45 // Returns a symbol for an error message.
46 static std::string demangle(StringRef symName) {
47   if (config->demangle)
48     return demangleItanium(symName);
49   return symName;
50 }
51 namespace lld {
52 std::string toString(const Symbol &b) { return demangle(b.getName()); }
53 std::string toELFString(const Archive::Symbol &b) {
54   return demangle(b.getName());
55 }
56 } // namespace lld
57 
58 static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
59   switch (sym.kind()) {
60   case Symbol::DefinedKind: {
61     auto &d = cast<Defined>(sym);
62     SectionBase *isec = d.section;
63 
64     // This is an absolute symbol.
65     if (!isec)
66       return d.value;
67 
68     assert(isec != &InputSection::discarded);
69     isec = isec->repl;
70 
71     uint64_t offset = d.value;
72 
73     // An object in an SHF_MERGE section might be referenced via a
74     // section symbol (as a hack for reducing the number of local
75     // symbols).
76     // Depending on the addend, the reference via a section symbol
77     // refers to a different object in the merge section.
78     // Since the objects in the merge section are not necessarily
79     // contiguous in the output, the addend can thus affect the final
80     // VA in a non-linear way.
81     // To make this work, we incorporate the addend into the section
82     // offset (and zero out the addend for later processing) so that
83     // we find the right object in the section.
84     if (d.isSection()) {
85       offset += addend;
86       addend = 0;
87     }
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 
101     // MIPS relocatable files can mix regular and microMIPS code.
102     // Linker needs to distinguish such code. To do so microMIPS
103     // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
104     // field. Unfortunately, the `MIPS::relocateOne()` method has
105     // a symbol value only. To pass type of the symbol (regular/microMIPS)
106     // to that routine as well as other places where we write
107     // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
108     // field etc) do the same trick as compiler uses to mark microMIPS
109     // for CPU - set the less-significant bit.
110     if (config->emachine == EM_MIPS && isMicroMips() &&
111         ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
112       va |= 1;
113 
114     if (d.isTls() && !config->relocatable) {
115       // Use the address of the TLS segment's first section rather than the
116       // segment's address, because segment addresses aren't initialized until
117       // after sections are finalized. (e.g. Measuring the size of .rela.dyn
118       // for Android relocation packing requires knowing TLS symbol addresses
119       // during section finalization.)
120       if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
121         fatal(toString(d.file) +
122               " has an STT_TLS symbol but doesn't have an SHF_TLS section");
123       return va - Out::tlsPhdr->firstSec->addr;
124     }
125     return va;
126   }
127   case Symbol::SharedKind:
128   case Symbol::UndefinedKind:
129     return 0;
130   case Symbol::LazyArchiveKind:
131   case Symbol::LazyObjectKind:
132     assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
133     return 0;
134   case Symbol::CommonKind:
135     llvm_unreachable("common symbol reached writer");
136   case Symbol::PlaceholderKind:
137     llvm_unreachable("placeholder symbol reached writer");
138   }
139   llvm_unreachable("invalid symbol kind");
140 }
141 
142 uint64_t Symbol::getVA(int64_t addend) const {
143   uint64_t outVA = getSymVA(*this, addend);
144   return outVA + 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 { return gotIndex * config->wordsize; }
154 
155 uint64_t Symbol::getGotPltVA() const {
156   if (isInIplt)
157     return in.igotPlt->getVA() + getGotPltOffset();
158   return in.gotPlt->getVA() + getGotPltOffset();
159 }
160 
161 uint64_t Symbol::getGotPltOffset() const {
162   if (isInIplt)
163     return pltIndex * config->wordsize;
164   return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
165 }
166 
167 uint64_t Symbol::getPPC64LongBranchOffset() const {
168   assert(ppc64BranchltIndex != 0xffff);
169   return ppc64BranchltIndex * config->wordsize;
170 }
171 
172 uint64_t Symbol::getPltVA() const {
173   PltSection *plt = isInIplt ? in.iplt : in.plt;
174   uint64_t outVA =
175       plt->getVA() + plt->headerSize + pltIndex * target->pltEntrySize;
176   // While linking microMIPS code PLT code are always microMIPS
177   // code. Set the less-significant bit to track that fact.
178   // See detailed comment in the `getSymVA` function.
179   if (config->emachine == EM_MIPS && isMicroMips())
180     outVA |= 1;
181   return outVA;
182 }
183 
184 uint64_t Symbol::getPPC64LongBranchTableVA() const {
185   assert(ppc64BranchltIndex != 0xffff);
186   return in.ppc64LongBranchTarget->getVA() +
187          ppc64BranchltIndex * config->wordsize;
188 }
189 
190 uint64_t Symbol::getSize() const {
191   if (const auto *dr = dyn_cast<Defined>(this))
192     return dr->size;
193   return cast<SharedSymbol>(this)->size;
194 }
195 
196 OutputSection *Symbol::getOutputSection() const {
197   if (auto *s = dyn_cast<Defined>(this)) {
198     if (auto *sec = s->section)
199       return sec->repl->getOutputSection();
200     return nullptr;
201   }
202   return nullptr;
203 }
204 
205 // If a symbol name contains '@', the characters after that is
206 // a symbol version name. This function parses that.
207 void Symbol::parseSymbolVersion() {
208   StringRef s = getName();
209   size_t pos = s.find('@');
210   if (pos == 0 || pos == StringRef::npos)
211     return;
212   StringRef verstr = s.substr(pos + 1);
213   if (verstr.empty())
214     return;
215 
216   // Truncate the symbol name so that it doesn't include the version string.
217   nameSize = pos;
218 
219   // If this is not in this DSO, it is not a definition.
220   if (!isDefined())
221     return;
222 
223   // '@@' in a symbol name means the default version.
224   // It is usually the most recent one.
225   bool isDefault = (verstr[0] == '@');
226   if (isDefault)
227     verstr = verstr.substr(1);
228 
229   for (const VersionDefinition &ver : namedVersionDefs()) {
230     if (ver.name != verstr)
231       continue;
232 
233     if (isDefault)
234       versionId = ver.id;
235     else
236       versionId = ver.id | VERSYM_HIDDEN;
237     return;
238   }
239 
240   // It is an error if the specified version is not defined.
241   // Usually version script is not provided when linking executable,
242   // but we may still want to override a versioned symbol from DSO,
243   // so we do not report error in this case. We also do not error
244   // if the symbol has a local version as it won't be in the dynamic
245   // symbol table.
246   if (config->shared && versionId != VER_NDX_LOCAL)
247     error(toString(file) + ": symbol " + s + " has undefined version " +
248           verstr);
249 }
250 
251 void Symbol::fetch() const {
252   if (auto *sym = dyn_cast<LazyArchive>(this)) {
253     cast<ArchiveFile>(sym->file)->fetch(sym->sym);
254     return;
255   }
256 
257   if (auto *sym = dyn_cast<LazyObject>(this)) {
258     dyn_cast<LazyObjFile>(sym->file)->fetch();
259     return;
260   }
261 
262   llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
263 }
264 
265 MemoryBufferRef LazyArchive::getMemberBuffer() {
266   Archive::Child c =
267       CHECK(sym.getMember(),
268             "could not get the member for symbol " + toELFString(sym));
269 
270   return CHECK(c.getMemoryBufferRef(),
271                "could not get the buffer for the member defining symbol " +
272                    toELFString(sym));
273 }
274 
275 uint8_t Symbol::computeBinding() const {
276   if (config->relocatable)
277     return binding;
278   if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
279       versionId == VER_NDX_LOCAL)
280     return STB_LOCAL;
281   if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
282     return STB_GLOBAL;
283   return binding;
284 }
285 
286 bool Symbol::includeInDynsym() const {
287   if (!config->hasDynSymTab)
288     return false;
289   if (computeBinding() == STB_LOCAL)
290     return false;
291 
292   // If a PIE binary was not linked against any shared libraries, then we can
293   // safely drop weak undef symbols from .dynsym.
294   if (isUndefWeak() && config->pie && sharedFiles.empty())
295     return false;
296 
297   return isUndefined() || isShared() || exportDynamic || inDynamicList;
298 }
299 
300 // Print out a log message for --trace-symbol.
301 void elf::printTraceSymbol(const Symbol *sym) {
302   std::string s;
303   if (sym->isUndefined())
304     s = ": reference to ";
305   else if (sym->isLazy())
306     s = ": lazy definition of ";
307   else if (sym->isShared())
308     s = ": shared definition of ";
309   else if (sym->isCommon())
310     s = ": common definition of ";
311   else
312     s = ": definition of ";
313 
314   message(toString(sym->file) + s + sym->getName());
315 }
316 
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->repl->isLive())
344     report(": unable to order discarded symbol: ");
345 }
346 
347 static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
348   if (va == STV_DEFAULT)
349     return vb;
350   if (vb == STV_DEFAULT)
351     return va;
352   return std::min(va, vb);
353 }
354 
355 // Merge symbol properties.
356 //
357 // When we have many symbols of the same name, we choose one of them,
358 // and that's the result of symbol resolution. However, symbols that
359 // were not chosen still affect some symbol properties.
360 void Symbol::mergeProperties(const Symbol &other) {
361   if (other.exportDynamic)
362     exportDynamic = true;
363   if (other.isUsedInRegularObj)
364     isUsedInRegularObj = true;
365 
366   // DSO symbols do not affect visibility in the output.
367   if (!other.isShared())
368     visibility = getMinVisibility(visibility, other.visibility);
369 }
370 
371 void Symbol::resolve(const Symbol &other) {
372   mergeProperties(other);
373 
374   if (isPlaceholder()) {
375     replace(other);
376     return;
377   }
378 
379   switch (other.kind()) {
380   case Symbol::UndefinedKind:
381     resolveUndefined(cast<Undefined>(other));
382     break;
383   case Symbol::CommonKind:
384     resolveCommon(cast<CommonSymbol>(other));
385     break;
386   case Symbol::DefinedKind:
387     resolveDefined(cast<Defined>(other));
388     break;
389   case Symbol::LazyArchiveKind:
390     resolveLazy(cast<LazyArchive>(other));
391     break;
392   case Symbol::LazyObjectKind:
393     resolveLazy(cast<LazyObject>(other));
394     break;
395   case Symbol::SharedKind:
396     resolveShared(cast<SharedSymbol>(other));
397     break;
398   case Symbol::PlaceholderKind:
399     llvm_unreachable("bad symbol kind");
400   }
401 }
402 
403 void Symbol::resolveUndefined(const Undefined &other) {
404   // An undefined symbol with non default visibility must be satisfied
405   // in the same DSO.
406   //
407   // If this is a non-weak defined symbol in a discarded section, override the
408   // existing undefined symbol for better error message later.
409   if ((isShared() && other.visibility != STV_DEFAULT) ||
410       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
411     replace(other);
412     return;
413   }
414 
415   if (traced)
416     printTraceSymbol(&other);
417 
418   if (isLazy()) {
419     // An undefined weak will not fetch archive members. See comment on Lazy in
420     // Symbols.h for the details.
421     if (other.binding == STB_WEAK) {
422       binding = STB_WEAK;
423       type = other.type;
424       return;
425     }
426 
427     // Do extra check for --warn-backrefs.
428     //
429     // --warn-backrefs is an option to prevent an undefined reference from
430     // fetching an archive member written earlier in the command line. It can be
431     // used to keep compatibility with GNU linkers to some degree.
432     // I'll explain the feature and why you may find it useful in this comment.
433     //
434     // lld's symbol resolution semantics is more relaxed than traditional Unix
435     // linkers. For example,
436     //
437     //   ld.lld foo.a bar.o
438     //
439     // succeeds even if bar.o contains an undefined symbol that has to be
440     // resolved by some object file in foo.a. Traditional Unix linkers don't
441     // allow this kind of backward reference, as they visit each file only once
442     // from left to right in the command line while resolving all undefined
443     // symbols at the moment of visiting.
444     //
445     // In the above case, since there's no undefined symbol when a linker visits
446     // foo.a, no files are pulled out from foo.a, and because the linker forgets
447     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
448     // that could have been resolved otherwise.
449     //
450     // That lld accepts more relaxed form means that (besides it'd make more
451     // sense) you can accidentally write a command line or a build file that
452     // works only with lld, even if you have a plan to distribute it to wider
453     // users who may be using GNU linkers. With --warn-backrefs, you can detect
454     // a library order that doesn't work with other Unix linkers.
455     //
456     // The option is also useful to detect cyclic dependencies between static
457     // archives. Again, lld accepts
458     //
459     //   ld.lld foo.a bar.a
460     //
461     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
462     // handled as an error.
463     //
464     // Here is how the option works. We assign a group ID to each file. A file
465     // with a smaller group ID can pull out object files from an archive file
466     // with an equal or greater group ID. Otherwise, it is a reverse dependency
467     // and an error.
468     //
469     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
470     // files within the same --{start,end}-group get the same group ID. E.g.
471     //
472     //   ld.lld A B --start-group C D --end-group E
473     //
474     // A forms group 0. B form group 1. C and D (including their member object
475     // files) form group 2. E forms group 3. I think that you can see how this
476     // group assignment rule simulates the traditional linker's semantics.
477     bool backref = config->warnBackrefs && other.file &&
478                    file->groupId < other.file->groupId;
479     fetch();
480 
481     // We don't report backward references to weak symbols as they can be
482     // overridden later.
483     if (backref && !isWeak())
484       warn("backward reference detected: " + other.getName() + " in " +
485            toString(other.file) + " refers to " + toString(file));
486     return;
487   }
488 
489   // Undefined symbols in a SharedFile do not change the binding.
490   if (dyn_cast_or_null<SharedFile>(other.file))
491     return;
492 
493   if (isUndefined() || isShared()) {
494     // The binding will be weak if there is at least one reference and all are
495     // weak. The binding has one opportunity to change to weak: if the first
496     // reference is weak.
497     if (other.binding != STB_WEAK || !referenced)
498       binding = other.binding;
499     referenced = true;
500   }
501 }
502 
503 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
504 // foo@@VER. We want to effectively ignore foo, so give precedence to
505 // foo@@VER.
506 // FIXME: If users can transition to using
507 // .symver foo,foo@@@VER
508 // we can delete this hack.
509 static int compareVersion(StringRef a, StringRef b) {
510   bool x = a.contains("@@");
511   bool y = b.contains("@@");
512   if (!x && y)
513     return 1;
514   if (x && !y)
515     return -1;
516   return 0;
517 }
518 
519 // Compare two symbols. Return 1 if the new symbol should win, -1 if
520 // the new symbol should lose, or 0 if there is a conflict.
521 int Symbol::compare(const Symbol *other) const {
522   assert(other->isDefined() || other->isCommon());
523 
524   if (!isDefined() && !isCommon())
525     return 1;
526 
527   if (int cmp = compareVersion(getName(), other->getName()))
528     return cmp;
529 
530   if (other->isWeak())
531     return -1;
532 
533   if (isWeak())
534     return 1;
535 
536   if (isCommon() && other->isCommon()) {
537     if (config->warnCommon)
538       warn("multiple common of " + getName());
539     return 0;
540   }
541 
542   if (isCommon()) {
543     if (config->warnCommon)
544       warn("common " + getName() + " is overridden");
545     return 1;
546   }
547 
548   if (other->isCommon()) {
549     if (config->warnCommon)
550       warn("common " + getName() + " is overridden");
551     return -1;
552   }
553 
554   auto *oldSym = cast<Defined>(this);
555   auto *newSym = cast<Defined>(other);
556 
557   if (dyn_cast_or_null<BitcodeFile>(other->file))
558     return 0;
559 
560   if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
561       newSym->binding == STB_GLOBAL)
562     return -1;
563 
564   return 0;
565 }
566 
567 static void reportDuplicate(Symbol *sym, InputFile *newFile,
568                             InputSectionBase *errSec, uint64_t errOffset) {
569   if (config->allowMultipleDefinition)
570     return;
571 
572   Defined *d = cast<Defined>(sym);
573   if (!d->section || !errSec) {
574     error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
575           toString(sym->file) + "\n>>> defined in " + toString(newFile));
576     return;
577   }
578 
579   // Construct and print an error message in the form of:
580   //
581   //   ld.lld: error: duplicate symbol: foo
582   //   >>> defined at bar.c:30
583   //   >>>            bar.o (/home/alice/src/bar.o)
584   //   >>> defined at baz.c:563
585   //   >>>            baz.o in archive libbaz.a
586   auto *sec1 = cast<InputSectionBase>(d->section);
587   std::string src1 = sec1->getSrcMsg(*sym, d->value);
588   std::string obj1 = sec1->getObjMsg(d->value);
589   std::string src2 = errSec->getSrcMsg(*sym, errOffset);
590   std::string obj2 = errSec->getObjMsg(errOffset);
591 
592   std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
593   if (!src1.empty())
594     msg += src1 + "\n>>>            ";
595   msg += obj1 + "\n>>> defined at ";
596   if (!src2.empty())
597     msg += src2 + "\n>>>            ";
598   msg += obj2;
599   error(msg);
600 }
601 
602 void Symbol::resolveCommon(const CommonSymbol &other) {
603   int cmp = compare(&other);
604   if (cmp < 0)
605     return;
606 
607   if (cmp > 0) {
608     replace(other);
609     return;
610   }
611 
612   CommonSymbol *oldSym = cast<CommonSymbol>(this);
613 
614   oldSym->alignment = std::max(oldSym->alignment, other.alignment);
615   if (oldSym->size < other.size) {
616     oldSym->file = other.file;
617     oldSym->size = other.size;
618   }
619 }
620 
621 void Symbol::resolveDefined(const Defined &other) {
622   int cmp = compare(&other);
623   if (cmp > 0)
624     replace(other);
625   else if (cmp == 0)
626     reportDuplicate(this, other.file,
627                     dyn_cast_or_null<InputSectionBase>(other.section),
628                     other.value);
629 }
630 
631 template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
632   if (!isUndefined())
633     return;
634 
635   // An undefined weak will not fetch archive members. See comment on Lazy in
636   // Symbols.h for the details.
637   if (isWeak()) {
638     uint8_t ty = type;
639     replace(other);
640     type = ty;
641     binding = STB_WEAK;
642     return;
643   }
644 
645   other.fetch();
646 }
647 
648 void Symbol::resolveShared(const SharedSymbol &other) {
649   if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
650     // An undefined symbol with non default visibility must be satisfied
651     // in the same DSO.
652     uint8_t bind = binding;
653     replace(other);
654     binding = bind;
655     referenced = true;
656   }
657 }
658