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