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