1 //===- SymbolTable.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 // Symbol table is a bag of all known symbols. We put all symbols of
10 // all input files to the symbol table. The symbol table is basically
11 // a hash table with the logic to resolve symbol name conflicts using
12 // the symbol types.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "SymbolTable.h"
17 #include "Config.h"
18 #include "LinkerScript.h"
19 #include "Symbols.h"
20 #include "SyntheticSections.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Strings.h"
24 #include "llvm/ADT/STLExtras.h"
25 
26 using namespace llvm;
27 using namespace llvm::object;
28 using namespace llvm::ELF;
29 
30 using namespace lld;
31 using namespace lld::elf;
32 
33 SymbolTable *elf::Symtab;
34 
35 // This function is where all the optimizations of link-time
36 // optimization happens. When LTO is in use, some input files are
37 // not in native object file format but in the LLVM bitcode format.
38 // This function compiles bitcode files into a few big native files
39 // using LLVM functions and replaces bitcode symbols with the results.
40 // Because all bitcode files that the program consists of are passed
41 // to the compiler at once, it can do whole-program optimization.
42 template <class ELFT> void SymbolTable::addCombinedLTOObject() {
43   // Compile bitcode files and replace bitcode symbols.
44   LTO.reset(new BitcodeCompiler);
45   for (BitcodeFile *F : BitcodeFiles)
46     LTO->add(*F);
47 
48   for (InputFile *File : LTO->compile()) {
49     DenseSet<CachedHashStringRef> DummyGroups;
50     auto *Obj = cast<ObjFile<ELFT>>(File);
51     Obj->parse(DummyGroups);
52     for (Symbol *Sym : Obj->getGlobalSymbols())
53       Sym->parseSymbolVersion();
54     ObjectFiles.push_back(File);
55   }
56 }
57 
58 // Set a flag for --trace-symbol so that we can print out a log message
59 // if a new symbol with the same name is inserted into the symbol table.
60 void SymbolTable::trace(StringRef Name) {
61   SymMap.insert({CachedHashStringRef(Name), -1});
62 }
63 
64 void SymbolTable::wrap(Symbol *Sym, Symbol *Real, Symbol *Wrap) {
65   // Swap symbols as instructed by -wrap.
66   int &Idx1 = SymMap[CachedHashStringRef(Sym->getName())];
67   int &Idx2 = SymMap[CachedHashStringRef(Real->getName())];
68   int &Idx3 = SymMap[CachedHashStringRef(Wrap->getName())];
69 
70   Idx2 = Idx1;
71   Idx1 = Idx3;
72 
73   // Now renaming is complete. No one refers Real symbol. We could leave
74   // Real as-is, but if Real is written to the symbol table, that may
75   // contain irrelevant values. So, we copy all values from Sym to Real.
76   StringRef S = Real->getName();
77   memcpy(Real, Sym, sizeof(SymbolUnion));
78   Real->setName(S);
79 }
80 
81 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
82   if (VA == STV_DEFAULT)
83     return VB;
84   if (VB == STV_DEFAULT)
85     return VA;
86   return std::min(VA, VB);
87 }
88 
89 // Find an existing symbol or create and insert a new one.
90 Symbol *SymbolTable::insert(const Symbol &New) {
91   // <name>@@<version> means the symbol is the default version. In that
92   // case <name>@@<version> will be used to resolve references to <name>.
93   //
94   // Since this is a hot path, the following string search code is
95   // optimized for speed. StringRef::find(char) is much faster than
96   // StringRef::find(StringRef).
97   StringRef Name = New.getName();
98   size_t Pos = Name.find('@');
99   if (Pos != StringRef::npos && Pos + 1 < Name.size() && Name[Pos + 1] == '@')
100     Name = Name.take_front(Pos);
101 
102   auto P = SymMap.insert({CachedHashStringRef(Name), (int)SymVector.size()});
103   int &SymIndex = P.first->second;
104   bool IsNew = P.second;
105   bool Traced = false;
106 
107   if (SymIndex == -1) {
108     SymIndex = SymVector.size();
109     IsNew = true;
110     Traced = true;
111   }
112 
113   Symbol *Old;
114   if (IsNew) {
115     Old = reinterpret_cast<Symbol *>(make<SymbolUnion>());
116     SymVector.push_back(Old);
117 
118     Old->SymbolKind = Symbol::PlaceholderKind;
119     Old->VersionId = Config->DefaultSymbolVersion;
120     Old->Visibility = STV_DEFAULT;
121     Old->IsUsedInRegularObj = false;
122     Old->ExportDynamic = false;
123     Old->CanInline = true;
124     Old->Traced = Traced;
125     Old->ScriptDefined = false;
126   } else {
127     Old = SymVector[SymIndex];
128   }
129 
130   return Old;
131 }
132 
133 // Merge symbol properties.
134 //
135 // When we have many symbols of the same name, we choose one of them,
136 // and that's the result of symbol resolution. However, symbols that
137 // were not chosen still affect some symbol properteis.
138 void SymbolTable::mergeProperties(Symbol *Old, const Symbol &New) {
139   // Merge symbol properties.
140   Old->ExportDynamic = Old->ExportDynamic || New.ExportDynamic;
141   Old->IsUsedInRegularObj = Old->IsUsedInRegularObj || New.IsUsedInRegularObj;
142 
143   // DSO symbols do not affect visibility in the output.
144   if (!isa<SharedSymbol>(New))
145     Old->Visibility = getMinVisibility(Old->Visibility, New.Visibility);
146 }
147 
148 Symbol *SymbolTable::addUndefined(const Undefined &New) {
149   Symbol *Old = insert(New);
150   mergeProperties(Old, New);
151 
152   if (Old->isPlaceholder()) {
153     replaceSymbol(Old, &New);
154     return Old;
155   }
156 
157   // An undefined symbol with non default visibility must be satisfied
158   // in the same DSO.
159   if (Old->isShared() && New.Visibility != STV_DEFAULT) {
160     replaceSymbol(Old, &New);
161     return Old;
162   }
163 
164   if (Old->isShared() || Old->isLazy() ||
165       (Old->isUndefined() && New.Binding != STB_WEAK))
166     Old->Binding = New.Binding;
167 
168   if (Old->isLazy()) {
169     // An undefined weak will not fetch archive members. See comment on Lazy in
170     // Symbols.h for the details.
171     if (New.Binding == STB_WEAK) {
172       Old->Type = New.Type;
173       return Old;
174     }
175 
176     // Do extra check for --warn-backrefs.
177     //
178     // --warn-backrefs is an option to prevent an undefined reference from
179     // fetching an archive member written earlier in the command line. It can be
180     // used to keep compatibility with GNU linkers to some degree.
181     // I'll explain the feature and why you may find it useful in this comment.
182     //
183     // lld's symbol resolution semantics is more relaxed than traditional Unix
184     // linkers. For example,
185     //
186     //   ld.lld foo.a bar.o
187     //
188     // succeeds even if bar.o contains an undefined symbol that has to be
189     // resolved by some object file in foo.a. Traditional Unix linkers don't
190     // allow this kind of backward reference, as they visit each file only once
191     // from left to right in the command line while resolving all undefined
192     // symbols at the moment of visiting.
193     //
194     // In the above case, since there's no undefined symbol when a linker visits
195     // foo.a, no files are pulled out from foo.a, and because the linker forgets
196     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
197     // that could have been resolved otherwise.
198     //
199     // That lld accepts more relaxed form means that (besides it'd make more
200     // sense) you can accidentally write a command line or a build file that
201     // works only with lld, even if you have a plan to distribute it to wider
202     // users who may be using GNU linkers. With --warn-backrefs, you can detect
203     // a library order that doesn't work with other Unix linkers.
204     //
205     // The option is also useful to detect cyclic dependencies between static
206     // archives. Again, lld accepts
207     //
208     //   ld.lld foo.a bar.a
209     //
210     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
211     // handled as an error.
212     //
213     // Here is how the option works. We assign a group ID to each file. A file
214     // with a smaller group ID can pull out object files from an archive file
215     // with an equal or greater group ID. Otherwise, it is a reverse dependency
216     // and an error.
217     //
218     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
219     // files within the same --{start,end}-group get the same group ID. E.g.
220     //
221     //   ld.lld A B --start-group C D --end-group E
222     //
223     // A forms group 0. B form group 1. C and D (including their member object
224     // files) form group 2. E forms group 3. I think that you can see how this
225     // group assignment rule simulates the traditional linker's semantics.
226     bool Backref = Config->WarnBackrefs && New.File &&
227                    Old->File->GroupId < New.File->GroupId;
228     fetchLazy(Old);
229 
230     // We don't report backward references to weak symbols as they can be
231     // overridden later.
232     if (Backref && !Old->isWeak())
233       warn("backward reference detected: " + New.getName() + " in " +
234            toString(New.File) + " refers to " + toString(Old->File));
235   }
236   return Old;
237 }
238 
239 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
240 // foo@@VER. We want to effectively ignore foo, so give precedence to
241 // foo@@VER.
242 // FIXME: If users can transition to using
243 // .symver foo,foo@@@VER
244 // we can delete this hack.
245 static int compareVersion(StringRef OldName, StringRef NewName) {
246   bool A = OldName.contains("@@");
247   bool B = NewName.contains("@@");
248   if (!A && B)
249     return 1;
250   if (A && !B)
251     return -1;
252   return 0;
253 }
254 
255 // Compare two symbols. Return 1 if the new symbol should win, -1 if
256 // the new symbol should lose, or 0 if there is a conflict.
257 static int compare(const Symbol *Old, const Symbol *New) {
258   assert(New->isDefined() || New->isCommon());
259 
260   if (!Old->isDefined() && !Old->isCommon())
261     return 1;
262 
263   if (int Cmp = compareVersion(Old->getName(), New->getName()))
264     return Cmp;
265 
266   if (New->isWeak())
267     return -1;
268 
269   if (Old->isWeak())
270     return 1;
271 
272   if (Old->isCommon() && New->isCommon()) {
273     if (Config->WarnCommon)
274       warn("multiple common of " + Old->getName());
275     return 0;
276   }
277 
278   if (Old->isCommon()) {
279     if (Config->WarnCommon)
280       warn("common " + Old->getName() + " is overridden");
281     return 1;
282   }
283 
284   if (New->isCommon()) {
285     if (Config->WarnCommon)
286       warn("common " + Old->getName() + " is overridden");
287     return -1;
288   }
289 
290   auto *OldSym = cast<Defined>(Old);
291   auto *NewSym = cast<Defined>(New);
292 
293   if (New->File && isa<BitcodeFile>(New->File))
294     return 0;
295 
296   if (!OldSym->Section && !NewSym->Section && OldSym->Value == NewSym->Value &&
297       NewSym->Binding == STB_GLOBAL)
298     return -1;
299 
300   return 0;
301 }
302 
303 Symbol *SymbolTable::addCommon(const CommonSymbol &New) {
304   Symbol *Old = insert(New);
305   mergeProperties(Old, New);
306 
307   if (Old->isPlaceholder()) {
308     replaceSymbol(Old, &New);
309     return Old;
310   }
311 
312   int Cmp = compare(Old, &New);
313   if (Cmp < 0)
314     return Old;
315 
316   if (Cmp > 0) {
317     replaceSymbol(Old, &New);
318     return Old;
319   }
320 
321   CommonSymbol *OldSym = cast<CommonSymbol>(Old);
322 
323   OldSym->Alignment = std::max(OldSym->Alignment, New.Alignment);
324   if (OldSym->Size < New.Size) {
325     OldSym->File = New.File;
326     OldSym->Size = New.Size;
327   }
328   return OldSym;
329 }
330 
331 static void reportDuplicate(Symbol *Sym, InputFile *NewFile,
332                             InputSectionBase *ErrSec, uint64_t ErrOffset) {
333   if (Config->AllowMultipleDefinition)
334     return;
335 
336   Defined *D = cast<Defined>(Sym);
337   if (!D->Section || !ErrSec) {
338     error("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " +
339           toString(Sym->File) + "\n>>> defined in " + toString(NewFile));
340     return;
341   }
342 
343   // Construct and print an error message in the form of:
344   //
345   //   ld.lld: error: duplicate symbol: foo
346   //   >>> defined at bar.c:30
347   //   >>>            bar.o (/home/alice/src/bar.o)
348   //   >>> defined at baz.c:563
349   //   >>>            baz.o in archive libbaz.a
350   auto *Sec1 = cast<InputSectionBase>(D->Section);
351   std::string Src1 = Sec1->getSrcMsg(*Sym, D->Value);
352   std::string Obj1 = Sec1->getObjMsg(D->Value);
353   std::string Src2 = ErrSec->getSrcMsg(*Sym, ErrOffset);
354   std::string Obj2 = ErrSec->getObjMsg(ErrOffset);
355 
356   std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at ";
357   if (!Src1.empty())
358     Msg += Src1 + "\n>>>            ";
359   Msg += Obj1 + "\n>>> defined at ";
360   if (!Src2.empty())
361     Msg += Src2 + "\n>>>            ";
362   Msg += Obj2;
363   error(Msg);
364 }
365 
366 Symbol *SymbolTable::addDefined(const Defined &New) {
367   Symbol *Old = insert(New);
368   mergeProperties(Old, New);
369 
370   if (Old->isPlaceholder()) {
371     replaceSymbol(Old, &New);
372     return Old;
373   }
374 
375   int Cmp = compare(Old, &New);
376   if (Cmp > 0)
377     replaceSymbol(Old, &New);
378   else if (Cmp == 0)
379     reportDuplicate(Old, New.File,
380                     dyn_cast_or_null<InputSectionBase>(New.Section), New.Value);
381   return Old;
382 }
383 
384 Symbol *SymbolTable::addShared(const SharedSymbol &New) {
385   Symbol *Old = insert(New);
386   mergeProperties(Old, New);
387 
388   // Make sure we preempt DSO symbols with default visibility.
389   if (New.Visibility == STV_DEFAULT)
390     Old->ExportDynamic = true;
391 
392   if (Old->isPlaceholder()) {
393     replaceSymbol(Old, &New);
394     return Old;
395   }
396 
397   if (Old->Visibility == STV_DEFAULT && (Old->isUndefined() || Old->isLazy())) {
398     // An undefined symbol with non default visibility must be satisfied
399     // in the same DSO.
400     uint8_t Binding = Old->Binding;
401     replaceSymbol(Old, &New);
402     Old->Binding = Binding;
403   }
404   return Old;
405 }
406 
407 Symbol *SymbolTable::find(StringRef Name) {
408   auto It = SymMap.find(CachedHashStringRef(Name));
409   if (It == SymMap.end())
410     return nullptr;
411   if (It->second == -1)
412     return nullptr;
413   return SymVector[It->second];
414 }
415 
416 template <class LazyT> Symbol *SymbolTable::addLazy(const LazyT &New) {
417   Symbol *Old = insert(New);
418   mergeProperties(Old, New);
419 
420   if (Old->isPlaceholder()) {
421     replaceSymbol(Old, &New);
422     return Old;
423   }
424 
425   if (!Old->isUndefined())
426     return Old;
427 
428   // An undefined weak will not fetch archive members. See comment on Lazy in
429   // Symbols.h for the details.
430   if (Old->isWeak()) {
431     uint8_t Type = Old->Type;
432     replaceSymbol(Old, &New);
433     Old->Type = Type;
434     Old->Binding = STB_WEAK;
435     return Old;
436   }
437 
438   if (InputFile *F = New.fetch())
439     parseFile(F);
440   return Old;
441 }
442 
443 Symbol *SymbolTable::addLazyArchive(const LazyArchive &New) {
444   return addLazy(New);
445 }
446 
447 Symbol *SymbolTable::addLazyObject(const LazyObject &New) {
448   return addLazy(New);
449 }
450 
451 void SymbolTable::fetchLazy(Symbol *Sym) {
452   if (auto *S = dyn_cast<LazyArchive>(Sym)) {
453     if (InputFile *File = S->fetch())
454       parseFile(File);
455     return;
456   }
457 
458   auto *S = cast<LazyObject>(Sym);
459   if (InputFile *File = cast<LazyObjFile>(S->File)->fetch())
460     parseFile(File);
461 }
462 
463 // Initialize DemangledSyms with a map from demangled symbols to symbol
464 // objects. Used to handle "extern C++" directive in version scripts.
465 //
466 // The map will contain all demangled symbols. That can be very large,
467 // and in LLD we generally want to avoid do anything for each symbol.
468 // Then, why are we doing this? Here's why.
469 //
470 // Users can use "extern C++ {}" directive to match against demangled
471 // C++ symbols. For example, you can write a pattern such as
472 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
473 // other than trying to match a pattern against all demangled symbols.
474 // So, if "extern C++" feature is used, we need to demangle all known
475 // symbols.
476 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() {
477   if (!DemangledSyms) {
478     DemangledSyms.emplace();
479     for (Symbol *Sym : SymVector) {
480       if (!Sym->isDefined() && !Sym->isCommon())
481         continue;
482       if (Optional<std::string> S = demangleItanium(Sym->getName()))
483         (*DemangledSyms)[*S].push_back(Sym);
484       else
485         (*DemangledSyms)[Sym->getName()].push_back(Sym);
486     }
487   }
488   return *DemangledSyms;
489 }
490 
491 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion Ver) {
492   if (Ver.IsExternCpp)
493     return getDemangledSyms().lookup(Ver.Name);
494   if (Symbol *B = find(Ver.Name))
495     if (B->isDefined() || B->isCommon())
496       return {B};
497   return {};
498 }
499 
500 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion Ver) {
501   std::vector<Symbol *> Res;
502   StringMatcher M(Ver.Name);
503 
504   if (Ver.IsExternCpp) {
505     for (auto &P : getDemangledSyms())
506       if (M.match(P.first()))
507         Res.insert(Res.end(), P.second.begin(), P.second.end());
508     return Res;
509   }
510 
511   for (Symbol *Sym : SymVector)
512     if ((Sym->isDefined() || Sym->isCommon()) && M.match(Sym->getName()))
513       Res.push_back(Sym);
514   return Res;
515 }
516 
517 // If there's only one anonymous version definition in a version
518 // script file, the script does not actually define any symbol version,
519 // but just specifies symbols visibilities.
520 void SymbolTable::handleAnonymousVersion() {
521   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
522     assignExactVersion(Ver, VER_NDX_GLOBAL, "global");
523   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
524     assignWildcardVersion(Ver, VER_NDX_GLOBAL);
525   for (SymbolVersion &Ver : Config->VersionScriptLocals)
526     assignExactVersion(Ver, VER_NDX_LOCAL, "local");
527   for (SymbolVersion &Ver : Config->VersionScriptLocals)
528     assignWildcardVersion(Ver, VER_NDX_LOCAL);
529 }
530 
531 // Handles -dynamic-list.
532 void SymbolTable::handleDynamicList() {
533   for (SymbolVersion &Ver : Config->DynamicList) {
534     std::vector<Symbol *> Syms;
535     if (Ver.HasWildcard)
536       Syms = findAllByVersion(Ver);
537     else
538       Syms = findByVersion(Ver);
539 
540     for (Symbol *B : Syms) {
541       if (!Config->Shared)
542         B->ExportDynamic = true;
543       else if (B->includeInDynsym())
544         B->IsPreemptible = true;
545     }
546   }
547 }
548 
549 // Set symbol versions to symbols. This function handles patterns
550 // containing no wildcard characters.
551 void SymbolTable::assignExactVersion(SymbolVersion Ver, uint16_t VersionId,
552                                      StringRef VersionName) {
553   if (Ver.HasWildcard)
554     return;
555 
556   // Get a list of symbols which we need to assign the version to.
557   std::vector<Symbol *> Syms = findByVersion(Ver);
558   if (Syms.empty()) {
559     if (!Config->UndefinedVersion)
560       error("version script assignment of '" + VersionName + "' to symbol '" +
561             Ver.Name + "' failed: symbol not defined");
562     return;
563   }
564 
565   // Assign the version.
566   for (Symbol *Sym : Syms) {
567     // Skip symbols containing version info because symbol versions
568     // specified by symbol names take precedence over version scripts.
569     // See parseSymbolVersion().
570     if (Sym->getName().contains('@'))
571       continue;
572 
573     if (Sym->VersionId != Config->DefaultSymbolVersion &&
574         Sym->VersionId != VersionId)
575       error("duplicate symbol '" + Ver.Name + "' in version script");
576     Sym->VersionId = VersionId;
577   }
578 }
579 
580 void SymbolTable::assignWildcardVersion(SymbolVersion Ver, uint16_t VersionId) {
581   if (!Ver.HasWildcard)
582     return;
583 
584   // Exact matching takes precendence over fuzzy matching,
585   // so we set a version to a symbol only if no version has been assigned
586   // to the symbol. This behavior is compatible with GNU.
587   for (Symbol *B : findAllByVersion(Ver))
588     if (B->VersionId == Config->DefaultSymbolVersion)
589       B->VersionId = VersionId;
590 }
591 
592 // This function processes version scripts by updating VersionId
593 // member of symbols.
594 void SymbolTable::scanVersionScript() {
595   // Handle edge cases first.
596   handleAnonymousVersion();
597   handleDynamicList();
598 
599   // Now we have version definitions, so we need to set version ids to symbols.
600   // Each version definition has a glob pattern, and all symbols that match
601   // with the pattern get that version.
602 
603   // First, we assign versions to exact matching symbols,
604   // i.e. version definitions not containing any glob meta-characters.
605   for (VersionDefinition &V : Config->VersionDefinitions)
606     for (SymbolVersion &Ver : V.Globals)
607       assignExactVersion(Ver, V.Id, V.Name);
608 
609   // Next, we assign versions to fuzzy matching symbols,
610   // i.e. version definitions containing glob meta-characters.
611   // Note that because the last match takes precedence over previous matches,
612   // we iterate over the definitions in the reverse order.
613   for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions))
614     for (SymbolVersion &Ver : V.Globals)
615       assignWildcardVersion(Ver, V.Id);
616 
617   // Symbol themselves might know their versions because symbols
618   // can contain versions in the form of <name>@<version>.
619   // Let them parse and update their names to exclude version suffix.
620   for (Symbol *Sym : SymVector)
621     Sym->parseSymbolVersion();
622 }
623 
624 template void SymbolTable::addCombinedLTOObject<ELF32LE>();
625 template void SymbolTable::addCombinedLTOObject<ELF32BE>();
626 template void SymbolTable::addCombinedLTOObject<ELF64LE>();
627 template void SymbolTable::addCombinedLTOObject<ELF64BE>();
628