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   defsym(Real, Sym);
168   defsym(Sym, Wrap);
169 }
170 
171 // Creates alias for symbol. Used to implement --defsym=ALIAS=SYM.
172 template <class ELFT>
173 void SymbolTable::addSymbolAlias(StringRef Alias, StringRef Name) {
174   SymbolBody *B = find(Name);
175   if (!B) {
176     error("-defsym: undefined symbol: " + Name);
177     return;
178   }
179 
180   // Tell LTO not to eliminate this symbol.
181   B->symbol()->IsUsedInRegularObj = true;
182   defsym(addUndefined<ELFT>(Alias), B->symbol());
183 }
184 
185 // Apply symbol renames created by -wrap and -defsym. The renames are created
186 // before LTO in addSymbolWrap() and addSymbolAlias() to have a chance to inform
187 // LTO (if LTO is running) not to include these symbols in IPO. Now that the
188 // symbols are finalized, we can perform the replacement.
189 void SymbolTable::applySymbolRenames() {
190   for (SymbolRenaming &S : Defsyms) {
191     S.Dst->body()->copyFrom(S.Src->body());
192     S.Dst->File = S.Src->File;
193     S.Dst->Binding = S.Binding;
194   }
195 }
196 
197 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
198   if (VA == STV_DEFAULT)
199     return VB;
200   if (VB == STV_DEFAULT)
201     return VA;
202   return std::min(VA, VB);
203 }
204 
205 // Find an existing symbol or create and insert a new one.
206 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name) {
207   // <name>@@<version> means the symbol is the default version. In that
208   // case <name>@@<version> will be used to resolve references to <name>.
209   //
210   // Since this is a hot path, the following string search code is
211   // optimized for speed. StringRef::find(char) is much faster than
212   // StringRef::find(StringRef).
213   size_t Pos = Name.find('@');
214   if (Pos != StringRef::npos && Pos + 1 < Name.size() && Name[Pos + 1] == '@')
215     Name = Name.take_front(Pos);
216 
217   auto P = Symtab.insert(
218       {CachedHashStringRef(Name), SymIndex((int)SymVector.size(), false)});
219   SymIndex &V = P.first->second;
220   bool IsNew = P.second;
221 
222   if (V.Idx == -1) {
223     IsNew = true;
224     V = SymIndex((int)SymVector.size(), true);
225   }
226 
227   Symbol *Sym;
228   if (IsNew) {
229     Sym = make<Symbol>();
230     Sym->InVersionScript = false;
231     Sym->Binding = STB_WEAK;
232     Sym->Visibility = STV_DEFAULT;
233     Sym->IsUsedInRegularObj = false;
234     Sym->ExportDynamic = false;
235     Sym->CanInline = true;
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 void SymbolTable::defsym(Symbol *Dst, Symbol *Src) {
529   // We want to tell LTO not to inline Dst symbol because LTO doesn't
530   // know the final symbol contents after renaming.
531   Dst->CanInline = false;
532   Defsyms.push_back({Dst, Src, Dst->Binding});
533 }
534 
535 template <class ELFT>
536 Symbol *SymbolTable::addLazyArchive(ArchiveFile *F,
537                                     const object::Archive::Symbol Sym) {
538   Symbol *S;
539   bool WasInserted;
540   StringRef Name = Sym.getName();
541   std::tie(S, WasInserted) = insert(Name);
542   if (WasInserted) {
543     replaceBody<LazyArchive>(S, F, Sym, SymbolBody::UnknownType);
544     return S;
545   }
546   if (!S->body()->isUndefined())
547     return S;
548 
549   // Weak undefined symbols should not fetch members from archives. If we were
550   // to keep old symbol we would not know that an archive member was available
551   // if a strong undefined symbol shows up afterwards in the link. If a strong
552   // undefined symbol never shows up, this lazy symbol will get to the end of
553   // the link and must be treated as the weak undefined one. We already marked
554   // this symbol as used when we added it to the symbol table, but we also need
555   // to preserve its type. FIXME: Move the Type field to Symbol.
556   if (S->isWeak()) {
557     replaceBody<LazyArchive>(S, F, Sym, S->body()->Type);
558     return S;
559   }
560   std::pair<MemoryBufferRef, uint64_t> MBInfo = F->getMember(&Sym);
561   if (!MBInfo.first.getBuffer().empty())
562     addFile<ELFT>(createObjectFile(MBInfo.first, F->getName(), MBInfo.second));
563   return S;
564 }
565 
566 template <class ELFT>
567 void SymbolTable::addLazyObject(StringRef Name, LazyObjFile &Obj) {
568   Symbol *S;
569   bool WasInserted;
570   std::tie(S, WasInserted) = insert(Name);
571   if (WasInserted) {
572     replaceBody<LazyObject>(S, &Obj, Name, SymbolBody::UnknownType);
573     return;
574   }
575   if (!S->body()->isUndefined())
576     return;
577 
578   // See comment for addLazyArchive above.
579   if (S->isWeak())
580     replaceBody<LazyObject>(S, &Obj, Name, S->body()->Type);
581   else if (InputFile *F = Obj.fetch())
582     addFile<ELFT>(F);
583 }
584 
585 // Process undefined (-u) flags by loading lazy symbols named by those flags.
586 template <class ELFT> void SymbolTable::scanUndefinedFlags() {
587   for (StringRef S : Config->Undefined)
588     if (auto *L = dyn_cast_or_null<Lazy>(find(S)))
589       if (InputFile *File = L->fetch())
590         addFile<ELFT>(File);
591 }
592 
593 // This function takes care of the case in which shared libraries depend on
594 // the user program (not the other way, which is usual). Shared libraries
595 // may have undefined symbols, expecting that the user program provides
596 // the definitions for them. An example is BSD's __progname symbol.
597 // We need to put such symbols to the main program's .dynsym so that
598 // shared libraries can find them.
599 // Except this, we ignore undefined symbols in DSOs.
600 template <class ELFT> void SymbolTable::scanShlibUndefined() {
601   for (InputFile *F : SharedFiles) {
602     for (StringRef U : cast<SharedFile<ELFT>>(F)->getUndefinedSymbols()) {
603       SymbolBody *Sym = find(U);
604       if (!Sym || !Sym->isDefined())
605         continue;
606       Sym->symbol()->ExportDynamic = true;
607 
608       // If -dynamic-list is given, the default version is set to
609       // VER_NDX_LOCAL, which prevents a symbol to be exported via .dynsym.
610       // Set to VER_NDX_GLOBAL so the symbol will be handled as if it were
611       // specified by -dynamic-list.
612       Sym->symbol()->VersionId = VER_NDX_GLOBAL;
613     }
614   }
615 }
616 
617 // Initialize DemangledSyms with a map from demangled symbols to symbol
618 // objects. Used to handle "extern C++" directive in version scripts.
619 //
620 // The map will contain all demangled symbols. That can be very large,
621 // and in LLD we generally want to avoid do anything for each symbol.
622 // Then, why are we doing this? Here's why.
623 //
624 // Users can use "extern C++ {}" directive to match against demangled
625 // C++ symbols. For example, you can write a pattern such as
626 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
627 // other than trying to match a pattern against all demangled symbols.
628 // So, if "extern C++" feature is used, we need to demangle all known
629 // symbols.
630 StringMap<std::vector<SymbolBody *>> &SymbolTable::getDemangledSyms() {
631   if (!DemangledSyms) {
632     DemangledSyms.emplace();
633     for (Symbol *Sym : SymVector) {
634       SymbolBody *B = Sym->body();
635       if (B->isUndefined())
636         continue;
637       if (Optional<std::string> S = demangle(B->getName()))
638         (*DemangledSyms)[*S].push_back(B);
639       else
640         (*DemangledSyms)[B->getName()].push_back(B);
641     }
642   }
643   return *DemangledSyms;
644 }
645 
646 std::vector<SymbolBody *> SymbolTable::findByVersion(SymbolVersion Ver) {
647   if (Ver.IsExternCpp)
648     return getDemangledSyms().lookup(Ver.Name);
649   if (SymbolBody *B = find(Ver.Name))
650     if (!B->isUndefined())
651       return {B};
652   return {};
653 }
654 
655 std::vector<SymbolBody *> SymbolTable::findAllByVersion(SymbolVersion Ver) {
656   std::vector<SymbolBody *> 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     SymbolBody *B = Sym->body();
668     if (!B->isUndefined() && M.match(B->getName()))
669       Res.push_back(B);
670   }
671   return Res;
672 }
673 
674 // If there's only one anonymous version definition in a version
675 // script file, the script does not actually define any symbol version,
676 // but just specifies symbols visibilities.
677 void SymbolTable::handleAnonymousVersion() {
678   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
679     assignExactVersion(Ver, VER_NDX_GLOBAL, "global");
680   for (SymbolVersion &Ver : Config->VersionScriptGlobals)
681     assignWildcardVersion(Ver, VER_NDX_GLOBAL);
682   for (SymbolVersion &Ver : Config->VersionScriptLocals)
683     assignExactVersion(Ver, VER_NDX_LOCAL, "local");
684   for (SymbolVersion &Ver : Config->VersionScriptLocals)
685     assignWildcardVersion(Ver, VER_NDX_LOCAL);
686 }
687 
688 // Handles -dynamic-list.
689 void SymbolTable::handleDynamicList() {
690   for (SymbolVersion &Ver : Config->DynamicList) {
691     std::vector<SymbolBody *> Syms;
692     if (Ver.HasWildcard)
693       Syms = findByVersion(Ver);
694     else
695       Syms = findAllByVersion(Ver);
696 
697     for (SymbolBody *B : Syms) {
698       if (!Config->Shared)
699         B->symbol()->VersionId = VER_NDX_GLOBAL;
700       else if (B->symbol()->includeInDynsym())
701         B->IsPreemptible = true;
702     }
703   }
704 }
705 
706 // Set symbol versions to symbols. This function handles patterns
707 // containing no wildcard characters.
708 void SymbolTable::assignExactVersion(SymbolVersion Ver, uint16_t VersionId,
709                                      StringRef VersionName) {
710   if (Ver.HasWildcard)
711     return;
712 
713   // Get a list of symbols which we need to assign the version to.
714   std::vector<SymbolBody *> Syms = findByVersion(Ver);
715   if (Syms.empty()) {
716     if (Config->NoUndefinedVersion)
717       error("version script assignment of '" + VersionName + "' to symbol '" +
718             Ver.Name + "' failed: symbol not defined");
719     return;
720   }
721 
722   // Assign the version.
723   for (SymbolBody *B : Syms) {
724     // Skip symbols containing version info because symbol versions
725     // specified by symbol names take precedence over version scripts.
726     // See parseSymbolVersion().
727     if (B->getName().contains('@'))
728       continue;
729 
730     Symbol *Sym = B->symbol();
731     if (Sym->InVersionScript)
732       warn("duplicate symbol '" + Ver.Name + "' in version script");
733     Sym->VersionId = VersionId;
734     Sym->InVersionScript = true;
735   }
736 }
737 
738 void SymbolTable::assignWildcardVersion(SymbolVersion Ver, uint16_t VersionId) {
739   if (!Ver.HasWildcard)
740     return;
741 
742   // Exact matching takes precendence over fuzzy matching,
743   // so we set a version to a symbol only if no version has been assigned
744   // to the symbol. This behavior is compatible with GNU.
745   for (SymbolBody *B : findAllByVersion(Ver))
746     if (B->symbol()->VersionId == Config->DefaultSymbolVersion)
747       B->symbol()->VersionId = VersionId;
748 }
749 
750 // This function processes version scripts by updating VersionId
751 // member of symbols.
752 void SymbolTable::scanVersionScript() {
753   // Handle edge cases first.
754   handleAnonymousVersion();
755   handleDynamicList();
756 
757   // Now we have version definitions, so we need to set version ids to symbols.
758   // Each version definition has a glob pattern, and all symbols that match
759   // with the pattern get that version.
760 
761   // First, we assign versions to exact matching symbols,
762   // i.e. version definitions not containing any glob meta-characters.
763   for (VersionDefinition &V : Config->VersionDefinitions)
764     for (SymbolVersion &Ver : V.Globals)
765       assignExactVersion(Ver, V.Id, V.Name);
766 
767   // Next, we assign versions to fuzzy matching symbols,
768   // i.e. version definitions containing glob meta-characters.
769   // Note that because the last match takes precedence over previous matches,
770   // we iterate over the definitions in the reverse order.
771   for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions))
772     for (SymbolVersion &Ver : V.Globals)
773       assignWildcardVersion(Ver, V.Id);
774 
775   // Symbol themselves might know their versions because symbols
776   // can contain versions in the form of <name>@<version>.
777   // Let them parse and update their names to exclude version suffix.
778   for (Symbol *Sym : SymVector)
779     Sym->body()->parseSymbolVersion();
780 }
781 
782 template void SymbolTable::addSymbolWrap<ELF32LE>(StringRef);
783 template void SymbolTable::addSymbolWrap<ELF32BE>(StringRef);
784 template void SymbolTable::addSymbolWrap<ELF64LE>(StringRef);
785 template void SymbolTable::addSymbolWrap<ELF64BE>(StringRef);
786 
787 template Symbol *SymbolTable::addUndefined<ELF32LE>(StringRef);
788 template Symbol *SymbolTable::addUndefined<ELF32BE>(StringRef);
789 template Symbol *SymbolTable::addUndefined<ELF64LE>(StringRef);
790 template Symbol *SymbolTable::addUndefined<ELF64BE>(StringRef);
791 
792 template Symbol *SymbolTable::addUndefined<ELF32LE>(StringRef, bool, uint8_t,
793                                                     uint8_t, uint8_t, bool,
794                                                     InputFile *);
795 template Symbol *SymbolTable::addUndefined<ELF32BE>(StringRef, bool, uint8_t,
796                                                     uint8_t, uint8_t, bool,
797                                                     InputFile *);
798 template Symbol *SymbolTable::addUndefined<ELF64LE>(StringRef, bool, uint8_t,
799                                                     uint8_t, uint8_t, bool,
800                                                     InputFile *);
801 template Symbol *SymbolTable::addUndefined<ELF64BE>(StringRef, bool, uint8_t,
802                                                     uint8_t, uint8_t, bool,
803                                                     InputFile *);
804 
805 template void SymbolTable::addSymbolAlias<ELF32LE>(StringRef, StringRef);
806 template void SymbolTable::addSymbolAlias<ELF32BE>(StringRef, StringRef);
807 template void SymbolTable::addSymbolAlias<ELF64LE>(StringRef, StringRef);
808 template void SymbolTable::addSymbolAlias<ELF64BE>(StringRef, StringRef);
809 
810 template void SymbolTable::addCombinedLTOObject<ELF32LE>();
811 template void SymbolTable::addCombinedLTOObject<ELF32BE>();
812 template void SymbolTable::addCombinedLTOObject<ELF64LE>();
813 template void SymbolTable::addCombinedLTOObject<ELF64BE>();
814 
815 template Symbol *SymbolTable::addRegular<ELF32LE>(StringRef, uint8_t, uint8_t,
816                                                   uint64_t, uint64_t, uint8_t,
817                                                   SectionBase *, InputFile *);
818 template Symbol *SymbolTable::addRegular<ELF32BE>(StringRef, uint8_t, uint8_t,
819                                                   uint64_t, uint64_t, uint8_t,
820                                                   SectionBase *, InputFile *);
821 template Symbol *SymbolTable::addRegular<ELF64LE>(StringRef, uint8_t, uint8_t,
822                                                   uint64_t, uint64_t, uint8_t,
823                                                   SectionBase *, InputFile *);
824 template Symbol *SymbolTable::addRegular<ELF64BE>(StringRef, uint8_t, uint8_t,
825                                                   uint64_t, uint64_t, uint8_t,
826                                                   SectionBase *, InputFile *);
827 
828 template DefinedRegular *SymbolTable::addAbsolute<ELF32LE>(StringRef, uint8_t,
829                                                            uint8_t);
830 template DefinedRegular *SymbolTable::addAbsolute<ELF32BE>(StringRef, uint8_t,
831                                                            uint8_t);
832 template DefinedRegular *SymbolTable::addAbsolute<ELF64LE>(StringRef, uint8_t,
833                                                            uint8_t);
834 template DefinedRegular *SymbolTable::addAbsolute<ELF64BE>(StringRef, uint8_t,
835                                                            uint8_t);
836 
837 template DefinedRegular *SymbolTable::addIgnored<ELF32LE>(StringRef, uint8_t);
838 template DefinedRegular *SymbolTable::addIgnored<ELF32BE>(StringRef, uint8_t);
839 template DefinedRegular *SymbolTable::addIgnored<ELF64LE>(StringRef, uint8_t);
840 template DefinedRegular *SymbolTable::addIgnored<ELF64BE>(StringRef, uint8_t);
841 
842 template Symbol *
843 SymbolTable::addLazyArchive<ELF32LE>(ArchiveFile *,
844                                      const object::Archive::Symbol);
845 template Symbol *
846 SymbolTable::addLazyArchive<ELF32BE>(ArchiveFile *,
847                                      const object::Archive::Symbol);
848 template Symbol *
849 SymbolTable::addLazyArchive<ELF64LE>(ArchiveFile *,
850                                      const object::Archive::Symbol);
851 template Symbol *
852 SymbolTable::addLazyArchive<ELF64BE>(ArchiveFile *,
853                                      const object::Archive::Symbol);
854 
855 template void SymbolTable::addLazyObject<ELF32LE>(StringRef, LazyObjFile &);
856 template void SymbolTable::addLazyObject<ELF32BE>(StringRef, LazyObjFile &);
857 template void SymbolTable::addLazyObject<ELF64LE>(StringRef, LazyObjFile &);
858 template void SymbolTable::addLazyObject<ELF64BE>(StringRef, LazyObjFile &);
859 
860 template void SymbolTable::addShared<ELF32LE>(SharedFile<ELF32LE> *, StringRef,
861                                               const typename ELF32LE::Sym &,
862                                               const typename ELF32LE::Verdef *);
863 template void SymbolTable::addShared<ELF32BE>(SharedFile<ELF32BE> *, StringRef,
864                                               const typename ELF32BE::Sym &,
865                                               const typename ELF32BE::Verdef *);
866 template void SymbolTable::addShared<ELF64LE>(SharedFile<ELF64LE> *, StringRef,
867                                               const typename ELF64LE::Sym &,
868                                               const typename ELF64LE::Verdef *);
869 template void SymbolTable::addShared<ELF64BE>(SharedFile<ELF64BE> *, StringRef,
870                                               const typename ELF64BE::Sym &,
871                                               const typename ELF64BE::Verdef *);
872 
873 template void SymbolTable::scanUndefinedFlags<ELF32LE>();
874 template void SymbolTable::scanUndefinedFlags<ELF32BE>();
875 template void SymbolTable::scanUndefinedFlags<ELF64LE>();
876 template void SymbolTable::scanUndefinedFlags<ELF64BE>();
877 
878 template void SymbolTable::scanShlibUndefined<ELF32LE>();
879 template void SymbolTable::scanShlibUndefined<ELF32BE>();
880 template void SymbolTable::scanShlibUndefined<ELF64LE>();
881 template void SymbolTable::scanShlibUndefined<ELF64BE>();
882