1 //===- SymbolTable.cpp ----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Symbol table is a bag of all known symbols. We put all symbols of
11 // all input files to the symbol table. The symbol table is basically
12 // a hash table with the logic to resolve symbol name conflicts using
13 // the symbol types.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "SymbolTable.h"
18 #include "Config.h"
19 #include "Error.h"
20 #include "LinkerScript.h"
21 #include "Memory.h"
22 #include "Symbols.h"
23 #include "llvm/ADT/STLExtras.h"
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace llvm::ELF;
28 
29 using namespace lld;
30 using namespace lld::elf;
31 
32 // All input object files must be for the same architecture
33 // (e.g. it does not make sense to link x86 object files with
34 // MIPS object files.) This function checks for that error.
35 template <class ELFT> static bool isCompatible(InputFile *F) {
36   if (!isa<ELFFileBase<ELFT>>(F) && !isa<BitcodeFile>(F))
37     return true;
38 
39   if (F->EKind == Config->EKind && F->EMachine == Config->EMachine) {
40     if (Config->EMachine != EM_MIPS)
41       return true;
42     if (isMipsN32Abi(F) == Config->MipsN32Abi)
43       return true;
44   }
45 
46   if (!Config->Emulation.empty())
47     error(toString(F) + " is incompatible with " + Config->Emulation);
48   else
49     error(toString(F) + " is incompatible with " + toString(Config->FirstElf));
50   return false;
51 }
52 
53 // Add symbols in File to the symbol table.
54 template <class ELFT> void SymbolTable<ELFT>::addFile(InputFile *File) {
55   if (!isCompatible<ELFT>(File))
56     return;
57 
58   // Binary file
59   if (auto *F = dyn_cast<BinaryFile>(File)) {
60     BinaryFiles.push_back(F);
61     F->parse<ELFT>();
62     return;
63   }
64 
65   // .a file
66   if (auto *F = dyn_cast<ArchiveFile>(File)) {
67     F->parse<ELFT>();
68     return;
69   }
70 
71   // Lazy object file
72   if (auto *F = dyn_cast<LazyObjectFile>(File)) {
73     F->parse<ELFT>();
74     return;
75   }
76 
77   if (Config->Trace)
78     outs() << toString(File) << "\n";
79 
80   // .so file
81   if (auto *F = dyn_cast<SharedFile<ELFT>>(File)) {
82     // DSOs are uniquified not by filename but by soname.
83     F->parseSoName();
84     if (ErrorCount || !SoNames.insert(F->getSoName()).second)
85       return;
86     SharedFiles.push_back(F);
87     F->parseRest();
88     return;
89   }
90 
91   // LLVM bitcode file
92   if (auto *F = dyn_cast<BitcodeFile>(File)) {
93     BitcodeFiles.push_back(F);
94     F->parse<ELFT>(ComdatGroups);
95     return;
96   }
97 
98   // Regular object file
99   auto *F = cast<ObjectFile<ELFT>>(File);
100   ObjectFiles.push_back(F);
101   F->parse(ComdatGroups);
102 }
103 
104 // This function is where all the optimizations of link-time
105 // optimization happens. When LTO is in use, some input files are
106 // not in native object file format but in the LLVM bitcode format.
107 // This function compiles bitcode files into a few big native files
108 // using LLVM functions and replaces bitcode symbols with the results.
109 // Because all bitcode files that consist of a program are passed
110 // to the compiler at once, it can do whole-program optimization.
111 template <class ELFT> void SymbolTable<ELFT>::addCombinedLTOObject() {
112   if (BitcodeFiles.empty())
113     return;
114 
115   // Compile bitcode files and replace bitcode symbols.
116   LTO.reset(new BitcodeCompiler);
117   for (BitcodeFile *F : BitcodeFiles)
118     LTO->add(*F);
119 
120   for (InputFile *File : LTO->compile()) {
121     ObjectFile<ELFT> *Obj = cast<ObjectFile<ELFT>>(File);
122     DenseSet<CachedHashStringRef> DummyGroups;
123     Obj->parse(DummyGroups);
124     ObjectFiles.push_back(Obj);
125   }
126 }
127 
128 template <class ELFT>
129 DefinedRegular<ELFT> *SymbolTable<ELFT>::addAbsolute(StringRef Name,
130                                                      uint8_t Visibility) {
131   Symbol *Sym = addRegular(Name, Visibility, STT_NOTYPE, 0, 0, STB_GLOBAL,
132                            nullptr, nullptr);
133   return cast<DefinedRegular<ELFT>>(Sym->body());
134 }
135 
136 // Add Name as an "ignored" symbol. An ignored symbol is a regular
137 // linker-synthesized defined symbol, but is only defined if needed.
138 template <class ELFT>
139 DefinedRegular<ELFT> *SymbolTable<ELFT>::addIgnored(StringRef Name,
140                                                     uint8_t Visibility) {
141   SymbolBody *S = find(Name);
142   if (!S || !S->isUndefined())
143     return nullptr;
144   return addAbsolute(Name, Visibility);
145 }
146 
147 // Set a flag for --trace-symbol so that we can print out a log message
148 // if a new symbol with the same name is inserted into the symbol table.
149 template <class ELFT> void SymbolTable<ELFT>::trace(StringRef Name) {
150   Symtab.insert({CachedHashStringRef(Name), {-1, true}});
151 }
152 
153 // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.
154 // Used to implement --wrap.
155 template <class ELFT> void SymbolTable<ELFT>::wrap(StringRef Name) {
156   SymbolBody *B = find(Name);
157   if (!B)
158     return;
159   Symbol *Sym = B->symbol();
160   Symbol *Real = addUndefined(Saver.save("__real_" + Name));
161   Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name));
162 
163   // We rename symbols by replacing the old symbol's SymbolBody with the new
164   // symbol's SymbolBody. This causes all SymbolBody pointers referring to the
165   // old symbol to instead refer to the new symbol.
166   memcpy(Real->Body.buffer, Sym->Body.buffer, sizeof(Sym->Body));
167   memcpy(Sym->Body.buffer, Wrap->Body.buffer, sizeof(Wrap->Body));
168 }
169 
170 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
171   if (VA == STV_DEFAULT)
172     return VB;
173   if (VB == STV_DEFAULT)
174     return VA;
175   return std::min(VA, VB);
176 }
177 
178 // Find an existing symbol or create and insert a new one.
179 template <class ELFT>
180 std::pair<Symbol *, bool> SymbolTable<ELFT>::insert(StringRef Name) {
181   auto P = Symtab.insert(
182       {CachedHashStringRef(Name), SymIndex((int)SymVector.size(), false)});
183   SymIndex &V = P.first->second;
184   bool IsNew = P.second;
185 
186   if (V.Idx == -1) {
187     IsNew = true;
188     V = SymIndex((int)SymVector.size(), true);
189   }
190 
191   Symbol *Sym;
192   if (IsNew) {
193     Sym = new (BAlloc) Symbol;
194     Sym->Binding = STB_WEAK;
195     Sym->Visibility = STV_DEFAULT;
196     Sym->IsUsedInRegularObj = false;
197     Sym->ExportDynamic = false;
198     Sym->Traced = V.Traced;
199     Sym->VersionId = Config->DefaultSymbolVersion;
200     SymVector.push_back(Sym);
201   } else {
202     Sym = SymVector[V.Idx];
203   }
204   return {Sym, IsNew};
205 }
206 
207 // Construct a string in the form of "Sym in File1 and File2".
208 // Used to construct an error message.
209 static std::string conflictMsg(SymbolBody *Existing, InputFile *NewFile) {
210   return "'" + toString(*Existing) + "' in " + toString(Existing->File) +
211          " and " + toString(NewFile);
212 }
213 
214 // Find an existing symbol or create and insert a new one, then apply the given
215 // attributes.
216 template <class ELFT>
217 std::pair<Symbol *, bool>
218 SymbolTable<ELFT>::insert(StringRef Name, uint8_t Type, uint8_t Visibility,
219                           bool CanOmitFromDynSym, InputFile *File) {
220   bool IsUsedInRegularObj = !File || File->kind() == InputFile::ObjectKind;
221   Symbol *S;
222   bool WasInserted;
223   std::tie(S, WasInserted) = insert(Name);
224 
225   // Merge in the new symbol's visibility.
226   S->Visibility = getMinVisibility(S->Visibility, Visibility);
227   if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic))
228     S->ExportDynamic = true;
229   if (IsUsedInRegularObj)
230     S->IsUsedInRegularObj = true;
231   if (!WasInserted && S->body()->Type != SymbolBody::UnknownType &&
232       ((Type == STT_TLS) != S->body()->isTls()))
233     error("TLS attribute mismatch for symbol " + conflictMsg(S->body(), File));
234 
235   return {S, WasInserted};
236 }
237 
238 template <class ELFT> Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name) {
239   return addUndefined(Name, STB_GLOBAL, STV_DEFAULT, /*Type*/ 0,
240                       /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
241 }
242 
243 template <class ELFT>
244 Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name, uint8_t Binding,
245                                         uint8_t StOther, uint8_t Type,
246                                         bool CanOmitFromDynSym,
247                                         InputFile *File) {
248   Symbol *S;
249   bool WasInserted;
250   std::tie(S, WasInserted) =
251       insert(Name, Type, StOther & 3, CanOmitFromDynSym, File);
252   if (WasInserted) {
253     S->Binding = Binding;
254     replaceBody<Undefined>(S, Name, StOther, Type, File);
255     return S;
256   }
257   if (Binding != STB_WEAK) {
258     if (S->body()->isShared() || S->body()->isLazy())
259       S->Binding = Binding;
260     if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(S->body()))
261       SS->file()->IsUsed = true;
262   }
263   if (auto *L = dyn_cast<Lazy>(S->body())) {
264     // An undefined weak will not fetch archive members, but we have to remember
265     // its type. See also comment in addLazyArchive.
266     if (S->isWeak())
267       L->Type = Type;
268     else if (InputFile *F = L->fetch())
269       addFile(F);
270   }
271   return S;
272 }
273 
274 // We have a new defined symbol with the specified binding. Return 1 if the new
275 // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are
276 // strong defined symbols.
277 static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding) {
278   if (WasInserted)
279     return 1;
280   SymbolBody *Body = S->body();
281   if (Body->isLazy() || Body->isUndefined() || Body->isShared())
282     return 1;
283   if (Binding == STB_WEAK)
284     return -1;
285   if (S->isWeak())
286     return 1;
287   return 0;
288 }
289 
290 // We have a new non-common defined symbol with the specified binding. Return 1
291 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there
292 // is a conflict. If the new symbol wins, also update the binding.
293 static int compareDefinedNonCommon(Symbol *S, bool WasInserted,
294                                    uint8_t Binding) {
295   if (int Cmp = compareDefined(S, WasInserted, Binding)) {
296     if (Cmp > 0)
297       S->Binding = Binding;
298     return Cmp;
299   }
300   if (isa<DefinedCommon>(S->body())) {
301     // Non-common symbols take precedence over common symbols.
302     if (Config->WarnCommon)
303       warn("common " + S->body()->getName() + " is overridden");
304     return 1;
305   }
306   return 0;
307 }
308 
309 template <class ELFT>
310 Symbol *SymbolTable<ELFT>::addCommon(StringRef N, uint64_t Size,
311                                      uint64_t Alignment, uint8_t Binding,
312                                      uint8_t StOther, uint8_t Type,
313                                      InputFile *File) {
314   Symbol *S;
315   bool WasInserted;
316   std::tie(S, WasInserted) =
317       insert(N, Type, StOther & 3, /*CanOmitFromDynSym*/ false, File);
318   int Cmp = compareDefined(S, WasInserted, Binding);
319   if (Cmp > 0) {
320     S->Binding = Binding;
321     replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
322   } else if (Cmp == 0) {
323     auto *C = dyn_cast<DefinedCommon>(S->body());
324     if (!C) {
325       // Non-common symbols take precedence over common symbols.
326       if (Config->WarnCommon)
327         warn("common " + S->body()->getName() + " is overridden");
328       return S;
329     }
330 
331     if (Config->WarnCommon)
332       warn("multiple common of " + S->body()->getName());
333 
334     Alignment = C->Alignment = std::max(C->Alignment, Alignment);
335     if (Size > C->Size)
336       replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
337   }
338   return S;
339 }
340 
341 static void print(const Twine &Msg) {
342   if (Config->AllowMultipleDefinition)
343     warn(Msg);
344   else
345     error(Msg);
346 }
347 
348 static void reportDuplicate(SymbolBody *Existing, InputFile *NewFile) {
349   print("duplicate symbol " + conflictMsg(Existing, NewFile));
350 }
351 
352 template <class ELFT>
353 static void reportDuplicate(SymbolBody *Existing,
354                             InputSectionBase<ELFT> *ErrSec,
355                             typename ELFT::uint ErrOffset) {
356   DefinedRegular<ELFT> *D = dyn_cast<DefinedRegular<ELFT>>(Existing);
357   if (!D || !D->Section || !ErrSec) {
358     reportDuplicate(Existing, ErrSec ? ErrSec->getFile() : nullptr);
359     return;
360   }
361 
362   std::string OldLoc = D->Section->getLocation(D->Value);
363   std::string NewLoc = ErrSec->getLocation(ErrOffset);
364 
365   print(NewLoc + ": duplicate symbol '" + toString(*Existing) + "'");
366   print(OldLoc + ": previous definition was here");
367 }
368 
369 template <typename ELFT>
370 Symbol *SymbolTable<ELFT>::addRegular(StringRef Name, uint8_t StOther,
371                                       uint8_t Type, uintX_t Value, uintX_t Size,
372                                       uint8_t Binding,
373                                       InputSectionBase<ELFT> *Section,
374                                       InputFile *File) {
375   Symbol *S;
376   bool WasInserted;
377   std::tie(S, WasInserted) = insert(Name, Type, StOther & 3,
378                                     /*CanOmitFromDynSym*/ false, File);
379   int Cmp = compareDefinedNonCommon(S, WasInserted, Binding);
380   if (Cmp > 0)
381     replaceBody<DefinedRegular<ELFT>>(S, Name, StOther, Type, Value, Size,
382                                       Section, File);
383   else if (Cmp == 0)
384     reportDuplicate(S->body(), Section, Value);
385   return S;
386 }
387 
388 template <typename ELFT>
389 Symbol *SymbolTable<ELFT>::addSynthetic(StringRef N,
390                                         const OutputSectionBase *Section,
391                                         uintX_t Value, uint8_t StOther) {
392   Symbol *S;
393   bool WasInserted;
394   std::tie(S, WasInserted) = insert(N, STT_NOTYPE, /*Visibility*/ StOther & 0x3,
395                                     /*CanOmitFromDynSym*/ false, nullptr);
396   int Cmp = compareDefinedNonCommon(S, WasInserted, STB_GLOBAL);
397   if (Cmp > 0)
398     replaceBody<DefinedSynthetic<ELFT>>(S, N, Value, Section);
399   else if (Cmp == 0)
400     reportDuplicate(S->body(), nullptr);
401   return S;
402 }
403 
404 template <typename ELFT>
405 void SymbolTable<ELFT>::addShared(SharedFile<ELFT> *F, StringRef Name,
406                                   const Elf_Sym &Sym,
407                                   const typename ELFT::Verdef *Verdef) {
408   // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT
409   // as the visibility, which will leave the visibility in the symbol table
410   // unchanged.
411   Symbol *S;
412   bool WasInserted;
413   std::tie(S, WasInserted) =
414       insert(Name, Sym.getType(), STV_DEFAULT, /*CanOmitFromDynSym*/ true, F);
415   // Make sure we preempt DSO symbols with default visibility.
416   if (Sym.getVisibility() == STV_DEFAULT)
417     S->ExportDynamic = true;
418   if (WasInserted || isa<Undefined>(S->body())) {
419     replaceBody<SharedSymbol<ELFT>>(S, F, Name, Sym, Verdef);
420     if (!S->isWeak())
421       F->IsUsed = true;
422   }
423 }
424 
425 template <class ELFT>
426 Symbol *SymbolTable<ELFT>::addBitcode(StringRef Name, uint8_t Binding,
427                                       uint8_t StOther, uint8_t Type,
428                                       bool CanOmitFromDynSym, BitcodeFile *F) {
429   Symbol *S;
430   bool WasInserted;
431   std::tie(S, WasInserted) =
432       insert(Name, Type, StOther & 3, CanOmitFromDynSym, F);
433   int Cmp = compareDefinedNonCommon(S, WasInserted, Binding);
434   if (Cmp > 0)
435     replaceBody<DefinedRegular<ELFT>>(S, Name, StOther, Type, 0, 0, nullptr, F);
436   else if (Cmp == 0)
437     reportDuplicate(S->body(), F);
438   return S;
439 }
440 
441 template <class ELFT> SymbolBody *SymbolTable<ELFT>::find(StringRef Name) {
442   auto It = Symtab.find(CachedHashStringRef(Name));
443   if (It == Symtab.end())
444     return nullptr;
445   SymIndex V = It->second;
446   if (V.Idx == -1)
447     return nullptr;
448   return SymVector[V.Idx]->body();
449 }
450 
451 // Returns a list of defined symbols that match with a given pattern.
452 template <class ELFT>
453 std::vector<SymbolBody *> SymbolTable<ELFT>::findAll(StringRef GlobPat) {
454   std::vector<SymbolBody *> Res;
455   StringMatcher M({GlobPat});
456   for (Symbol *Sym : SymVector) {
457     SymbolBody *B = Sym->body();
458     StringRef Name = B->getName();
459     if (!B->isUndefined() && M.match(Name))
460       Res.push_back(B);
461   }
462   return Res;
463 }
464 
465 template <class ELFT>
466 void SymbolTable<ELFT>::addLazyArchive(ArchiveFile *F,
467                                        const object::Archive::Symbol Sym) {
468   Symbol *S;
469   bool WasInserted;
470   StringRef Name = Sym.getName();
471   std::tie(S, WasInserted) = insert(Name);
472   if (WasInserted) {
473     replaceBody<LazyArchive>(S, *F, Sym, SymbolBody::UnknownType);
474     return;
475   }
476   if (!S->body()->isUndefined())
477     return;
478 
479   // Weak undefined symbols should not fetch members from archives. If we were
480   // to keep old symbol we would not know that an archive member was available
481   // if a strong undefined symbol shows up afterwards in the link. If a strong
482   // undefined symbol never shows up, this lazy symbol will get to the end of
483   // the link and must be treated as the weak undefined one. We already marked
484   // this symbol as used when we added it to the symbol table, but we also need
485   // to preserve its type. FIXME: Move the Type field to Symbol.
486   if (S->isWeak()) {
487     replaceBody<LazyArchive>(S, *F, Sym, S->body()->Type);
488     return;
489   }
490   std::pair<MemoryBufferRef, uint64_t> MBInfo = F->getMember(&Sym);
491   if (!MBInfo.first.getBuffer().empty())
492     addFile(createObjectFile(MBInfo.first, F->getName(), MBInfo.second));
493 }
494 
495 template <class ELFT>
496 void SymbolTable<ELFT>::addLazyObject(StringRef Name, LazyObjectFile &Obj) {
497   Symbol *S;
498   bool WasInserted;
499   std::tie(S, WasInserted) = insert(Name);
500   if (WasInserted) {
501     replaceBody<LazyObject>(S, Name, Obj, SymbolBody::UnknownType);
502     return;
503   }
504   if (!S->body()->isUndefined())
505     return;
506 
507   // See comment for addLazyArchive above.
508   if (S->isWeak()) {
509     replaceBody<LazyObject>(S, Name, Obj, S->body()->Type);
510   } else {
511     MemoryBufferRef MBRef = Obj.getBuffer();
512     if (!MBRef.getBuffer().empty())
513       addFile(createObjectFile(MBRef));
514   }
515 }
516 
517 // Process undefined (-u) flags by loading lazy symbols named by those flags.
518 template <class ELFT> void SymbolTable<ELFT>::scanUndefinedFlags() {
519   for (StringRef S : Config->Undefined)
520     if (auto *L = dyn_cast_or_null<Lazy>(find(S)))
521       if (InputFile *File = L->fetch())
522         addFile(File);
523 }
524 
525 // This function takes care of the case in which shared libraries depend on
526 // the user program (not the other way, which is usual). Shared libraries
527 // may have undefined symbols, expecting that the user program provides
528 // the definitions for them. An example is BSD's __progname symbol.
529 // We need to put such symbols to the main program's .dynsym so that
530 // shared libraries can find them.
531 // Except this, we ignore undefined symbols in DSOs.
532 template <class ELFT> void SymbolTable<ELFT>::scanShlibUndefined() {
533   for (SharedFile<ELFT> *File : SharedFiles)
534     for (StringRef U : File->getUndefinedSymbols())
535       if (SymbolBody *Sym = find(U))
536         if (Sym->isDefined())
537           Sym->symbol()->ExportDynamic = true;
538 }
539 
540 // This function processes --export-dynamic-symbol and --dynamic-list.
541 template <class ELFT> void SymbolTable<ELFT>::scanDynamicList() {
542   for (StringRef S : Config->DynamicList)
543     if (SymbolBody *B = find(S))
544       B->symbol()->ExportDynamic = true;
545 }
546 
547 // Initialize DemangledSyms with a map from demangled symbols to symbol
548 // objects. Used to handle "extern C++" directive in version scripts.
549 //
550 // The map will contain all demangled symbols. That can be very large,
551 // and in LLD we generally want to avoid do anything for each symbol.
552 // Then, why are we doing this? Here's why.
553 //
554 // Users can use "extern C++ {}" directive to match against demangled
555 // C++ symbols. For example, you can write a pattern such as
556 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
557 // other than trying to match a pattern against all demangled symbols.
558 // So, if "extern C++" feature is used, we need to demangle all known
559 // symbols.
560 template <class ELFT>
561 void SymbolTable<ELFT>::initDemangledSyms() {
562   if (DemangledSyms)
563     return;
564   DemangledSyms.emplace();
565 
566   for (Symbol *Sym : SymVector) {
567     SymbolBody *B = Sym->body();
568     (*DemangledSyms)[demangle(B->getName())].push_back(B);
569   }
570 }
571 
572 template <class ELFT>
573 ArrayRef<SymbolBody *> SymbolTable<ELFT>::findDemangled(StringRef Name) {
574   initDemangledSyms();
575   auto I = DemangledSyms->find(Name);
576   if (I != DemangledSyms->end())
577     return I->second;
578   return {};
579 }
580 
581 template <class ELFT>
582 std::vector<SymbolBody *>
583 SymbolTable<ELFT>::findAllDemangled(StringRef GlobPat) {
584   initDemangledSyms();
585   std::vector<SymbolBody *> Res;
586   StringMatcher M({GlobPat});
587   for (auto &P : *DemangledSyms)
588     if (M.match(P.first()))
589       for (SymbolBody *Body : P.second)
590         if (!Body->isUndefined())
591           Res.push_back(Body);
592   return Res;
593 }
594 
595 // If there's only one anonymous version definition in a version
596 // script file, the script does not actually define any symbol version,
597 // but just specifies symbols visibilities. We assume that the script was
598 // in the form of { global: foo; bar; local *; }. So, local is default.
599 // In this function, we make specified symbols global.
600 template <class ELFT> void SymbolTable<ELFT>::handleAnonymousVersion() {
601   for (SymbolVersion &Ver : Config->VersionScriptGlobals) {
602     if (hasWildcard(Ver.Name)) {
603       for (SymbolBody *B : findAll(Ver.Name))
604         B->symbol()->VersionId = VER_NDX_GLOBAL;
605       continue;
606     }
607     if (SymbolBody *B = find(Ver.Name))
608       B->symbol()->VersionId = VER_NDX_GLOBAL;
609   }
610 }
611 
612 // Set symbol versions to symbols. This function handles patterns
613 // containing no wildcard characters.
614 template <class ELFT>
615 void SymbolTable<ELFT>::assignExactVersion(SymbolVersion Ver, uint16_t VersionId,
616                                            StringRef VersionName) {
617   if (Ver.HasWildcard)
618     return;
619 
620   // Get a list of symbols which we need to assign the version to.
621   std::vector<SymbolBody *> Syms;
622   if (Ver.IsExternCpp)
623     Syms = findDemangled(Ver.Name);
624   else
625     Syms.push_back(find(Ver.Name));
626 
627   // Assign the version.
628   for (SymbolBody *B : Syms) {
629     if (!B || B->isUndefined()) {
630       if (Config->NoUndefinedVersion)
631         error("version script assignment of '" + VersionName + "' to symbol '" +
632               Ver.Name + "' failed: symbol not defined");
633       continue;
634     }
635 
636     if (B->symbol()->VersionId != Config->DefaultSymbolVersion)
637       warn("duplicate symbol '" + Ver.Name + "' in version script");
638     B->symbol()->VersionId = VersionId;
639   }
640 }
641 
642 template <class ELFT>
643 void SymbolTable<ELFT>::assignWildcardVersion(SymbolVersion Ver,
644                                               uint16_t VersionId) {
645   if (!Ver.HasWildcard)
646     return;
647   std::vector<SymbolBody *> Syms =
648       Ver.IsExternCpp ? findAllDemangled(Ver.Name) : findAll(Ver.Name);
649 
650   // Exact matching takes precendence over fuzzy matching,
651   // so we set a version to a symbol only if no version has been assigned
652   // to the symbol. This behavior is compatible with GNU.
653   for (SymbolBody *B : Syms)
654     if (B->symbol()->VersionId == Config->DefaultSymbolVersion)
655       B->symbol()->VersionId = VersionId;
656 }
657 
658 // This function processes version scripts by updating VersionId
659 // member of symbols.
660 template <class ELFT> void SymbolTable<ELFT>::scanVersionScript() {
661   // Symbol themselves might know their versions because symbols
662   // can contain versions in the form of <name>@<version>.
663   // Let them parse their names.
664   if (!Config->VersionDefinitions.empty())
665     for (Symbol *Sym : SymVector)
666       Sym->body()->parseSymbolVersion();
667 
668   // Handle edge cases first.
669   if (!Config->VersionScriptGlobals.empty()) {
670     handleAnonymousVersion();
671     return;
672   }
673 
674   if (Config->VersionDefinitions.empty())
675     return;
676 
677   // Now we have version definitions, so we need to set version ids to symbols.
678   // Each version definition has a glob pattern, and all symbols that match
679   // with the pattern get that version.
680 
681   // First, we assign versions to exact matching symbols,
682   // i.e. version definitions not containing any glob meta-characters.
683   for (SymbolVersion &Ver : Config->VersionScriptLocals)
684     assignExactVersion(Ver, VER_NDX_LOCAL, "local");
685   for (VersionDefinition &V : Config->VersionDefinitions)
686     for (SymbolVersion &Ver : V.Globals)
687       assignExactVersion(Ver, V.Id, V.Name);
688 
689   // Next, we assign versions to fuzzy matching symbols,
690   // i.e. version definitions containing glob meta-characters.
691   // Note that because the last match takes precedence over previous matches,
692   // we iterate over the definitions in the reverse order.
693   for (SymbolVersion &Ver : Config->VersionScriptLocals)
694     assignWildcardVersion(Ver, VER_NDX_LOCAL);
695   for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions))
696     for (SymbolVersion &Ver : V.Globals)
697       assignWildcardVersion(Ver, V.Id);
698 }
699 
700 template class elf::SymbolTable<ELF32LE>;
701 template class elf::SymbolTable<ELF32BE>;
702 template class elf::SymbolTable<ELF64LE>;
703 template class elf::SymbolTable<ELF64BE>;
704