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     message(toString(File));
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 *SymbolTable<ELFT>::addAbsolute(StringRef Name,
130                                                uint8_t Visibility,
131                                                uint8_t Binding) {
132   Symbol *Sym =
133       addRegular(Name, Visibility, STT_NOTYPE, 0, 0, Binding, nullptr, nullptr);
134   return cast<DefinedRegular>(Sym->body());
135 }
136 
137 // Add Name as an "ignored" symbol. An ignored symbol is a regular
138 // linker-synthesized defined symbol, but is only defined if needed.
139 template <class ELFT>
140 DefinedRegular *SymbolTable<ELFT>::addIgnored(StringRef Name,
141                                               uint8_t Visibility) {
142   SymbolBody *S = find(Name);
143   if (!S || S->isInCurrentDSO())
144     return nullptr;
145   return addAbsolute(Name, Visibility);
146 }
147 
148 // Set a flag for --trace-symbol so that we can print out a log message
149 // if a new symbol with the same name is inserted into the symbol table.
150 template <class ELFT> void SymbolTable<ELFT>::trace(StringRef Name) {
151   Symtab.insert({CachedHashStringRef(Name), {-1, true}});
152 }
153 
154 // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.
155 // Used to implement --wrap.
156 template <class ELFT> void SymbolTable<ELFT>::wrap(StringRef Name) {
157   SymbolBody *B = find(Name);
158   if (!B)
159     return;
160   Symbol *Sym = B->symbol();
161   Symbol *Real = addUndefined(Saver.save("__real_" + Name));
162   Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name));
163 
164   // We rename symbols by replacing the old symbol's SymbolBody with the new
165   // symbol's SymbolBody. This causes all SymbolBody pointers referring to the
166   // old symbol to instead refer to the new symbol.
167   memcpy(Real->Body.buffer, Sym->Body.buffer, sizeof(Sym->Body));
168   memcpy(Sym->Body.buffer, Wrap->Body.buffer, sizeof(Wrap->Body));
169 }
170 
171 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
172   if (VA == STV_DEFAULT)
173     return VB;
174   if (VB == STV_DEFAULT)
175     return VA;
176   return std::min(VA, VB);
177 }
178 
179 // Find an existing symbol or create and insert a new one.
180 template <class ELFT>
181 std::pair<Symbol *, bool> SymbolTable<ELFT>::insert(StringRef Name) {
182   auto P = Symtab.insert(
183       {CachedHashStringRef(Name), SymIndex((int)SymVector.size(), false)});
184   SymIndex &V = P.first->second;
185   bool IsNew = P.second;
186 
187   if (V.Idx == -1) {
188     IsNew = true;
189     V = SymIndex((int)SymVector.size(), true);
190   }
191 
192   Symbol *Sym;
193   if (IsNew) {
194     Sym = make<Symbol>();
195     Sym->InVersionScript = false;
196     Sym->Binding = STB_WEAK;
197     Sym->Visibility = STV_DEFAULT;
198     Sym->IsUsedInRegularObj = false;
199     Sym->ExportDynamic = false;
200     Sym->Traced = V.Traced;
201     Sym->VersionId = Config->DefaultSymbolVersion;
202     SymVector.push_back(Sym);
203   } else {
204     Sym = SymVector[V.Idx];
205   }
206   return {Sym, IsNew};
207 }
208 
209 // Construct a string in the form of "Sym in File1 and File2".
210 // Used to construct an error message.
211 static std::string conflictMsg(SymbolBody *Existing, InputFile *NewFile) {
212   return "'" + toString(*Existing) + "' in " + toString(Existing->File) +
213          " and " + toString(NewFile);
214 }
215 
216 // Find an existing symbol or create and insert a new one, then apply the given
217 // attributes.
218 template <class ELFT>
219 std::pair<Symbol *, bool>
220 SymbolTable<ELFT>::insert(StringRef Name, uint8_t Type, uint8_t Visibility,
221                           bool CanOmitFromDynSym, InputFile *File) {
222   bool IsUsedInRegularObj = !File || File->kind() == InputFile::ObjectKind;
223   Symbol *S;
224   bool WasInserted;
225   std::tie(S, WasInserted) = insert(Name);
226 
227   // Merge in the new symbol's visibility.
228   S->Visibility = getMinVisibility(S->Visibility, Visibility);
229   if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic))
230     S->ExportDynamic = true;
231   if (IsUsedInRegularObj)
232     S->IsUsedInRegularObj = true;
233   if (!WasInserted && S->body()->Type != SymbolBody::UnknownType &&
234       ((Type == STT_TLS) != S->body()->isTls()))
235     error("TLS attribute mismatch for symbol " + conflictMsg(S->body(), File));
236 
237   return {S, WasInserted};
238 }
239 
240 template <class ELFT> Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name) {
241   return addUndefined(Name, /*IsLocal=*/false, STB_GLOBAL, STV_DEFAULT,
242                       /*Type*/ 0,
243                       /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
244 }
245 
246 static uint8_t getVisibility(uint8_t StOther) { return StOther & 3; }
247 
248 template <class ELFT>
249 Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name, bool IsLocal,
250                                         uint8_t Binding, uint8_t StOther,
251                                         uint8_t Type, bool CanOmitFromDynSym,
252                                         InputFile *File) {
253   Symbol *S;
254   bool WasInserted;
255   std::tie(S, WasInserted) =
256       insert(Name, Type, getVisibility(StOther), CanOmitFromDynSym, File);
257   if (WasInserted) {
258     S->Binding = Binding;
259     replaceBody<Undefined>(S, Name, IsLocal, StOther, Type, File);
260     return S;
261   }
262   if (Binding != STB_WEAK) {
263     if (S->body()->isShared() || S->body()->isLazy())
264       S->Binding = Binding;
265     if (auto *SS = dyn_cast<SharedSymbol>(S->body()))
266       cast<SharedFile<ELFT>>(SS->File)->IsUsed = true;
267   }
268   if (auto *L = dyn_cast<Lazy>(S->body())) {
269     // An undefined weak will not fetch archive members, but we have to remember
270     // its type. See also comment in addLazyArchive.
271     if (S->isWeak())
272       L->Type = Type;
273     else if (InputFile *F = L->fetch())
274       addFile(F);
275   }
276   return S;
277 }
278 
279 // We have a new defined symbol with the specified binding. Return 1 if the new
280 // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are
281 // strong defined symbols.
282 static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding) {
283   if (WasInserted)
284     return 1;
285   SymbolBody *Body = S->body();
286   if (Body->isLazy() || !Body->isInCurrentDSO())
287     return 1;
288   if (Binding == STB_WEAK)
289     return -1;
290   if (S->isWeak())
291     return 1;
292   return 0;
293 }
294 
295 // We have a new non-common defined symbol with the specified binding. Return 1
296 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there
297 // is a conflict. If the new symbol wins, also update the binding.
298 template <typename ELFT>
299 static int compareDefinedNonCommon(Symbol *S, bool WasInserted, uint8_t Binding,
300                                    bool IsAbsolute, typename ELFT::uint Value) {
301   if (int Cmp = compareDefined(S, WasInserted, Binding)) {
302     if (Cmp > 0)
303       S->Binding = Binding;
304     return Cmp;
305   }
306   SymbolBody *B = S->body();
307   if (isa<DefinedCommon>(B)) {
308     // Non-common symbols take precedence over common symbols.
309     if (Config->WarnCommon)
310       warn("common " + S->body()->getName() + " is overridden");
311     return 1;
312   } else if (auto *R = dyn_cast<DefinedRegular>(B)) {
313     if (R->Section == nullptr && Binding == STB_GLOBAL && IsAbsolute &&
314         R->Value == Value)
315       return -1;
316   }
317   return 0;
318 }
319 
320 template <class ELFT>
321 Symbol *SymbolTable<ELFT>::addCommon(StringRef N, uint64_t Size,
322                                      uint32_t Alignment, uint8_t Binding,
323                                      uint8_t StOther, uint8_t Type,
324                                      InputFile *File) {
325   Symbol *S;
326   bool WasInserted;
327   std::tie(S, WasInserted) = insert(N, Type, getVisibility(StOther),
328                                     /*CanOmitFromDynSym*/ false, File);
329   int Cmp = compareDefined(S, WasInserted, Binding);
330   if (Cmp > 0) {
331     S->Binding = Binding;
332     replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
333   } else if (Cmp == 0) {
334     auto *C = dyn_cast<DefinedCommon>(S->body());
335     if (!C) {
336       // Non-common symbols take precedence over common symbols.
337       if (Config->WarnCommon)
338         warn("common " + S->body()->getName() + " is overridden");
339       return S;
340     }
341 
342     if (Config->WarnCommon)
343       warn("multiple common of " + S->body()->getName());
344 
345     Alignment = C->Alignment = std::max(C->Alignment, Alignment);
346     if (Size > C->Size)
347       replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
348   }
349   return S;
350 }
351 
352 static void print(const Twine &Msg) {
353   if (Config->AllowMultipleDefinition)
354     warn(Msg);
355   else
356     error(Msg);
357 }
358 
359 static void reportDuplicate(SymbolBody *Existing, InputFile *NewFile) {
360   print("duplicate symbol " + conflictMsg(Existing, NewFile));
361 }
362 
363 template <class ELFT>
364 static void reportDuplicate(SymbolBody *Existing, InputSectionBase *ErrSec,
365                             typename ELFT::uint ErrOffset) {
366   DefinedRegular *D = dyn_cast<DefinedRegular>(Existing);
367   if (!D || !D->Section || !ErrSec) {
368     reportDuplicate(Existing, ErrSec ? ErrSec->getFile<ELFT>() : nullptr);
369     return;
370   }
371 
372   std::string OldLoc =
373       cast<InputSectionBase>(D->Section)->template getLocation<ELFT>(D->Value);
374   std::string NewLoc = ErrSec->getLocation<ELFT>(ErrOffset);
375 
376   print(NewLoc + ": duplicate symbol '" + toString(*Existing) + "'");
377   print(OldLoc + ": previous definition was here");
378 }
379 
380 template <typename ELFT>
381 Symbol *SymbolTable<ELFT>::addRegular(StringRef Name, uint8_t StOther,
382                                       uint8_t Type, uint64_t Value,
383                                       uint64_t Size, uint8_t Binding,
384                                       SectionBase *Section, InputFile *File) {
385   Symbol *S;
386   bool WasInserted;
387   std::tie(S, WasInserted) = insert(Name, Type, getVisibility(StOther),
388                                     /*CanOmitFromDynSym*/ false, File);
389   int Cmp = compareDefinedNonCommon<ELFT>(S, WasInserted, Binding,
390                                           Section == nullptr, Value);
391   if (Cmp > 0)
392     replaceBody<DefinedRegular>(S, Name, /*IsLocal=*/false, StOther, Type,
393                                 Value, Size, Section, File);
394   else if (Cmp == 0)
395     reportDuplicate<ELFT>(S->body(),
396                           dyn_cast_or_null<InputSectionBase>(Section), Value);
397   return S;
398 }
399 
400 template <typename ELFT>
401 void SymbolTable<ELFT>::addShared(SharedFile<ELFT> *File, StringRef Name,
402                                   const Elf_Sym &Sym,
403                                   const typename ELFT::Verdef *Verdef) {
404   // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT
405   // as the visibility, which will leave the visibility in the symbol table
406   // unchanged.
407   Symbol *S;
408   bool WasInserted;
409   std::tie(S, WasInserted) = insert(Name, Sym.getType(), STV_DEFAULT,
410                                     /*CanOmitFromDynSym*/ true, File);
411   // Make sure we preempt DSO symbols with default visibility.
412   if (Sym.getVisibility() == STV_DEFAULT)
413     S->ExportDynamic = true;
414 
415   if (WasInserted || isa<Undefined>(S->body())) {
416     replaceBody<SharedSymbol>(S, File, Name, Sym.st_other, Sym.getType(), &Sym,
417                               Verdef);
418     if (!S->isWeak())
419       File->IsUsed = true;
420   }
421 }
422 
423 template <class ELFT>
424 Symbol *SymbolTable<ELFT>::addBitcode(StringRef Name, uint8_t Binding,
425                                       uint8_t StOther, uint8_t Type,
426                                       bool CanOmitFromDynSym, BitcodeFile *F) {
427   Symbol *S;
428   bool WasInserted;
429   std::tie(S, WasInserted) =
430       insert(Name, Type, getVisibility(StOther), CanOmitFromDynSym, F);
431   int Cmp = compareDefinedNonCommon<ELFT>(S, WasInserted, Binding,
432                                           /*IsAbs*/ false, /*Value*/ 0);
433   if (Cmp > 0)
434     replaceBody<DefinedRegular>(S, Name, /*IsLocal=*/false, StOther, Type, 0, 0,
435                                 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 template <class ELFT>
452 SymbolBody *SymbolTable<ELFT>::findInCurrentDSO(StringRef Name) {
453   if (SymbolBody *S = find(Name))
454     if (S->isInCurrentDSO())
455       return S;
456   return nullptr;
457 }
458 
459 template <class ELFT>
460 void SymbolTable<ELFT>::addLazyArchive(ArchiveFile *F,
461                                        const object::Archive::Symbol Sym) {
462   Symbol *S;
463   bool WasInserted;
464   StringRef Name = Sym.getName();
465   std::tie(S, WasInserted) = insert(Name);
466   if (WasInserted) {
467     replaceBody<LazyArchive>(S, *F, Sym, SymbolBody::UnknownType);
468     return;
469   }
470   if (!S->body()->isUndefined())
471     return;
472 
473   // Weak undefined symbols should not fetch members from archives. If we were
474   // to keep old symbol we would not know that an archive member was available
475   // if a strong undefined symbol shows up afterwards in the link. If a strong
476   // undefined symbol never shows up, this lazy symbol will get to the end of
477   // the link and must be treated as the weak undefined one. We already marked
478   // this symbol as used when we added it to the symbol table, but we also need
479   // to preserve its type. FIXME: Move the Type field to Symbol.
480   if (S->isWeak()) {
481     replaceBody<LazyArchive>(S, *F, Sym, S->body()->Type);
482     return;
483   }
484   std::pair<MemoryBufferRef, uint64_t> MBInfo = F->getMember(&Sym);
485   if (!MBInfo.first.getBuffer().empty())
486     addFile(createObjectFile(MBInfo.first, F->getName(), MBInfo.second));
487 }
488 
489 template <class ELFT>
490 void SymbolTable<ELFT>::addLazyObject(StringRef Name, LazyObjectFile &Obj) {
491   Symbol *S;
492   bool WasInserted;
493   std::tie(S, WasInserted) = insert(Name);
494   if (WasInserted) {
495     replaceBody<LazyObject>(S, Name, Obj, SymbolBody::UnknownType);
496     return;
497   }
498   if (!S->body()->isUndefined())
499     return;
500 
501   // See comment for addLazyArchive above.
502   if (S->isWeak()) {
503     replaceBody<LazyObject>(S, Name, Obj, S->body()->Type);
504   } else {
505     MemoryBufferRef MBRef = Obj.getBuffer();
506     if (!MBRef.getBuffer().empty())
507       addFile(createObjectFile(MBRef));
508   }
509 }
510 
511 // Process undefined (-u) flags by loading lazy symbols named by those flags.
512 template <class ELFT> void SymbolTable<ELFT>::scanUndefinedFlags() {
513   for (StringRef S : Config->Undefined)
514     if (auto *L = dyn_cast_or_null<Lazy>(find(S)))
515       if (InputFile *File = L->fetch())
516         addFile(File);
517 }
518 
519 // This function takes care of the case in which shared libraries depend on
520 // the user program (not the other way, which is usual). Shared libraries
521 // may have undefined symbols, expecting that the user program provides
522 // the definitions for them. An example is BSD's __progname symbol.
523 // We need to put such symbols to the main program's .dynsym so that
524 // shared libraries can find them.
525 // Except this, we ignore undefined symbols in DSOs.
526 template <class ELFT> void SymbolTable<ELFT>::scanShlibUndefined() {
527   for (SharedFile<ELFT> *File : SharedFiles)
528     for (StringRef U : File->getUndefinedSymbols())
529       if (SymbolBody *Sym = find(U))
530         if (Sym->isDefined())
531           Sym->symbol()->ExportDynamic = true;
532 }
533 
534 // Initialize DemangledSyms with a map from demangled symbols to symbol
535 // objects. Used to handle "extern C++" directive in version scripts.
536 //
537 // The map will contain all demangled symbols. That can be very large,
538 // and in LLD we generally want to avoid do anything for each symbol.
539 // Then, why are we doing this? Here's why.
540 //
541 // Users can use "extern C++ {}" directive to match against demangled
542 // C++ symbols. For example, you can write a pattern such as
543 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
544 // other than trying to match a pattern against all demangled symbols.
545 // So, if "extern C++" feature is used, we need to demangle all known
546 // symbols.
547 template <class ELFT>
548 StringMap<std::vector<SymbolBody *>> &SymbolTable<ELFT>::getDemangledSyms() {
549   if (!DemangledSyms) {
550     DemangledSyms.emplace();
551     for (Symbol *Sym : SymVector) {
552       SymbolBody *B = Sym->body();
553       if (B->isUndefined())
554         continue;
555       if (Optional<std::string> S = demangle(B->getName()))
556         (*DemangledSyms)[*S].push_back(B);
557       else
558         (*DemangledSyms)[B->getName()].push_back(B);
559     }
560   }
561   return *DemangledSyms;
562 }
563 
564 template <class ELFT>
565 std::vector<SymbolBody *> SymbolTable<ELFT>::findByVersion(SymbolVersion Ver) {
566   if (Ver.IsExternCpp)
567     return getDemangledSyms().lookup(Ver.Name);
568   if (SymbolBody *B = find(Ver.Name))
569     if (!B->isUndefined())
570       return {B};
571   return {};
572 }
573 
574 template <class ELFT>
575 std::vector<SymbolBody *>
576 SymbolTable<ELFT>::findAllByVersion(SymbolVersion Ver) {
577   std::vector<SymbolBody *> Res;
578   StringMatcher M(Ver.Name);
579 
580   if (Ver.IsExternCpp) {
581     for (auto &P : getDemangledSyms())
582       if (M.match(P.first()))
583         Res.insert(Res.end(), P.second.begin(), P.second.end());
584     return Res;
585   }
586 
587   for (Symbol *Sym : SymVector) {
588     SymbolBody *B = Sym->body();
589     if (!B->isUndefined() && M.match(B->getName()))
590       Res.push_back(B);
591   }
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.
598 template <class ELFT> void SymbolTable<ELFT>::handleAnonymousVersion() {
599   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
600     assignExactVersion(Ver, VER_NDX_GLOBAL, "global");
601   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
602     assignWildcardVersion(Ver, VER_NDX_GLOBAL);
603   for (SymbolVersion &Ver : Config->VersionScriptLocals)
604     assignExactVersion(Ver, VER_NDX_LOCAL, "local");
605   for (SymbolVersion &Ver : Config->VersionScriptLocals)
606     assignWildcardVersion(Ver, VER_NDX_LOCAL);
607 }
608 
609 // Set symbol versions to symbols. This function handles patterns
610 // containing no wildcard characters.
611 template <class ELFT>
612 void SymbolTable<ELFT>::assignExactVersion(SymbolVersion Ver, uint16_t VersionId,
613                                            StringRef VersionName) {
614   if (Ver.HasWildcard)
615     return;
616 
617   // Get a list of symbols which we need to assign the version to.
618   std::vector<SymbolBody *> Syms = findByVersion(Ver);
619   if (Syms.empty()) {
620     if (Config->NoUndefinedVersion)
621       error("version script assignment of '" + VersionName + "' to symbol '" +
622             Ver.Name + "' failed: symbol not defined");
623     return;
624   }
625 
626   // Assign the version.
627   for (SymbolBody *B : Syms) {
628     Symbol *Sym = B->symbol();
629     if (Sym->InVersionScript)
630       warn("duplicate symbol '" + Ver.Name + "' in version script");
631     Sym->VersionId = VersionId;
632     Sym->InVersionScript = true;
633   }
634 }
635 
636 template <class ELFT>
637 void SymbolTable<ELFT>::assignWildcardVersion(SymbolVersion Ver,
638                                               uint16_t VersionId) {
639   if (!Ver.HasWildcard)
640     return;
641   std::vector<SymbolBody *> Syms = findAllByVersion(Ver);
642 
643   // Exact matching takes precendence over fuzzy matching,
644   // so we set a version to a symbol only if no version has been assigned
645   // to the symbol. This behavior is compatible with GNU.
646   for (SymbolBody *B : Syms)
647     if (B->symbol()->VersionId == Config->DefaultSymbolVersion)
648       B->symbol()->VersionId = VersionId;
649 }
650 
651 // This function processes version scripts by updating VersionId
652 // member of symbols.
653 template <class ELFT> void SymbolTable<ELFT>::scanVersionScript() {
654   // Symbol themselves might know their versions because symbols
655   // can contain versions in the form of <name>@<version>.
656   // Let them parse their names.
657   if (!Config->VersionDefinitions.empty())
658     for (Symbol *Sym : SymVector)
659       Sym->body()->parseSymbolVersion();
660 
661   // Handle edge cases first.
662   handleAnonymousVersion();
663 
664   if (Config->VersionDefinitions.empty())
665     return;
666 
667   // Now we have version definitions, so we need to set version ids to symbols.
668   // Each version definition has a glob pattern, and all symbols that match
669   // with the pattern get that version.
670 
671   // First, we assign versions to exact matching symbols,
672   // i.e. version definitions not containing any glob meta-characters.
673   for (VersionDefinition &V : Config->VersionDefinitions)
674     for (SymbolVersion &Ver : V.Globals)
675       assignExactVersion(Ver, V.Id, V.Name);
676 
677   // Next, we assign versions to fuzzy matching symbols,
678   // i.e. version definitions containing glob meta-characters.
679   // Note that because the last match takes precedence over previous matches,
680   // we iterate over the definitions in the reverse order.
681   for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions))
682     for (SymbolVersion &Ver : V.Globals)
683       assignWildcardVersion(Ver, V.Id);
684 }
685 
686 template class elf::SymbolTable<ELF32LE>;
687 template class elf::SymbolTable<ELF32BE>;
688 template class elf::SymbolTable<ELF64LE>;
689 template class elf::SymbolTable<ELF64BE>;
690