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