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