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 static InputFile *getFirstElf() {
36   if (!ObjectFiles.empty())
37     return ObjectFiles[0];
38   if (!SharedFiles.empty())
39     return SharedFiles[0];
40   return BitcodeFiles[0];
41 }
42 
43 // All input object files must be for the same architecture
44 // (e.g. it does not make sense to link x86 object files with
45 // MIPS object files.) This function checks for that error.
46 static bool isCompatible(InputFile *F) {
47   if (!F->isElf() && !isa<BitcodeFile>(F))
48     return true;
49 
50   if (F->EKind == Config->EKind && F->EMachine == Config->EMachine) {
51     if (Config->EMachine != EM_MIPS)
52       return true;
53     if (isMipsN32Abi(F) == Config->MipsN32Abi)
54       return true;
55   }
56 
57   if (!Config->Emulation.empty())
58     error(toString(F) + " is incompatible with " + Config->Emulation);
59   else
60     error(toString(F) + " is incompatible with " + toString(getFirstElf()));
61   return false;
62 }
63 
64 // Add symbols in File to the symbol table.
65 template <class ELFT> void SymbolTable::addFile(InputFile *File) {
66   if (!isCompatible(File))
67     return;
68 
69   // Binary file
70   if (auto *F = dyn_cast<BinaryFile>(File)) {
71     BinaryFiles.push_back(F);
72     F->parse();
73     return;
74   }
75 
76   // .a file
77   if (auto *F = dyn_cast<ArchiveFile>(File)) {
78     F->parse<ELFT>();
79     return;
80   }
81 
82   // Lazy object file
83   if (auto *F = dyn_cast<LazyObjFile>(File)) {
84     LazyObjFiles.push_back(F);
85     F->parse<ELFT>();
86     return;
87   }
88 
89   if (Config->Trace)
90     message(toString(File));
91 
92   // .so file
93   if (auto *F = dyn_cast<SharedFile<ELFT>>(File)) {
94     // DSOs are uniquified not by filename but by soname.
95     F->parseDynamic();
96     if (errorCount())
97       return;
98 
99     // If a DSO appears more than once on the command line with and without
100     // --as-needed, --no-as-needed takes precedence over --as-needed because a
101     // user can add an extra DSO with --no-as-needed to force it to be added to
102     // the dependency list.
103     DenseMap<StringRef, InputFile *>::iterator It;
104     bool WasInserted;
105     std::tie(It, WasInserted) = SoNames.try_emplace(F->SoName, F);
106     cast<SharedFile<ELFT>>(It->second)->IsNeeded |= F->IsNeeded;
107     if (!WasInserted)
108       return;
109 
110     SharedFiles.push_back(F);
111     F->parseRest();
112     return;
113   }
114 
115   // LLVM bitcode file
116   if (auto *F = dyn_cast<BitcodeFile>(File)) {
117     BitcodeFiles.push_back(F);
118     F->parse<ELFT>(ComdatGroups);
119     return;
120   }
121 
122   // Regular object file
123   ObjectFiles.push_back(File);
124   cast<ObjFile<ELFT>>(File)->parse(ComdatGroups);
125 }
126 
127 // This function is where all the optimizations of link-time
128 // optimization happens. When LTO is in use, some input files are
129 // not in native object file format but in the LLVM bitcode format.
130 // This function compiles bitcode files into a few big native files
131 // using LLVM functions and replaces bitcode symbols with the results.
132 // Because all bitcode files that the program consists of are passed
133 // to the compiler at once, it can do whole-program optimization.
134 template <class ELFT> void SymbolTable::addCombinedLTOObject() {
135   if (BitcodeFiles.empty())
136     return;
137 
138   // Compile bitcode files and replace bitcode symbols.
139   LTO.reset(new BitcodeCompiler);
140   for (BitcodeFile *F : BitcodeFiles)
141     LTO->add(*F);
142 
143   for (InputFile *File : LTO->compile()) {
144     DenseSet<CachedHashStringRef> DummyGroups;
145     auto *Obj = cast<ObjFile<ELFT>>(File);
146     Obj->parse(DummyGroups);
147     for (Symbol *Sym : Obj->getGlobalSymbols())
148       Sym->parseSymbolVersion();
149     ObjectFiles.push_back(File);
150   }
151 }
152 
153 // Set a flag for --trace-symbol so that we can print out a log message
154 // if a new symbol with the same name is inserted into the symbol table.
155 void SymbolTable::trace(StringRef Name) {
156   SymMap.insert({CachedHashStringRef(Name), -1});
157 }
158 
159 void SymbolTable::wrap(Symbol *Sym, Symbol *Real, Symbol *Wrap) {
160   // Swap symbols as instructed by -wrap.
161   int &Idx1 = SymMap[CachedHashStringRef(Sym->getName())];
162   int &Idx2 = SymMap[CachedHashStringRef(Real->getName())];
163   int &Idx3 = SymMap[CachedHashStringRef(Wrap->getName())];
164 
165   Idx2 = Idx1;
166   Idx1 = Idx3;
167 
168   // Now renaming is complete. No one refers Real symbol. We could leave
169   // Real as-is, but if Real is written to the symbol table, that may
170   // contain irrelevant values. So, we copy all values from Sym to Real.
171   StringRef S = Real->getName();
172   memcpy(Real, Sym, sizeof(SymbolUnion));
173   Real->setName(S);
174 }
175 
176 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
177   if (VA == STV_DEFAULT)
178     return VB;
179   if (VB == STV_DEFAULT)
180     return VA;
181   return std::min(VA, VB);
182 }
183 
184 // Find an existing symbol or create and insert a new one.
185 std::pair<Symbol *, bool> SymbolTable::insertName(StringRef Name) {
186   // <name>@@<version> means the symbol is the default version. In that
187   // case <name>@@<version> will be used to resolve references to <name>.
188   //
189   // Since this is a hot path, the following string search code is
190   // optimized for speed. StringRef::find(char) is much faster than
191   // StringRef::find(StringRef).
192   size_t Pos = Name.find('@');
193   if (Pos != StringRef::npos && Pos + 1 < Name.size() && Name[Pos + 1] == '@')
194     Name = Name.take_front(Pos);
195 
196   auto P = SymMap.insert({CachedHashStringRef(Name), (int)SymVector.size()});
197   int &SymIndex = P.first->second;
198   bool IsNew = P.second;
199   bool Traced = false;
200 
201   if (SymIndex == -1) {
202     SymIndex = SymVector.size();
203     IsNew = true;
204     Traced = true;
205   }
206 
207   if (!IsNew)
208     return {SymVector[SymIndex], false};
209 
210   auto *Sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
211   Sym->SymbolKind = Symbol::PlaceholderKind;
212   Sym->Visibility = STV_DEFAULT;
213   Sym->IsUsedInRegularObj = false;
214   Sym->ExportDynamic = false;
215   Sym->CanInline = true;
216   Sym->Traced = Traced;
217   Sym->VersionId = Config->DefaultSymbolVersion;
218   SymVector.push_back(Sym);
219   return {Sym, true};
220 }
221 
222 // Find an existing symbol or create and insert a new one, then apply the given
223 // attributes.
224 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name,
225                                               uint8_t Visibility,
226                                               bool CanOmitFromDynSym,
227                                               InputFile *File) {
228   Symbol *S;
229   bool WasInserted;
230   std::tie(S, WasInserted) = insertName(Name);
231 
232   // Merge in the new symbol's visibility.
233   S->Visibility = getMinVisibility(S->Visibility, Visibility);
234 
235   if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic))
236     S->ExportDynamic = true;
237 
238   if (!File || File->kind() == InputFile::ObjKind)
239     S->IsUsedInRegularObj = true;
240 
241   return {S, WasInserted};
242 }
243 
244 static uint8_t getVisibility(uint8_t StOther) { return StOther & 3; }
245 
246 template <class ELFT>
247 Symbol *SymbolTable::addUndefined(StringRef Name, uint8_t Binding,
248                                   uint8_t StOther, uint8_t Type,
249                                   bool CanOmitFromDynSym, InputFile *File) {
250   Symbol *S;
251   bool WasInserted;
252   uint8_t Visibility = getVisibility(StOther);
253   std::tie(S, WasInserted) = insert(Name, Visibility, CanOmitFromDynSym, File);
254 
255   // An undefined symbol with non default visibility must be satisfied
256   // in the same DSO.
257   if (WasInserted || (isa<SharedSymbol>(S) && Visibility != STV_DEFAULT)) {
258     replaceSymbol<Undefined>(S, File, Name, Binding, StOther, Type);
259     return S;
260   }
261 
262   if (S->isShared() || S->isLazy() || (S->isUndefined() && Binding != STB_WEAK))
263     S->Binding = Binding;
264 
265   if (S->isLazy()) {
266     // An undefined weak will not fetch archive members. See comment on Lazy in
267     // Symbols.h for the details.
268     if (Binding == STB_WEAK) {
269       S->Type = Type;
270       return S;
271     }
272 
273     // Do extra check for --warn-backrefs.
274     //
275     // --warn-backrefs is an option to prevent an undefined reference from
276     // fetching an archive member written earlier in the command line. It can be
277     // used to keep compatibility with GNU linkers to some degree.
278     // I'll explain the feature and why you may find it useful in this comment.
279     //
280     // lld's symbol resolution semantics is more relaxed than traditional Unix
281     // linkers. For example,
282     //
283     //   ld.lld foo.a bar.o
284     //
285     // succeeds even if bar.o contains an undefined symbol that has to be
286     // resolved by some object file in foo.a. Traditional Unix linkers don't
287     // allow this kind of backward reference, as they visit each file only once
288     // from left to right in the command line while resolving all undefined
289     // symbols at the moment of visiting.
290     //
291     // In the above case, since there's no undefined symbol when a linker visits
292     // foo.a, no files are pulled out from foo.a, and because the linker forgets
293     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
294     // that could have been resolved otherwise.
295     //
296     // That lld accepts more relaxed form means that (besides it'd make more
297     // sense) you can accidentally write a command line or a build file that
298     // works only with lld, even if you have a plan to distribute it to wider
299     // users who may be using GNU linkers. With --warn-backrefs, you can detect
300     // a library order that doesn't work with other Unix linkers.
301     //
302     // The option is also useful to detect cyclic dependencies between static
303     // archives. Again, lld accepts
304     //
305     //   ld.lld foo.a bar.a
306     //
307     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
308     // handled as an error.
309     //
310     // Here is how the option works. We assign a group ID to each file. A file
311     // with a smaller group ID can pull out object files from an archive file
312     // with an equal or greater group ID. Otherwise, it is a reverse dependency
313     // and an error.
314     //
315     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
316     // files within the same --{start,end}-group get the same group ID. E.g.
317     //
318     //   ld.lld A B --start-group C D --end-group E
319     //
320     // A forms group 0. B form group 1. C and D (including their member object
321     // files) form group 2. E forms group 3. I think that you can see how this
322     // group assignment rule simulates the traditional linker's semantics.
323     bool Backref =
324         Config->WarnBackrefs && File && S->File->GroupId < File->GroupId;
325     fetchLazy<ELFT>(S);
326 
327     // We don't report backward references to weak symbols as they can be
328     // overridden later.
329     if (Backref && !S->isWeak())
330       warn("backward reference detected: " + Name + " in " + toString(File) +
331            " refers to " + toString(S->File));
332   }
333   return S;
334 }
335 
336 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
337 // foo@@VER. We want to effectively ignore foo, so give precedence to
338 // foo@@VER.
339 // FIXME: If users can transition to using
340 // .symver foo,foo@@@VER
341 // we can delete this hack.
342 static int compareVersion(Symbol *S, StringRef Name) {
343   bool A = Name.contains("@@");
344   bool B = S->getName().contains("@@");
345   if (A && !B)
346     return 1;
347   if (!A && B)
348     return -1;
349   return 0;
350 }
351 
352 // We have a new defined symbol with the specified binding. Return 1 if the new
353 // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are
354 // strong defined symbols.
355 static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding,
356                           StringRef Name) {
357   if (WasInserted)
358     return 1;
359   if (!S->isDefined())
360     return 1;
361   if (int R = compareVersion(S, Name))
362     return R;
363   if (Binding == STB_WEAK)
364     return -1;
365   if (S->isWeak())
366     return 1;
367   return 0;
368 }
369 
370 // We have a new non-common defined symbol with the specified binding. Return 1
371 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there
372 // is a conflict. If the new symbol wins, also update the binding.
373 static int compareDefinedNonCommon(Symbol *S, bool WasInserted, uint8_t Binding,
374                                    bool IsAbsolute, uint64_t Value,
375                                    StringRef Name) {
376   if (int Cmp = compareDefined(S, WasInserted, Binding, Name))
377     return Cmp;
378   if (auto *R = dyn_cast<Defined>(S)) {
379     if (R->Section && isa<BssSection>(R->Section)) {
380       // Non-common symbols take precedence over common symbols.
381       if (Config->WarnCommon)
382         warn("common " + S->getName() + " is overridden");
383       return 1;
384     }
385     if (R->Section == nullptr && Binding == STB_GLOBAL && IsAbsolute &&
386         R->Value == Value)
387       return -1;
388   }
389   return 0;
390 }
391 
392 Symbol *SymbolTable::addCommon(StringRef N, uint64_t Size, uint32_t Alignment,
393                                uint8_t Binding, uint8_t StOther, uint8_t Type,
394                                InputFile &File) {
395   Symbol *S;
396   bool WasInserted;
397   std::tie(S, WasInserted) = insert(N, getVisibility(StOther),
398                                     /*CanOmitFromDynSym*/ false, &File);
399 
400   int Cmp = compareDefined(S, WasInserted, Binding, N);
401   if (Cmp < 0)
402     return S;
403 
404   if (Cmp > 0) {
405     auto *Bss = make<BssSection>("COMMON", Size, Alignment);
406     Bss->File = &File;
407     Bss->Live = !Config->GcSections;
408     InputSections.push_back(Bss);
409 
410     replaceSymbol<Defined>(S, &File, N, Binding, StOther, Type, 0, Size, Bss);
411     return S;
412   }
413 
414   auto *D = cast<Defined>(S);
415   auto *Bss = dyn_cast_or_null<BssSection>(D->Section);
416   if (!Bss) {
417     // Non-common symbols take precedence over common symbols.
418     if (Config->WarnCommon)
419       warn("common " + S->getName() + " is overridden");
420     return S;
421   }
422 
423   if (Config->WarnCommon)
424     warn("multiple common of " + D->getName());
425 
426   Bss->Alignment = std::max(Bss->Alignment, Alignment);
427   if (Size > Bss->Size) {
428     D->File = Bss->File = &File;
429     D->Size = Bss->Size = Size;
430   }
431   return S;
432 }
433 
434 static void reportDuplicate(Symbol *Sym, InputFile *NewFile,
435                             InputSectionBase *ErrSec, uint64_t ErrOffset) {
436   if (Config->AllowMultipleDefinition)
437     return;
438 
439   Defined *D = cast<Defined>(Sym);
440   if (!D->Section || !ErrSec) {
441     error("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " +
442           toString(Sym->File) + "\n>>> defined in " + toString(NewFile));
443     return;
444   }
445 
446   // Construct and print an error message in the form of:
447   //
448   //   ld.lld: error: duplicate symbol: foo
449   //   >>> defined at bar.c:30
450   //   >>>            bar.o (/home/alice/src/bar.o)
451   //   >>> defined at baz.c:563
452   //   >>>            baz.o in archive libbaz.a
453   auto *Sec1 = cast<InputSectionBase>(D->Section);
454   std::string Src1 = Sec1->getSrcMsg(*Sym, D->Value);
455   std::string Obj1 = Sec1->getObjMsg(D->Value);
456   std::string Src2 = ErrSec->getSrcMsg(*Sym, ErrOffset);
457   std::string Obj2 = ErrSec->getObjMsg(ErrOffset);
458 
459   std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at ";
460   if (!Src1.empty())
461     Msg += Src1 + "\n>>>            ";
462   Msg += Obj1 + "\n>>> defined at ";
463   if (!Src2.empty())
464     Msg += Src2 + "\n>>>            ";
465   Msg += Obj2;
466   error(Msg);
467 }
468 
469 Defined *SymbolTable::addDefined(StringRef Name, uint8_t StOther, uint8_t Type,
470                                  uint64_t Value, uint64_t Size, uint8_t Binding,
471                                  SectionBase *Section, InputFile *File) {
472   Symbol *S;
473   bool WasInserted;
474   std::tie(S, WasInserted) = insert(Name, getVisibility(StOther),
475                                     /*CanOmitFromDynSym*/ false, File);
476   int Cmp = compareDefinedNonCommon(S, WasInserted, Binding, Section == nullptr,
477                                     Value, Name);
478   if (Cmp > 0)
479     replaceSymbol<Defined>(S, File, Name, Binding, StOther, Type, Value, Size,
480                            Section);
481   else if (Cmp == 0)
482     reportDuplicate(S, File, dyn_cast_or_null<InputSectionBase>(Section),
483                     Value);
484   return cast<Defined>(S);
485 }
486 
487 template <typename ELFT>
488 void SymbolTable::addShared(StringRef Name, SharedFile<ELFT> &File,
489                             const typename ELFT::Sym &Sym, uint32_t Alignment,
490                             uint32_t VerdefIndex) {
491   // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT
492   // as the visibility, which will leave the visibility in the symbol table
493   // unchanged.
494   Symbol *S;
495   bool WasInserted;
496   std::tie(S, WasInserted) = insert(Name, STV_DEFAULT,
497                                     /*CanOmitFromDynSym*/ true, &File);
498   // Make sure we preempt DSO symbols with default visibility.
499   if (Sym.getVisibility() == STV_DEFAULT)
500     S->ExportDynamic = true;
501 
502   // An undefined symbol with non default visibility must be satisfied
503   // in the same DSO.
504   auto Replace = [&](uint8_t Binding) {
505     replaceSymbol<SharedSymbol>(S, File, Name, Binding, Sym.st_other,
506                                 Sym.getType(), Sym.st_value, Sym.st_size,
507                                 Alignment, VerdefIndex);
508   };
509 
510   if (WasInserted)
511     Replace(Sym.getBinding());
512   else if (S->Visibility == STV_DEFAULT && (S->isUndefined() || S->isLazy()))
513     Replace(S->Binding);
514 }
515 
516 Symbol *SymbolTable::addBitcode(StringRef Name, uint8_t Binding,
517                                 uint8_t StOther, uint8_t Type,
518                                 bool CanOmitFromDynSym, BitcodeFile &F) {
519   Symbol *S;
520   bool WasInserted;
521   std::tie(S, WasInserted) =
522       insert(Name, getVisibility(StOther), CanOmitFromDynSym, &F);
523   int Cmp = compareDefinedNonCommon(S, WasInserted, Binding,
524                                     /*IsAbs*/ false, /*Value*/ 0, Name);
525   if (Cmp > 0)
526     replaceSymbol<Defined>(S, &F, Name, Binding, StOther, Type, 0, 0, nullptr);
527   else if (Cmp == 0)
528     reportDuplicate(S, &F, nullptr, 0);
529   return S;
530 }
531 
532 Symbol *SymbolTable::find(StringRef Name) {
533   auto It = SymMap.find(CachedHashStringRef(Name));
534   if (It == SymMap.end())
535     return nullptr;
536   if (It->second == -1)
537     return nullptr;
538   return SymVector[It->second];
539 }
540 
541 template <class ELFT>
542 void SymbolTable::addLazyArchive(StringRef Name, ArchiveFile &File,
543                                  const object::Archive::Symbol Sym) {
544   Symbol *S;
545   bool WasInserted;
546   std::tie(S, WasInserted) = insertName(Name);
547   if (WasInserted) {
548     replaceSymbol<LazyArchive>(S, File, STT_NOTYPE, Sym);
549     return;
550   }
551   if (!S->isUndefined())
552     return;
553 
554   // An undefined weak will not fetch archive members. See comment on Lazy in
555   // Symbols.h for the details.
556   if (S->isWeak()) {
557     replaceSymbol<LazyArchive>(S, File, S->Type, Sym);
558     S->Binding = STB_WEAK;
559     return;
560   }
561 
562   if (InputFile *F = File.fetch(Sym))
563     addFile<ELFT>(F);
564 }
565 
566 template <class ELFT>
567 void SymbolTable::addLazyObject(StringRef Name, LazyObjFile &File) {
568   Symbol *S;
569   bool WasInserted;
570   std::tie(S, WasInserted) = insertName(Name);
571   if (WasInserted) {
572     replaceSymbol<LazyObject>(S, File, STT_NOTYPE, Name);
573     return;
574   }
575   if (!S->isUndefined())
576     return;
577 
578   // An undefined weak will not fetch archive members. See comment on Lazy in
579   // Symbols.h for the details.
580   if (S->isWeak()) {
581     replaceSymbol<LazyObject>(S, File, S->Type, Name);
582     S->Binding = STB_WEAK;
583     return;
584   }
585 
586   if (InputFile *F = File.fetch())
587     addFile<ELFT>(F);
588 }
589 
590 template <class ELFT> void SymbolTable::fetchLazy(Symbol *Sym) {
591   if (auto *S = dyn_cast<LazyArchive>(Sym)) {
592     if (InputFile *File = S->fetch())
593       addFile<ELFT>(File);
594     return;
595   }
596 
597   auto *S = cast<LazyObject>(Sym);
598   if (InputFile *File = cast<LazyObjFile>(S->File)->fetch())
599     addFile<ELFT>(File);
600 }
601 
602 // Initialize DemangledSyms with a map from demangled symbols to symbol
603 // objects. Used to handle "extern C++" directive in version scripts.
604 //
605 // The map will contain all demangled symbols. That can be very large,
606 // and in LLD we generally want to avoid do anything for each symbol.
607 // Then, why are we doing this? Here's why.
608 //
609 // Users can use "extern C++ {}" directive to match against demangled
610 // C++ symbols. For example, you can write a pattern such as
611 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
612 // other than trying to match a pattern against all demangled symbols.
613 // So, if "extern C++" feature is used, we need to demangle all known
614 // symbols.
615 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() {
616   if (!DemangledSyms) {
617     DemangledSyms.emplace();
618     for (Symbol *Sym : SymVector) {
619       if (!Sym->isDefined())
620         continue;
621       if (Optional<std::string> S = demangleItanium(Sym->getName()))
622         (*DemangledSyms)[*S].push_back(Sym);
623       else
624         (*DemangledSyms)[Sym->getName()].push_back(Sym);
625     }
626   }
627   return *DemangledSyms;
628 }
629 
630 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion Ver) {
631   if (Ver.IsExternCpp)
632     return getDemangledSyms().lookup(Ver.Name);
633   if (Symbol *B = find(Ver.Name))
634     if (B->isDefined())
635       return {B};
636   return {};
637 }
638 
639 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion Ver) {
640   std::vector<Symbol *> Res;
641   StringMatcher M(Ver.Name);
642 
643   if (Ver.IsExternCpp) {
644     for (auto &P : getDemangledSyms())
645       if (M.match(P.first()))
646         Res.insert(Res.end(), P.second.begin(), P.second.end());
647     return Res;
648   }
649 
650   for (Symbol *Sym : SymVector)
651     if (Sym->isDefined() && M.match(Sym->getName()))
652       Res.push_back(Sym);
653   return Res;
654 }
655 
656 // If there's only one anonymous version definition in a version
657 // script file, the script does not actually define any symbol version,
658 // but just specifies symbols visibilities.
659 void SymbolTable::handleAnonymousVersion() {
660   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
661     assignExactVersion(Ver, VER_NDX_GLOBAL, "global");
662   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
663     assignWildcardVersion(Ver, VER_NDX_GLOBAL);
664   for (SymbolVersion &Ver : Config->VersionScriptLocals)
665     assignExactVersion(Ver, VER_NDX_LOCAL, "local");
666   for (SymbolVersion &Ver : Config->VersionScriptLocals)
667     assignWildcardVersion(Ver, VER_NDX_LOCAL);
668 }
669 
670 // Handles -dynamic-list.
671 void SymbolTable::handleDynamicList() {
672   for (SymbolVersion &Ver : Config->DynamicList) {
673     std::vector<Symbol *> Syms;
674     if (Ver.HasWildcard)
675       Syms = findAllByVersion(Ver);
676     else
677       Syms = findByVersion(Ver);
678 
679     for (Symbol *B : Syms) {
680       if (!Config->Shared)
681         B->ExportDynamic = true;
682       else if (B->includeInDynsym())
683         B->IsPreemptible = true;
684     }
685   }
686 }
687 
688 // Set symbol versions to symbols. This function handles patterns
689 // containing no wildcard characters.
690 void SymbolTable::assignExactVersion(SymbolVersion Ver, uint16_t VersionId,
691                                      StringRef VersionName) {
692   if (Ver.HasWildcard)
693     return;
694 
695   // Get a list of symbols which we need to assign the version to.
696   std::vector<Symbol *> Syms = findByVersion(Ver);
697   if (Syms.empty()) {
698     if (!Config->UndefinedVersion)
699       error("version script assignment of '" + VersionName + "' to symbol '" +
700             Ver.Name + "' failed: symbol not defined");
701     return;
702   }
703 
704   // Assign the version.
705   for (Symbol *Sym : Syms) {
706     // Skip symbols containing version info because symbol versions
707     // specified by symbol names take precedence over version scripts.
708     // See parseSymbolVersion().
709     if (Sym->getName().contains('@'))
710       continue;
711 
712     if (Sym->VersionId != Config->DefaultSymbolVersion &&
713         Sym->VersionId != VersionId)
714       error("duplicate symbol '" + Ver.Name + "' in version script");
715     Sym->VersionId = VersionId;
716   }
717 }
718 
719 void SymbolTable::assignWildcardVersion(SymbolVersion Ver, uint16_t VersionId) {
720   if (!Ver.HasWildcard)
721     return;
722 
723   // Exact matching takes precendence over fuzzy matching,
724   // so we set a version to a symbol only if no version has been assigned
725   // to the symbol. This behavior is compatible with GNU.
726   for (Symbol *B : findAllByVersion(Ver))
727     if (B->VersionId == Config->DefaultSymbolVersion)
728       B->VersionId = VersionId;
729 }
730 
731 // This function processes version scripts by updating VersionId
732 // member of symbols.
733 void SymbolTable::scanVersionScript() {
734   // Handle edge cases first.
735   handleAnonymousVersion();
736   handleDynamicList();
737 
738   // Now we have version definitions, so we need to set version ids to symbols.
739   // Each version definition has a glob pattern, and all symbols that match
740   // with the pattern get that version.
741 
742   // First, we assign versions to exact matching symbols,
743   // i.e. version definitions not containing any glob meta-characters.
744   for (VersionDefinition &V : Config->VersionDefinitions)
745     for (SymbolVersion &Ver : V.Globals)
746       assignExactVersion(Ver, V.Id, V.Name);
747 
748   // Next, we assign versions to fuzzy matching symbols,
749   // i.e. version definitions containing glob meta-characters.
750   // Note that because the last match takes precedence over previous matches,
751   // we iterate over the definitions in the reverse order.
752   for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions))
753     for (SymbolVersion &Ver : V.Globals)
754       assignWildcardVersion(Ver, V.Id);
755 
756   // Symbol themselves might know their versions because symbols
757   // can contain versions in the form of <name>@<version>.
758   // Let them parse and update their names to exclude version suffix.
759   for (Symbol *Sym : SymVector)
760     Sym->parseSymbolVersion();
761 }
762 
763 template void SymbolTable::addFile<ELF32LE>(InputFile *);
764 template void SymbolTable::addFile<ELF32BE>(InputFile *);
765 template void SymbolTable::addFile<ELF64LE>(InputFile *);
766 template void SymbolTable::addFile<ELF64BE>(InputFile *);
767 
768 template Symbol *SymbolTable::addUndefined<ELF32LE>(StringRef, uint8_t, uint8_t,
769                                                     uint8_t, bool, InputFile *);
770 template Symbol *SymbolTable::addUndefined<ELF32BE>(StringRef, uint8_t, uint8_t,
771                                                     uint8_t, bool, InputFile *);
772 template Symbol *SymbolTable::addUndefined<ELF64LE>(StringRef, uint8_t, uint8_t,
773                                                     uint8_t, bool, InputFile *);
774 template Symbol *SymbolTable::addUndefined<ELF64BE>(StringRef, uint8_t, uint8_t,
775                                                     uint8_t, bool, InputFile *);
776 
777 template void SymbolTable::addCombinedLTOObject<ELF32LE>();
778 template void SymbolTable::addCombinedLTOObject<ELF32BE>();
779 template void SymbolTable::addCombinedLTOObject<ELF64LE>();
780 template void SymbolTable::addCombinedLTOObject<ELF64BE>();
781 
782 template void
783 SymbolTable::addLazyArchive<ELF32LE>(StringRef, ArchiveFile &,
784                                      const object::Archive::Symbol);
785 template void
786 SymbolTable::addLazyArchive<ELF32BE>(StringRef, ArchiveFile &,
787                                      const object::Archive::Symbol);
788 template void
789 SymbolTable::addLazyArchive<ELF64LE>(StringRef, ArchiveFile &,
790                                      const object::Archive::Symbol);
791 template void
792 SymbolTable::addLazyArchive<ELF64BE>(StringRef, ArchiveFile &,
793                                      const object::Archive::Symbol);
794 
795 template void SymbolTable::addLazyObject<ELF32LE>(StringRef, LazyObjFile &);
796 template void SymbolTable::addLazyObject<ELF32BE>(StringRef, LazyObjFile &);
797 template void SymbolTable::addLazyObject<ELF64LE>(StringRef, LazyObjFile &);
798 template void SymbolTable::addLazyObject<ELF64BE>(StringRef, LazyObjFile &);
799 
800 template void SymbolTable::fetchLazy<ELF32LE>(Symbol *);
801 template void SymbolTable::fetchLazy<ELF32BE>(Symbol *);
802 template void SymbolTable::fetchLazy<ELF64LE>(Symbol *);
803 template void SymbolTable::fetchLazy<ELF64BE>(Symbol *);
804 
805 template void SymbolTable::addShared<ELF32LE>(StringRef, SharedFile<ELF32LE> &,
806                                               const typename ELF32LE::Sym &,
807                                               uint32_t Alignment, uint32_t);
808 template void SymbolTable::addShared<ELF32BE>(StringRef, SharedFile<ELF32BE> &,
809                                               const typename ELF32BE::Sym &,
810                                               uint32_t Alignment, uint32_t);
811 template void SymbolTable::addShared<ELF64LE>(StringRef, SharedFile<ELF64LE> &,
812                                               const typename ELF64LE::Sym &,
813                                               uint32_t Alignment, uint32_t);
814 template void SymbolTable::addShared<ELF64BE>(StringRef, SharedFile<ELF64BE> &,
815                                               const typename ELF64BE::Sym &,
816                                               uint32_t Alignment, uint32_t);
817