xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision 303c9861)
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 static uint64_t getSymVA(const Symbol &Sym, int64_t &Addend) {
46   switch (Sym.kind()) {
47   case Symbol::DefinedKind: {
48     auto &D = cast<Defined>(Sym);
49     SectionBase *IS = D.Section;
50 
51     // This is an absolute symbol.
52     if (!IS)
53       return D.Value;
54 
55     assert(IS != &InputSection::Discarded);
56     IS = IS->Repl;
57 
58     uint64_t Offset = D.Value;
59 
60     // An object in an SHF_MERGE section might be referenced via a
61     // section symbol (as a hack for reducing the number of local
62     // symbols).
63     // Depending on the addend, the reference via a section symbol
64     // refers to a different object in the merge section.
65     // Since the objects in the merge section are not necessarily
66     // contiguous in the output, the addend can thus affect the final
67     // VA in a non-linear way.
68     // To make this work, we incorporate the addend into the section
69     // offset (and zero out the addend for later processing) so that
70     // we find the right object in the section.
71     if (D.isSection()) {
72       Offset += Addend;
73       Addend = 0;
74     }
75 
76     // In the typical case, this is actually very simple and boils
77     // down to adding together 3 numbers:
78     // 1. The address of the output section.
79     // 2. The offset of the input section within the output section.
80     // 3. The offset within the input section (this addition happens
81     //    inside InputSection::getOffset).
82     //
83     // If you understand the data structures involved with this next
84     // line (and how they get built), then you have a pretty good
85     // understanding of the linker.
86     uint64_t VA = IS->getVA(Offset);
87 
88     // MIPS relocatable files can mix regular and microMIPS code.
89     // Linker needs to distinguish such code. To do so microMIPS
90     // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
91     // field. Unfortunately, the `MIPS::relocateOne()` method has
92     // a symbol value only. To pass type of the symbol (regular/microMIPS)
93     // to that routine as well as other places where we write
94     // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
95     // field etc) do the same trick as compiler uses to mark microMIPS
96     // for CPU - set the less-significant bit.
97     if (Config->EMachine == EM_MIPS && isMicroMips() &&
98         ((Sym.StOther & STO_MIPS_MICROMIPS) || Sym.NeedsPltAddr))
99       VA |= 1;
100 
101     if (D.isTls() && !Config->Relocatable) {
102       // Use the address of the TLS segment's first section rather than the
103       // segment's address, because segment addresses aren't initialized until
104       // after sections are finalized. (e.g. Measuring the size of .rela.dyn
105       // for Android relocation packing requires knowing TLS symbol addresses
106       // during section finalization.)
107       if (!Out::TlsPhdr || !Out::TlsPhdr->FirstSec)
108         fatal(toString(D.File) +
109               " has an STT_TLS symbol but doesn't have an SHF_TLS section");
110       return VA - Out::TlsPhdr->FirstSec->Addr;
111     }
112     return VA;
113   }
114   case Symbol::SharedKind:
115   case Symbol::UndefinedKind:
116     return 0;
117   case Symbol::LazyArchiveKind:
118   case Symbol::LazyObjectKind:
119     assert(Sym.IsUsedInRegularObj && "lazy symbol reached writer");
120     return 0;
121   case Symbol::CommonKind:
122     llvm_unreachable("common symbol reached writer");
123   case Symbol::PlaceholderKind:
124     llvm_unreachable("placeholder symbol reached writer");
125   }
126   llvm_unreachable("invalid symbol kind");
127 }
128 
129 uint64_t Symbol::getVA(int64_t Addend) const {
130   uint64_t OutVA = getSymVA(*this, Addend);
131   return OutVA + Addend;
132 }
133 
134 uint64_t Symbol::getGotVA() const {
135   if (GotInIgot)
136     return In.IgotPlt->getVA() + getGotPltOffset();
137   return In.Got->getVA() + getGotOffset();
138 }
139 
140 uint64_t Symbol::getGotOffset() const { return GotIndex * Config->Wordsize; }
141 
142 uint64_t Symbol::getGotPltVA() const {
143   if (IsInIplt)
144     return In.IgotPlt->getVA() + getGotPltOffset();
145   return In.GotPlt->getVA() + getGotPltOffset();
146 }
147 
148 uint64_t Symbol::getGotPltOffset() const {
149   if (IsInIplt)
150     return PltIndex * Config->Wordsize;
151   return (PltIndex + Target->GotPltHeaderEntriesNum) * Config->Wordsize;
152 }
153 
154 uint64_t Symbol::getPPC64LongBranchOffset() const {
155   assert(PPC64BranchltIndex != 0xffff);
156   return PPC64BranchltIndex * Config->Wordsize;
157 }
158 
159 uint64_t Symbol::getPltVA() const {
160   PltSection *Plt = IsInIplt ? In.Iplt : In.Plt;
161   uint64_t OutVA =
162       Plt->getVA() + Plt->HeaderSize + PltIndex * Target->PltEntrySize;
163   // While linking microMIPS code PLT code are always microMIPS
164   // code. Set the less-significant bit to track that fact.
165   // See detailed comment in the `getSymVA` function.
166   if (Config->EMachine == EM_MIPS && isMicroMips())
167     OutVA |= 1;
168   return OutVA;
169 }
170 
171 uint64_t Symbol::getPPC64LongBranchTableVA() const {
172   assert(PPC64BranchltIndex != 0xffff);
173   return In.PPC64LongBranchTarget->getVA() +
174          PPC64BranchltIndex * Config->Wordsize;
175 }
176 
177 uint64_t Symbol::getSize() const {
178   if (const auto *DR = dyn_cast<Defined>(this))
179     return DR->Size;
180   return cast<SharedSymbol>(this)->Size;
181 }
182 
183 OutputSection *Symbol::getOutputSection() const {
184   if (auto *S = dyn_cast<Defined>(this)) {
185     if (auto *Sec = S->Section)
186       return Sec->Repl->getOutputSection();
187     return nullptr;
188   }
189   return nullptr;
190 }
191 
192 // If a symbol name contains '@', the characters after that is
193 // a symbol version name. This function parses that.
194 void Symbol::parseSymbolVersion() {
195   StringRef S = getName();
196   size_t Pos = S.find('@');
197   if (Pos == 0 || Pos == StringRef::npos)
198     return;
199   StringRef Verstr = S.substr(Pos + 1);
200   if (Verstr.empty())
201     return;
202 
203   // Truncate the symbol name so that it doesn't include the version string.
204   NameSize = Pos;
205 
206   // If this is not in this DSO, it is not a definition.
207   if (!isDefined())
208     return;
209 
210   // '@@' in a symbol name means the default version.
211   // It is usually the most recent one.
212   bool IsDefault = (Verstr[0] == '@');
213   if (IsDefault)
214     Verstr = Verstr.substr(1);
215 
216   for (VersionDefinition &Ver : Config->VersionDefinitions) {
217     if (Ver.Name != Verstr)
218       continue;
219 
220     if (IsDefault)
221       VersionId = Ver.Id;
222     else
223       VersionId = Ver.Id | VERSYM_HIDDEN;
224     return;
225   }
226 
227   // It is an error if the specified version is not defined.
228   // Usually version script is not provided when linking executable,
229   // but we may still want to override a versioned symbol from DSO,
230   // so we do not report error in this case. We also do not error
231   // if the symbol has a local version as it won't be in the dynamic
232   // symbol table.
233   if (Config->Shared && VersionId != VER_NDX_LOCAL)
234     error(toString(File) + ": symbol " + S + " has undefined version " +
235           Verstr);
236 }
237 
238 void Symbol::fetch() const {
239   if (auto *Sym = dyn_cast<LazyArchive>(this)) {
240     cast<ArchiveFile>(Sym->File)->fetch(Sym->Sym);
241     return;
242   }
243 
244   if (auto *Sym = dyn_cast<LazyObject>(this)) {
245     dyn_cast<LazyObjFile>(Sym->File)->fetch();
246     return;
247   }
248 
249   llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
250 }
251 
252 MemoryBufferRef LazyArchive::getMemberBuffer() {
253   Archive::Child C = CHECK(
254       Sym.getMember(), "could not get the member for symbol " + Sym.getName());
255 
256   return CHECK(C.getMemoryBufferRef(),
257                "could not get the buffer for the member defining symbol " +
258                    Sym.getName());
259 }
260 
261 uint8_t Symbol::computeBinding() const {
262   if (Config->Relocatable)
263     return Binding;
264   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
265     return STB_LOCAL;
266   if (VersionId == VER_NDX_LOCAL && isDefined() && !IsPreemptible)
267     return STB_LOCAL;
268   if (!Config->GnuUnique && Binding == STB_GNU_UNIQUE)
269     return STB_GLOBAL;
270   return Binding;
271 }
272 
273 bool Symbol::includeInDynsym() const {
274   if (!Config->HasDynSymTab)
275     return false;
276   if (computeBinding() == STB_LOCAL)
277     return false;
278 
279   // If a PIE binary was not linked against any shared libraries, then we can
280   // safely drop weak undef symbols from .dynsym.
281   if (isUndefWeak() && Config->Pie && SharedFiles.empty())
282     return false;
283 
284   return isUndefined() || isShared() || ExportDynamic;
285 }
286 
287 // Print out a log message for --trace-symbol.
288 void elf::printTraceSymbol(const Symbol *Sym) {
289   std::string S;
290   if (Sym->isUndefined())
291     S = ": reference to ";
292   else if (Sym->isLazy())
293     S = ": lazy definition of ";
294   else if (Sym->isShared())
295     S = ": shared definition of ";
296   else if (Sym->isCommon())
297     S = ": common definition of ";
298   else
299     S = ": definition of ";
300 
301   message(toString(Sym->File) + S + Sym->getName());
302 }
303 
304 void elf::maybeWarnUnorderableSymbol(const Symbol *Sym) {
305   if (!Config->WarnSymbolOrdering)
306     return;
307 
308   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
309   // is emitted. It makes sense to not warn on undefined symbols.
310   //
311   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
312   // but we don't have to be compatible here.
313   if (Sym->isUndefined() &&
314       Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
315     return;
316 
317   const InputFile *File = Sym->File;
318   auto *D = dyn_cast<Defined>(Sym);
319 
320   auto Warn = [&](StringRef S) { warn(toString(File) + S + Sym->getName()); };
321 
322   if (Sym->isUndefined())
323     Warn(": unable to order undefined symbol: ");
324   else if (Sym->isShared())
325     Warn(": unable to order shared symbol: ");
326   else if (D && !D->Section)
327     Warn(": unable to order absolute symbol: ");
328   else if (D && isa<OutputSection>(D->Section))
329     Warn(": unable to order synthetic symbol: ");
330   else if (D && !D->Section->Repl->isLive())
331     Warn(": unable to order discarded symbol: ");
332 }
333 
334 // Returns a symbol for an error message.
335 std::string lld::toString(const Symbol &B) {
336   if (Config->Demangle)
337     if (Optional<std::string> S = demangleItanium(B.getName()))
338       return *S;
339   return B.getName();
340 }
341 
342 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
343   if (VA == STV_DEFAULT)
344     return VB;
345   if (VB == STV_DEFAULT)
346     return VA;
347   return std::min(VA, VB);
348 }
349 
350 // Merge symbol properties.
351 //
352 // When we have many symbols of the same name, we choose one of them,
353 // and that's the result of symbol resolution. However, symbols that
354 // were not chosen still affect some symbol properties.
355 void Symbol::mergeProperties(const Symbol &Other) {
356   if (Other.ExportDynamic)
357     ExportDynamic = true;
358   if (Other.IsUsedInRegularObj)
359     IsUsedInRegularObj = true;
360 
361   // DSO symbols do not affect visibility in the output.
362   if (!Other.isShared())
363     Visibility = getMinVisibility(Visibility, Other.Visibility);
364 }
365 
366 void Symbol::resolve(const Symbol &Other) {
367   mergeProperties(Other);
368 
369   if (isPlaceholder()) {
370     replace(Other);
371     return;
372   }
373 
374   switch (Other.kind()) {
375   case Symbol::UndefinedKind:
376     resolveUndefined(cast<Undefined>(Other));
377     break;
378   case Symbol::CommonKind:
379     resolveCommon(cast<CommonSymbol>(Other));
380     break;
381   case Symbol::DefinedKind:
382     resolveDefined(cast<Defined>(Other));
383     break;
384   case Symbol::LazyArchiveKind:
385     resolveLazy(cast<LazyArchive>(Other));
386     break;
387   case Symbol::LazyObjectKind:
388     resolveLazy(cast<LazyObject>(Other));
389     break;
390   case Symbol::SharedKind:
391     resolveShared(cast<SharedSymbol>(Other));
392     break;
393   case Symbol::PlaceholderKind:
394     llvm_unreachable("bad symbol kind");
395   }
396 }
397 
398 void Symbol::resolveUndefined(const Undefined &Other) {
399   // An undefined symbol with non default visibility must be satisfied
400   // in the same DSO.
401   //
402   // If this is a non-weak defined symbol in a discarded section, override the
403   // existing undefined symbol for better error message later.
404   if ((isShared() && Other.Visibility != STV_DEFAULT) ||
405       (isUndefined() && Other.Binding != STB_WEAK && Other.DiscardedSecIdx)) {
406     replace(Other);
407     return;
408   }
409 
410   if (Traced)
411     printTraceSymbol(&Other);
412 
413   if (isShared() || isLazy() || (isUndefined() && Other.Binding != STB_WEAK))
414     Binding = Other.Binding;
415 
416   if (isLazy()) {
417     // An undefined weak will not fetch archive members. See comment on Lazy in
418     // Symbols.h for the details.
419     if (Other.Binding == STB_WEAK) {
420       Type = Other.Type;
421       return;
422     }
423 
424     // Do extra check for --warn-backrefs.
425     //
426     // --warn-backrefs is an option to prevent an undefined reference from
427     // fetching an archive member written earlier in the command line. It can be
428     // used to keep compatibility with GNU linkers to some degree.
429     // I'll explain the feature and why you may find it useful in this comment.
430     //
431     // lld's symbol resolution semantics is more relaxed than traditional Unix
432     // linkers. For example,
433     //
434     //   ld.lld foo.a bar.o
435     //
436     // succeeds even if bar.o contains an undefined symbol that has to be
437     // resolved by some object file in foo.a. Traditional Unix linkers don't
438     // allow this kind of backward reference, as they visit each file only once
439     // from left to right in the command line while resolving all undefined
440     // symbols at the moment of visiting.
441     //
442     // In the above case, since there's no undefined symbol when a linker visits
443     // foo.a, no files are pulled out from foo.a, and because the linker forgets
444     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
445     // that could have been resolved otherwise.
446     //
447     // That lld accepts more relaxed form means that (besides it'd make more
448     // sense) you can accidentally write a command line or a build file that
449     // works only with lld, even if you have a plan to distribute it to wider
450     // users who may be using GNU linkers. With --warn-backrefs, you can detect
451     // a library order that doesn't work with other Unix linkers.
452     //
453     // The option is also useful to detect cyclic dependencies between static
454     // archives. Again, lld accepts
455     //
456     //   ld.lld foo.a bar.a
457     //
458     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
459     // handled as an error.
460     //
461     // Here is how the option works. We assign a group ID to each file. A file
462     // with a smaller group ID can pull out object files from an archive file
463     // with an equal or greater group ID. Otherwise, it is a reverse dependency
464     // and an error.
465     //
466     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
467     // files within the same --{start,end}-group get the same group ID. E.g.
468     //
469     //   ld.lld A B --start-group C D --end-group E
470     //
471     // A forms group 0. B form group 1. C and D (including their member object
472     // files) form group 2. E forms group 3. I think that you can see how this
473     // group assignment rule simulates the traditional linker's semantics.
474     bool Backref = Config->WarnBackrefs && Other.File &&
475                    File->GroupId < Other.File->GroupId;
476     fetch();
477 
478     // We don't report backward references to weak symbols as they can be
479     // overridden later.
480     if (Backref && !isWeak())
481       warn("backward reference detected: " + Other.getName() + " in " +
482            toString(Other.File) + " refers to " + toString(File));
483   }
484 }
485 
486 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
487 // foo@@VER. We want to effectively ignore foo, so give precedence to
488 // foo@@VER.
489 // FIXME: If users can transition to using
490 // .symver foo,foo@@@VER
491 // we can delete this hack.
492 static int compareVersion(StringRef A, StringRef B) {
493   bool X = A.contains("@@");
494   bool Y = B.contains("@@");
495   if (!X && Y)
496     return 1;
497   if (X && !Y)
498     return -1;
499   return 0;
500 }
501 
502 // Compare two symbols. Return 1 if the new symbol should win, -1 if
503 // the new symbol should lose, or 0 if there is a conflict.
504 int Symbol::compare(const Symbol *Other) const {
505   assert(Other->isDefined() || Other->isCommon());
506 
507   if (!isDefined() && !isCommon())
508     return 1;
509 
510   if (int Cmp = compareVersion(getName(), Other->getName()))
511     return Cmp;
512 
513   if (Other->isWeak())
514     return -1;
515 
516   if (isWeak())
517     return 1;
518 
519   if (isCommon() && Other->isCommon()) {
520     if (Config->WarnCommon)
521       warn("multiple common of " + getName());
522     return 0;
523   }
524 
525   if (isCommon()) {
526     if (Config->WarnCommon)
527       warn("common " + getName() + " is overridden");
528     return 1;
529   }
530 
531   if (Other->isCommon()) {
532     if (Config->WarnCommon)
533       warn("common " + getName() + " is overridden");
534     return -1;
535   }
536 
537   auto *OldSym = cast<Defined>(this);
538   auto *NewSym = cast<Defined>(Other);
539 
540   if (Other->File && isa<BitcodeFile>(Other->File))
541     return 0;
542 
543   if (!OldSym->Section && !NewSym->Section && OldSym->Value == NewSym->Value &&
544       NewSym->Binding == STB_GLOBAL)
545     return -1;
546 
547   return 0;
548 }
549 
550 static void reportDuplicate(Symbol *Sym, InputFile *NewFile,
551                             InputSectionBase *ErrSec, uint64_t ErrOffset) {
552   if (Config->AllowMultipleDefinition)
553     return;
554 
555   Defined *D = cast<Defined>(Sym);
556   if (!D->Section || !ErrSec) {
557     error("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " +
558           toString(Sym->File) + "\n>>> defined in " + toString(NewFile));
559     return;
560   }
561 
562   // Construct and print an error message in the form of:
563   //
564   //   ld.lld: error: duplicate symbol: foo
565   //   >>> defined at bar.c:30
566   //   >>>            bar.o (/home/alice/src/bar.o)
567   //   >>> defined at baz.c:563
568   //   >>>            baz.o in archive libbaz.a
569   auto *Sec1 = cast<InputSectionBase>(D->Section);
570   std::string Src1 = Sec1->getSrcMsg(*Sym, D->Value);
571   std::string Obj1 = Sec1->getObjMsg(D->Value);
572   std::string Src2 = ErrSec->getSrcMsg(*Sym, ErrOffset);
573   std::string Obj2 = ErrSec->getObjMsg(ErrOffset);
574 
575   std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at ";
576   if (!Src1.empty())
577     Msg += Src1 + "\n>>>            ";
578   Msg += Obj1 + "\n>>> defined at ";
579   if (!Src2.empty())
580     Msg += Src2 + "\n>>>            ";
581   Msg += Obj2;
582   error(Msg);
583 }
584 
585 void Symbol::resolveCommon(const CommonSymbol &Other) {
586   int Cmp = compare(&Other);
587   if (Cmp < 0)
588     return;
589 
590   if (Cmp > 0) {
591     replace(Other);
592     return;
593   }
594 
595   CommonSymbol *OldSym = cast<CommonSymbol>(this);
596 
597   OldSym->Alignment = std::max(OldSym->Alignment, Other.Alignment);
598   if (OldSym->Size < Other.Size) {
599     OldSym->File = Other.File;
600     OldSym->Size = Other.Size;
601   }
602 }
603 
604 void Symbol::resolveDefined(const Defined &Other) {
605   int Cmp = compare(&Other);
606   if (Cmp > 0)
607     replace(Other);
608   else if (Cmp == 0)
609     reportDuplicate(this, Other.File,
610                     dyn_cast_or_null<InputSectionBase>(Other.Section),
611                     Other.Value);
612 }
613 
614 template <class LazyT> void Symbol::resolveLazy(const LazyT &Other) {
615   if (!isUndefined())
616     return;
617 
618   // An undefined weak will not fetch archive members. See comment on Lazy in
619   // Symbols.h for the details.
620   if (isWeak()) {
621     uint8_t Ty = Type;
622     replace(Other);
623     Type = Ty;
624     Binding = STB_WEAK;
625     return;
626   }
627 
628   Other.fetch();
629 }
630 
631 void Symbol::resolveShared(const SharedSymbol &Other) {
632   if (Visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
633     // An undefined symbol with non default visibility must be satisfied
634     // in the same DSO.
635     uint8_t Bind = Binding;
636     replace(Other);
637     Binding = Bind;
638   }
639 }
640