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 (!Config->FirstElf && isa<ELFFileBase<ELFT>>(File))
56     Config->FirstElf = File;
57 
58   if (!isCompatible<ELFT>(File))
59     return;
60 
61   // Binary file
62   if (auto *F = dyn_cast<BinaryFile>(File)) {
63     BinaryFiles.push_back(F);
64     F->parse<ELFT>();
65     return;
66   }
67 
68   // .a file
69   if (auto *F = dyn_cast<ArchiveFile>(File)) {
70     F->parse<ELFT>();
71     return;
72   }
73 
74   // Lazy object file
75   if (auto *F = dyn_cast<LazyObjectFile>(File)) {
76     F->parse<ELFT>();
77     return;
78   }
79 
80   if (Config->Trace)
81     message(toString(File));
82 
83   // .so file
84   if (auto *F = dyn_cast<SharedFile<ELFT>>(File)) {
85     // DSOs are uniquified not by filename but by soname.
86     F->parseSoName();
87     if (ErrorCount || !SoNames.insert(F->SoName).second)
88       return;
89     SharedFiles.push_back(F);
90     F->parseRest();
91     return;
92   }
93 
94   // LLVM bitcode file
95   if (auto *F = dyn_cast<BitcodeFile>(File)) {
96     BitcodeFiles.push_back(F);
97     F->parse<ELFT>(ComdatGroups);
98     return;
99   }
100 
101   // Regular object file
102   auto *F = cast<ObjectFile<ELFT>>(File);
103   ObjectFiles.push_back(F);
104   F->parse(ComdatGroups);
105 }
106 
107 // This function is where all the optimizations of link-time
108 // optimization happens. When LTO is in use, some input files are
109 // not in native object file format but in the LLVM bitcode format.
110 // This function compiles bitcode files into a few big native files
111 // using LLVM functions and replaces bitcode symbols with the results.
112 // Because all bitcode files that consist of a program are passed
113 // to the compiler at once, it can do whole-program optimization.
114 template <class ELFT> void SymbolTable<ELFT>::addCombinedLTOObject() {
115   if (BitcodeFiles.empty())
116     return;
117 
118   // Compile bitcode files and replace bitcode symbols.
119   LTO.reset(new BitcodeCompiler);
120   for (BitcodeFile *F : BitcodeFiles)
121     LTO->add(*F);
122 
123   for (InputFile *File : LTO->compile()) {
124     ObjectFile<ELFT> *Obj = cast<ObjectFile<ELFT>>(File);
125     DenseSet<CachedHashStringRef> DummyGroups;
126     Obj->parse(DummyGroups);
127     ObjectFiles.push_back(Obj);
128   }
129 }
130 
131 template <class ELFT>
132 DefinedRegular *SymbolTable<ELFT>::addAbsolute(StringRef Name,
133                                                uint8_t Visibility,
134                                                uint8_t Binding) {
135   Symbol *Sym =
136       addRegular(Name, Visibility, STT_NOTYPE, 0, 0, Binding, nullptr, nullptr);
137   return cast<DefinedRegular>(Sym->body());
138 }
139 
140 // Add Name as an "ignored" symbol. An ignored symbol is a regular
141 // linker-synthesized defined symbol, but is only defined if needed.
142 template <class ELFT>
143 DefinedRegular *SymbolTable<ELFT>::addIgnored(StringRef Name,
144                                               uint8_t Visibility) {
145   SymbolBody *S = find(Name);
146   if (!S || S->isInCurrentDSO())
147     return nullptr;
148   return addAbsolute(Name, Visibility);
149 }
150 
151 // Set a flag for --trace-symbol so that we can print out a log message
152 // if a new symbol with the same name is inserted into the symbol table.
153 template <class ELFT> void SymbolTable<ELFT>::trace(StringRef Name) {
154   Symtab.insert({CachedHashStringRef(Name), {-1, true}});
155 }
156 
157 // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.
158 // Used to implement --wrap.
159 template <class ELFT> void SymbolTable<ELFT>::addSymbolWrap(StringRef Name) {
160   SymbolBody *B = find(Name);
161   if (!B)
162     return;
163   Symbol *Sym = B->symbol();
164   Symbol *Real = addUndefined(Saver.save("__real_" + Name));
165   Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name));
166 
167   // Tell LTO not to eliminate this symbol
168   Wrap->IsUsedInRegularObj = true;
169 
170   Config->RenamedSymbols[Real] = {Sym, Real->Binding};
171   Config->RenamedSymbols[Sym] = {Wrap, Sym->Binding};
172 }
173 
174 // Creates alias for symbol. Used to implement --defsym=ALIAS=SYM.
175 template <class ELFT>
176 void SymbolTable<ELFT>::addSymbolAlias(StringRef Alias, StringRef Name) {
177   SymbolBody *B = find(Name);
178   if (!B) {
179     error("-defsym: undefined symbol: " + Name);
180     return;
181   }
182   Symbol *Sym = B->symbol();
183   Symbol *AliasSym = addUndefined(Alias);
184 
185   // Tell LTO not to eliminate this symbol
186   Sym->IsUsedInRegularObj = true;
187   Config->RenamedSymbols[AliasSym] = {Sym, AliasSym->Binding};
188 }
189 
190 // Apply symbol renames created by -wrap and -defsym. The renames are created
191 // before LTO in addSymbolWrap() and addSymbolAlias() to have a chance to inform
192 // LTO (if LTO is running) not to include these symbols in IPO. Now that the
193 // symbols are finalized, we can perform the replacement.
194 template <class ELFT> void SymbolTable<ELFT>::applySymbolRenames() {
195   for (auto &KV : Config->RenamedSymbols) {
196     Symbol *Dst = KV.first;
197     Symbol *Src = KV.second.Target;
198     Dst->body()->copy(Src->body());
199     Dst->Binding = KV.second.OriginalBinding;
200   }
201 }
202 
203 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
204   if (VA == STV_DEFAULT)
205     return VB;
206   if (VB == STV_DEFAULT)
207     return VA;
208   return std::min(VA, VB);
209 }
210 
211 // Find an existing symbol or create and insert a new one.
212 template <class ELFT>
213 std::pair<Symbol *, bool> SymbolTable<ELFT>::insert(StringRef Name) {
214   // <name>@@<version> means the symbol is the default version. In that
215   // case <name>@@<version> will be used to resolve references to <name>.
216   size_t Pos = Name.find("@@");
217   if (Pos != StringRef::npos)
218     Name = Name.take_front(Pos);
219 
220   auto P = Symtab.insert(
221       {CachedHashStringRef(Name), SymIndex((int)SymVector.size(), false)});
222   SymIndex &V = P.first->second;
223   bool IsNew = P.second;
224 
225   if (V.Idx == -1) {
226     IsNew = true;
227     V = SymIndex((int)SymVector.size(), true);
228   }
229 
230   Symbol *Sym;
231   if (IsNew) {
232     Sym = make<Symbol>();
233     Sym->InVersionScript = false;
234     Sym->Binding = STB_WEAK;
235     Sym->Visibility = STV_DEFAULT;
236     Sym->IsUsedInRegularObj = false;
237     Sym->ExportDynamic = false;
238     Sym->Traced = V.Traced;
239     Sym->VersionId = Config->DefaultSymbolVersion;
240     SymVector.push_back(Sym);
241   } else {
242     Sym = SymVector[V.Idx];
243   }
244   return {Sym, IsNew};
245 }
246 
247 // Find an existing symbol or create and insert a new one, then apply the given
248 // attributes.
249 template <class ELFT>
250 std::pair<Symbol *, bool>
251 SymbolTable<ELFT>::insert(StringRef Name, uint8_t Type, uint8_t Visibility,
252                           bool CanOmitFromDynSym, InputFile *File) {
253   bool IsUsedInRegularObj = !File || File->kind() == InputFile::ObjectKind;
254   Symbol *S;
255   bool WasInserted;
256   std::tie(S, WasInserted) = insert(Name);
257 
258   // Merge in the new symbol's visibility.
259   S->Visibility = getMinVisibility(S->Visibility, Visibility);
260 
261   if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic))
262     S->ExportDynamic = true;
263 
264   if (IsUsedInRegularObj)
265     S->IsUsedInRegularObj = true;
266 
267   if (!WasInserted && S->body()->Type != SymbolBody::UnknownType &&
268       ((Type == STT_TLS) != S->body()->isTls())) {
269     error("TLS attribute mismatch: " + toString(*S->body()) +
270           "\n>>> defined in " + toString(S->body()->File) +
271           "\n>>> defined in " + toString(File));
272   }
273 
274   return {S, WasInserted};
275 }
276 
277 template <class ELFT> Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name) {
278   return addUndefined(Name, /*IsLocal=*/false, STB_GLOBAL, STV_DEFAULT,
279                       /*Type*/ 0,
280                       /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
281 }
282 
283 static uint8_t getVisibility(uint8_t StOther) { return StOther & 3; }
284 
285 template <class ELFT>
286 Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name, bool IsLocal,
287                                         uint8_t Binding, uint8_t StOther,
288                                         uint8_t Type, bool CanOmitFromDynSym,
289                                         InputFile *File) {
290   Symbol *S;
291   bool WasInserted;
292   uint8_t Visibility = getVisibility(StOther);
293   std::tie(S, WasInserted) =
294       insert(Name, Type, Visibility, CanOmitFromDynSym, File);
295   // An undefined symbol with non default visibility must be satisfied
296   // in the same DSO.
297   if (WasInserted ||
298       (isa<SharedSymbol>(S->body()) && Visibility != STV_DEFAULT)) {
299     S->Binding = Binding;
300     replaceBody<Undefined>(S, Name, IsLocal, StOther, Type, File);
301     return S;
302   }
303   if (Binding != STB_WEAK) {
304     SymbolBody *B = S->body();
305     if (B->isShared() || B->isLazy() || B->isUndefined())
306       S->Binding = Binding;
307     if (auto *SS = dyn_cast<SharedSymbol>(B))
308       cast<SharedFile<ELFT>>(SS->File)->IsUsed = true;
309   }
310   if (auto *L = dyn_cast<Lazy>(S->body())) {
311     // An undefined weak will not fetch archive members, but we have to remember
312     // its type. See also comment in addLazyArchive.
313     if (S->isWeak())
314       L->Type = Type;
315     else if (InputFile *F = L->fetch())
316       addFile(F);
317   }
318   return S;
319 }
320 
321 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
322 // foo@@VER. We want to effectively ignore foo, so give precedence to
323 // foo@@VER.
324 // FIXME: If users can transition to using
325 // .symver foo,foo@@@VER
326 // we can delete this hack.
327 static int compareVersion(Symbol *S, StringRef Name) {
328   bool A = Name.contains("@@");
329   bool B = S->body()->getName().contains("@@");
330   if (A && !B)
331     return 1;
332   if (!A && B)
333     return -1;
334   return 0;
335 }
336 
337 // We have a new defined symbol with the specified binding. Return 1 if the new
338 // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are
339 // strong defined symbols.
340 static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding,
341                           StringRef Name) {
342   if (WasInserted)
343     return 1;
344   SymbolBody *Body = S->body();
345   if (!Body->isInCurrentDSO())
346     return 1;
347 
348   if (int R = compareVersion(S, Name))
349     return R;
350 
351   if (Binding == STB_WEAK)
352     return -1;
353   if (S->isWeak())
354     return 1;
355   return 0;
356 }
357 
358 // We have a new non-common defined symbol with the specified binding. Return 1
359 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there
360 // is a conflict. If the new symbol wins, also update the binding.
361 template <typename ELFT>
362 static int compareDefinedNonCommon(Symbol *S, bool WasInserted, uint8_t Binding,
363                                    bool IsAbsolute, typename ELFT::uint Value,
364                                    StringRef Name) {
365   if (int Cmp = compareDefined(S, WasInserted, Binding, Name)) {
366     if (Cmp > 0)
367       S->Binding = Binding;
368     return Cmp;
369   }
370   SymbolBody *B = S->body();
371   if (isa<DefinedCommon>(B)) {
372     // Non-common symbols take precedence over common symbols.
373     if (Config->WarnCommon)
374       warn("common " + S->body()->getName() + " is overridden");
375     return 1;
376   } else if (auto *R = dyn_cast<DefinedRegular>(B)) {
377     if (R->Section == nullptr && Binding == STB_GLOBAL && IsAbsolute &&
378         R->Value == Value)
379       return -1;
380   }
381   return 0;
382 }
383 
384 template <class ELFT>
385 Symbol *SymbolTable<ELFT>::addCommon(StringRef N, uint64_t Size,
386                                      uint32_t Alignment, uint8_t Binding,
387                                      uint8_t StOther, uint8_t Type,
388                                      InputFile *File) {
389   Symbol *S;
390   bool WasInserted;
391   std::tie(S, WasInserted) = insert(N, Type, getVisibility(StOther),
392                                     /*CanOmitFromDynSym*/ false, File);
393   int Cmp = compareDefined(S, WasInserted, Binding, N);
394   if (Cmp > 0) {
395     S->Binding = Binding;
396     replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
397   } else if (Cmp == 0) {
398     auto *C = dyn_cast<DefinedCommon>(S->body());
399     if (!C) {
400       // Non-common symbols take precedence over common symbols.
401       if (Config->WarnCommon)
402         warn("common " + S->body()->getName() + " is overridden");
403       return S;
404     }
405 
406     if (Config->WarnCommon)
407       warn("multiple common of " + S->body()->getName());
408 
409     Alignment = C->Alignment = std::max(C->Alignment, Alignment);
410     if (Size > C->Size)
411       replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
412   }
413   return S;
414 }
415 
416 static void warnOrError(const Twine &Msg) {
417   if (Config->AllowMultipleDefinition)
418     warn(Msg);
419   else
420     error(Msg);
421 }
422 
423 static void reportDuplicate(SymbolBody *Sym, InputFile *NewFile) {
424   warnOrError("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " +
425               toString(Sym->File) + "\n>>> defined in " + toString(NewFile));
426 }
427 
428 template <class ELFT>
429 static void reportDuplicate(SymbolBody *Sym, InputSectionBase *ErrSec,
430                             typename ELFT::uint ErrOffset) {
431   DefinedRegular *D = dyn_cast<DefinedRegular>(Sym);
432   if (!D || !D->Section || !ErrSec) {
433     reportDuplicate(Sym, ErrSec ? ErrSec->getFile<ELFT>() : nullptr);
434     return;
435   }
436 
437   // Construct and print an error message in the form of:
438   //
439   //   ld.lld: error: duplicate symbol: foo
440   //   >>> defined at bar.c:30
441   //   >>>            bar.o (/home/alice/src/bar.o)
442   //   >>> defined at baz.c:563
443   //   >>>            baz.o in archive libbaz.a
444   auto *Sec1 = cast<InputSectionBase>(D->Section);
445   std::string Src1 = Sec1->getSrcMsg<ELFT>(D->Value);
446   std::string Obj1 = Sec1->getObjMsg<ELFT>(D->Value);
447   std::string Src2 = ErrSec->getSrcMsg<ELFT>(ErrOffset);
448   std::string Obj2 = ErrSec->getObjMsg<ELFT>(ErrOffset);
449 
450   std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at ";
451   if (!Src1.empty())
452     Msg += Src1 + "\n>>>            ";
453   Msg += Obj1 + "\n>>> defined at ";
454   if (!Src2.empty())
455     Msg += Src2 + "\n>>>            ";
456   Msg += Obj2;
457   warnOrError(Msg);
458 }
459 
460 template <typename ELFT>
461 Symbol *SymbolTable<ELFT>::addRegular(StringRef Name, uint8_t StOther,
462                                       uint8_t Type, uint64_t Value,
463                                       uint64_t Size, uint8_t Binding,
464                                       SectionBase *Section, InputFile *File) {
465   Symbol *S;
466   bool WasInserted;
467   std::tie(S, WasInserted) = insert(Name, Type, getVisibility(StOther),
468                                     /*CanOmitFromDynSym*/ false, File);
469   int Cmp = compareDefinedNonCommon<ELFT>(S, WasInserted, Binding,
470                                           Section == nullptr, Value, Name);
471   if (Cmp > 0)
472     replaceBody<DefinedRegular>(S, Name, /*IsLocal=*/false, StOther, Type,
473                                 Value, Size, Section, File);
474   else if (Cmp == 0)
475     reportDuplicate<ELFT>(S->body(),
476                           dyn_cast_or_null<InputSectionBase>(Section), Value);
477   return S;
478 }
479 
480 template <typename ELFT>
481 void SymbolTable<ELFT>::addShared(SharedFile<ELFT> *File, StringRef Name,
482                                   const Elf_Sym &Sym,
483                                   const typename ELFT::Verdef *Verdef) {
484   // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT
485   // as the visibility, which will leave the visibility in the symbol table
486   // unchanged.
487   Symbol *S;
488   bool WasInserted;
489   std::tie(S, WasInserted) = insert(Name, Sym.getType(), STV_DEFAULT,
490                                     /*CanOmitFromDynSym*/ true, File);
491   // Make sure we preempt DSO symbols with default visibility.
492   if (Sym.getVisibility() == STV_DEFAULT)
493     S->ExportDynamic = true;
494 
495   SymbolBody *Body = S->body();
496   // An undefined symbol with non default visibility must be satisfied
497   // in the same DSO.
498   if (WasInserted ||
499       (isa<Undefined>(Body) && Body->getVisibility() == STV_DEFAULT)) {
500     replaceBody<SharedSymbol>(S, File, Name, Sym.st_other, Sym.getType(), &Sym,
501                               Verdef);
502     if (!S->isWeak())
503       File->IsUsed = true;
504   }
505 }
506 
507 template <class ELFT>
508 Symbol *SymbolTable<ELFT>::addBitcode(StringRef Name, uint8_t Binding,
509                                       uint8_t StOther, uint8_t Type,
510                                       bool CanOmitFromDynSym, BitcodeFile *F) {
511   Symbol *S;
512   bool WasInserted;
513   std::tie(S, WasInserted) =
514       insert(Name, Type, getVisibility(StOther), CanOmitFromDynSym, F);
515   int Cmp = compareDefinedNonCommon<ELFT>(S, WasInserted, Binding,
516                                           /*IsAbs*/ false, /*Value*/ 0, Name);
517   if (Cmp > 0)
518     replaceBody<DefinedRegular>(S, Name, /*IsLocal=*/false, StOther, Type, 0, 0,
519                                 nullptr, F);
520   else if (Cmp == 0)
521     reportDuplicate(S->body(), F);
522   return S;
523 }
524 
525 template <class ELFT> SymbolBody *SymbolTable<ELFT>::find(StringRef Name) {
526   auto It = Symtab.find(CachedHashStringRef(Name));
527   if (It == Symtab.end())
528     return nullptr;
529   SymIndex V = It->second;
530   if (V.Idx == -1)
531     return nullptr;
532   return SymVector[V.Idx]->body();
533 }
534 
535 template <class ELFT>
536 SymbolBody *SymbolTable<ELFT>::findInCurrentDSO(StringRef Name) {
537   if (SymbolBody *S = find(Name))
538     if (S->isInCurrentDSO())
539       return S;
540   return nullptr;
541 }
542 
543 template <class ELFT>
544 Symbol *SymbolTable<ELFT>::addLazyArchive(ArchiveFile *F,
545                                           const object::Archive::Symbol Sym) {
546   Symbol *S;
547   bool WasInserted;
548   StringRef Name = Sym.getName();
549   std::tie(S, WasInserted) = insert(Name);
550   if (WasInserted) {
551     replaceBody<LazyArchive>(S, *F, Sym, SymbolBody::UnknownType);
552     return S;
553   }
554   if (!S->body()->isUndefined())
555     return S;
556 
557   // Weak undefined symbols should not fetch members from archives. If we were
558   // to keep old symbol we would not know that an archive member was available
559   // if a strong undefined symbol shows up afterwards in the link. If a strong
560   // undefined symbol never shows up, this lazy symbol will get to the end of
561   // the link and must be treated as the weak undefined one. We already marked
562   // this symbol as used when we added it to the symbol table, but we also need
563   // to preserve its type. FIXME: Move the Type field to Symbol.
564   if (S->isWeak()) {
565     replaceBody<LazyArchive>(S, *F, Sym, S->body()->Type);
566     return S;
567   }
568   std::pair<MemoryBufferRef, uint64_t> MBInfo = F->getMember(&Sym);
569   if (!MBInfo.first.getBuffer().empty())
570     addFile(createObjectFile(MBInfo.first, F->getName(), MBInfo.second));
571   return S;
572 }
573 
574 template <class ELFT>
575 void SymbolTable<ELFT>::addLazyObject(StringRef Name, LazyObjectFile &Obj) {
576   Symbol *S;
577   bool WasInserted;
578   std::tie(S, WasInserted) = insert(Name);
579   if (WasInserted) {
580     replaceBody<LazyObject>(S, Name, Obj, SymbolBody::UnknownType);
581     return;
582   }
583   if (!S->body()->isUndefined())
584     return;
585 
586   // See comment for addLazyArchive above.
587   if (S->isWeak())
588     replaceBody<LazyObject>(S, Name, Obj, S->body()->Type);
589   else if (InputFile *F = Obj.fetch())
590     addFile(F);
591 }
592 
593 // Process undefined (-u) flags by loading lazy symbols named by those flags.
594 template <class ELFT> void SymbolTable<ELFT>::scanUndefinedFlags() {
595   for (StringRef S : Config->Undefined)
596     if (auto *L = dyn_cast_or_null<Lazy>(find(S)))
597       if (InputFile *File = L->fetch())
598         addFile(File);
599 }
600 
601 // This function takes care of the case in which shared libraries depend on
602 // the user program (not the other way, which is usual). Shared libraries
603 // may have undefined symbols, expecting that the user program provides
604 // the definitions for them. An example is BSD's __progname symbol.
605 // We need to put such symbols to the main program's .dynsym so that
606 // shared libraries can find them.
607 // Except this, we ignore undefined symbols in DSOs.
608 template <class ELFT> void SymbolTable<ELFT>::scanShlibUndefined() {
609   for (SharedFile<ELFT> *File : SharedFiles) {
610     for (StringRef U : File->getUndefinedSymbols()) {
611       SymbolBody *Sym = find(U);
612       if (!Sym || !Sym->isDefined())
613         continue;
614       Sym->symbol()->ExportDynamic = true;
615 
616       // If -dynamic-list is given, the default version is set to
617       // VER_NDX_LOCAL, which prevents a symbol to be exported via .dynsym.
618       // Set to VER_NDX_GLOBAL so the symbol will be handled as if it were
619       // specified by -dynamic-list.
620       Sym->symbol()->VersionId = VER_NDX_GLOBAL;
621     }
622   }
623 }
624 
625 // Initialize DemangledSyms with a map from demangled symbols to symbol
626 // objects. Used to handle "extern C++" directive in version scripts.
627 //
628 // The map will contain all demangled symbols. That can be very large,
629 // and in LLD we generally want to avoid do anything for each symbol.
630 // Then, why are we doing this? Here's why.
631 //
632 // Users can use "extern C++ {}" directive to match against demangled
633 // C++ symbols. For example, you can write a pattern such as
634 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
635 // other than trying to match a pattern against all demangled symbols.
636 // So, if "extern C++" feature is used, we need to demangle all known
637 // symbols.
638 template <class ELFT>
639 StringMap<std::vector<SymbolBody *>> &SymbolTable<ELFT>::getDemangledSyms() {
640   if (!DemangledSyms) {
641     DemangledSyms.emplace();
642     for (Symbol *Sym : SymVector) {
643       SymbolBody *B = Sym->body();
644       if (B->isUndefined())
645         continue;
646       if (Optional<std::string> S = demangle(B->getName()))
647         (*DemangledSyms)[*S].push_back(B);
648       else
649         (*DemangledSyms)[B->getName()].push_back(B);
650     }
651   }
652   return *DemangledSyms;
653 }
654 
655 template <class ELFT>
656 std::vector<SymbolBody *> SymbolTable<ELFT>::findByVersion(SymbolVersion Ver) {
657   if (Ver.IsExternCpp)
658     return getDemangledSyms().lookup(Ver.Name);
659   if (SymbolBody *B = find(Ver.Name))
660     if (!B->isUndefined())
661       return {B};
662   return {};
663 }
664 
665 template <class ELFT>
666 std::vector<SymbolBody *>
667 SymbolTable<ELFT>::findAllByVersion(SymbolVersion Ver) {
668   std::vector<SymbolBody *> Res;
669   StringMatcher M(Ver.Name);
670 
671   if (Ver.IsExternCpp) {
672     for (auto &P : getDemangledSyms())
673       if (M.match(P.first()))
674         Res.insert(Res.end(), P.second.begin(), P.second.end());
675     return Res;
676   }
677 
678   for (Symbol *Sym : SymVector) {
679     SymbolBody *B = Sym->body();
680     if (!B->isUndefined() && M.match(B->getName()))
681       Res.push_back(B);
682   }
683   return Res;
684 }
685 
686 // If there's only one anonymous version definition in a version
687 // script file, the script does not actually define any symbol version,
688 // but just specifies symbols visibilities.
689 template <class ELFT> void SymbolTable<ELFT>::handleAnonymousVersion() {
690   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
691     assignExactVersion(Ver, VER_NDX_GLOBAL, "global");
692   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
693     assignWildcardVersion(Ver, VER_NDX_GLOBAL);
694   for (SymbolVersion &Ver : Config->VersionScriptLocals)
695     assignExactVersion(Ver, VER_NDX_LOCAL, "local");
696   for (SymbolVersion &Ver : Config->VersionScriptLocals)
697     assignWildcardVersion(Ver, VER_NDX_LOCAL);
698 }
699 
700 // Set symbol versions to symbols. This function handles patterns
701 // containing no wildcard characters.
702 template <class ELFT>
703 void SymbolTable<ELFT>::assignExactVersion(SymbolVersion Ver,
704                                            uint16_t VersionId,
705                                            StringRef VersionName) {
706   if (Ver.HasWildcard)
707     return;
708 
709   // Get a list of symbols which we need to assign the version to.
710   std::vector<SymbolBody *> Syms = findByVersion(Ver);
711   if (Syms.empty()) {
712     if (Config->NoUndefinedVersion)
713       error("version script assignment of '" + VersionName + "' to symbol '" +
714             Ver.Name + "' failed: symbol not defined");
715     return;
716   }
717 
718   // Assign the version.
719   for (SymbolBody *B : Syms) {
720     // Skip symbols containing version info because symbol versions
721     // specified by symbol names take precedence over version scripts.
722     // See parseSymbolVersion().
723     if (B->getName().contains('@'))
724       continue;
725 
726     Symbol *Sym = B->symbol();
727     if (Sym->InVersionScript)
728       warn("duplicate symbol '" + Ver.Name + "' in version script");
729     Sym->VersionId = VersionId;
730     Sym->InVersionScript = true;
731   }
732 }
733 
734 template <class ELFT>
735 void SymbolTable<ELFT>::assignWildcardVersion(SymbolVersion Ver,
736                                               uint16_t VersionId) {
737   if (!Ver.HasWildcard)
738     return;
739 
740   // Exact matching takes precendence over fuzzy matching,
741   // so we set a version to a symbol only if no version has been assigned
742   // to the symbol. This behavior is compatible with GNU.
743   for (SymbolBody *B : findAllByVersion(Ver))
744     if (B->symbol()->VersionId == Config->DefaultSymbolVersion)
745       B->symbol()->VersionId = VersionId;
746 }
747 
748 // This function processes version scripts by updating VersionId
749 // member of symbols.
750 template <class ELFT> void SymbolTable<ELFT>::scanVersionScript() {
751   // Handle edge cases first.
752   handleAnonymousVersion();
753 
754   // Now we have version definitions, so we need to set version ids to symbols.
755   // Each version definition has a glob pattern, and all symbols that match
756   // with the pattern get that version.
757 
758   // First, we assign versions to exact matching symbols,
759   // i.e. version definitions not containing any glob meta-characters.
760   for (VersionDefinition &V : Config->VersionDefinitions)
761     for (SymbolVersion &Ver : V.Globals)
762       assignExactVersion(Ver, V.Id, V.Name);
763 
764   // Next, we assign versions to fuzzy matching symbols,
765   // i.e. version definitions containing glob meta-characters.
766   // Note that because the last match takes precedence over previous matches,
767   // we iterate over the definitions in the reverse order.
768   for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions))
769     for (SymbolVersion &Ver : V.Globals)
770       assignWildcardVersion(Ver, V.Id);
771 
772   // Symbol themselves might know their versions because symbols
773   // can contain versions in the form of <name>@<version>.
774   // Let them parse and update their names to exclude version suffix.
775   for (Symbol *Sym : SymVector)
776     Sym->body()->parseSymbolVersion();
777 }
778 
779 template class elf::SymbolTable<ELF32LE>;
780 template class elf::SymbolTable<ELF32BE>;
781 template class elf::SymbolTable<ELF64LE>;
782 template class elf::SymbolTable<ELF64BE>;
783