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