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