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 "SymbolListFile.h"
22 #include "Symbols.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/Support/StringSaver.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 // All input object files must be for the same architecture
34 // (e.g. it does not make sense to link x86 object files with
35 // MIPS object files.) This function checks for that error.
36 template <class ELFT> static bool isCompatible(InputFile *F) {
37   if (!isa<ELFFileBase<ELFT>>(F) && !isa<BitcodeFile>(F))
38     return true;
39   if (F->EKind == Config->EKind && F->EMachine == Config->EMachine)
40     return true;
41   StringRef A = F->getName();
42   StringRef B = Config->Emulation;
43   if (B.empty())
44     B = Config->FirstElf->getName();
45   error(A + " is incompatible with " + B);
46   return false;
47 }
48 
49 // Add symbols in File to the symbol table.
50 template <class ELFT>
51 void SymbolTable<ELFT>::addFile(std::unique_ptr<InputFile> File) {
52   InputFile *FileP = File.get();
53   if (!isCompatible<ELFT>(FileP))
54     return;
55 
56   // Binary file
57   if (auto *F = dyn_cast<BinaryFile>(FileP)) {
58     BinaryFiles.emplace_back(cast<BinaryFile>(File.release()));
59     addFile(F->createELF<ELFT>());
60     return;
61   }
62 
63   // .a file
64   if (auto *F = dyn_cast<ArchiveFile>(FileP)) {
65     ArchiveFiles.emplace_back(cast<ArchiveFile>(File.release()));
66     F->parse<ELFT>();
67     return;
68   }
69 
70   // Lazy object file
71   if (auto *F = dyn_cast<LazyObjectFile>(FileP)) {
72     LazyObjectFiles.emplace_back(cast<LazyObjectFile>(File.release()));
73     F->parse<ELFT>();
74     return;
75   }
76 
77   if (Config->Trace)
78     outs() << getFilename(FileP) << "\n";
79 
80   // .so file
81   if (auto *F = dyn_cast<SharedFile<ELFT>>(FileP)) {
82     // DSOs are uniquified not by filename but by soname.
83     F->parseSoName();
84     if (!SoNames.insert(F->getSoName()).second)
85       return;
86 
87     SharedFiles.emplace_back(cast<SharedFile<ELFT>>(File.release()));
88     F->parseRest();
89     return;
90   }
91 
92   // LLVM bitcode file
93   if (auto *F = dyn_cast<BitcodeFile>(FileP)) {
94     BitcodeFiles.emplace_back(cast<BitcodeFile>(File.release()));
95     F->parse<ELFT>(ComdatGroups);
96     return;
97   }
98 
99   // Regular object file
100   auto *F = cast<ObjectFile<ELFT>>(FileP);
101   ObjectFiles.emplace_back(cast<ObjectFile<ELFT>>(File.release()));
102   F->parse(ComdatGroups);
103 }
104 
105 // This function is where all the optimizations of link-time
106 // optimization happens. When LTO is in use, some input files are
107 // not in native object file format but in the LLVM bitcode format.
108 // This function compiles bitcode files into a few big native files
109 // using LLVM functions and replaces bitcode symbols with the results.
110 // Because all bitcode files that consist of a program are passed
111 // to the compiler at once, it can do whole-program optimization.
112 template <class ELFT> void SymbolTable<ELFT>::addCombinedLtoObject() {
113   if (BitcodeFiles.empty())
114     return;
115 
116   // Compile bitcode files.
117   Lto.reset(new BitcodeCompiler);
118   for (const std::unique_ptr<BitcodeFile> &F : BitcodeFiles)
119     Lto->add(*F);
120   std::vector<std::unique_ptr<InputFile>> IFs = Lto->compile();
121 
122   // Replace bitcode symbols.
123   for (auto &IF : IFs) {
124     ObjectFile<ELFT> *Obj = cast<ObjectFile<ELFT>>(IF.release());
125 
126     DenseSet<StringRef> DummyGroups;
127     Obj->parse(DummyGroups);
128     ObjectFiles.emplace_back(Obj);
129   }
130 }
131 
132 template <class ELFT>
133 DefinedRegular<ELFT> *SymbolTable<ELFT>::addAbsolute(StringRef Name,
134                                                      uint8_t Visibility) {
135   return cast<DefinedRegular<ELFT>>(
136       addRegular(Name, STB_GLOBAL, Visibility)->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<ELFT> *SymbolTable<ELFT>::addIgnored(StringRef Name,
143                                                     uint8_t Visibility) {
144   if (!find(Name))
145     return nullptr;
146   return addAbsolute(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 template <class ELFT> void SymbolTable<ELFT>::trace(StringRef Name) {
152   Symtab.insert({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<ELFT>::wrap(StringRef Name) {
158   SymbolBody *B = find(Name);
159   if (!B)
160     return;
161   StringSaver Saver(Alloc);
162   Symbol *Sym = B->symbol();
163   Symbol *Real = addUndefined(Saver.save("__real_" + Name));
164   Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name));
165   // We rename symbols by replacing the old symbol's SymbolBody with the new
166   // symbol's SymbolBody. This causes all SymbolBody pointers referring to the
167   // old symbol to instead refer to the new symbol.
168   memcpy(Real->Body.buffer, Sym->Body.buffer, sizeof(Sym->Body));
169   memcpy(Sym->Body.buffer, Wrap->Body.buffer, sizeof(Wrap->Body));
170 }
171 
172 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
173   if (VA == STV_DEFAULT)
174     return VB;
175   if (VB == STV_DEFAULT)
176     return VA;
177   return std::min(VA, VB);
178 }
179 
180 // Parses a symbol in the form of <name>@<version> or <name>@@<version>.
181 static std::pair<StringRef, uint16_t> getSymbolVersion(StringRef S) {
182   if (Config->VersionDefinitions.empty())
183     return {S, Config->DefaultSymbolVersion};
184 
185   size_t Pos = S.find('@');
186   if (Pos == 0 || Pos == StringRef::npos)
187     return {S, Config->DefaultSymbolVersion};
188 
189   StringRef Name = S.substr(0, Pos);
190   StringRef Verstr = S.substr(Pos + 1);
191   if (Verstr.empty())
192     return {S, Config->DefaultSymbolVersion};
193 
194   // '@@' in a symbol name means the default version.
195   // It is usually the most recent one.
196   bool IsDefault = (Verstr[0] == '@');
197   if (IsDefault)
198     Verstr = Verstr.substr(1);
199 
200   for (VersionDefinition &V : Config->VersionDefinitions) {
201     if (V.Name == Verstr)
202       return {Name, IsDefault ? V.Id : (V.Id | VERSYM_HIDDEN)};
203   }
204 
205   // It is an error if the specified version was not defined.
206   error("symbol " + S + " has undefined version " + Verstr);
207   return {S, Config->DefaultSymbolVersion};
208 }
209 
210 // Find an existing symbol or create and insert a new one.
211 template <class ELFT>
212 std::pair<Symbol *, bool> SymbolTable<ELFT>::insert(StringRef &Name) {
213   auto P = Symtab.insert({Name, SymIndex((int)SymVector.size(), false)});
214   SymIndex &V = P.first->second;
215   bool IsNew = P.second;
216 
217   if (V.Idx == -1) {
218     IsNew = true;
219     V = SymIndex((int)SymVector.size(), true);
220   }
221 
222   Symbol *Sym;
223   if (IsNew) {
224     Sym = new (Alloc) Symbol;
225     Sym->Binding = STB_WEAK;
226     Sym->Visibility = STV_DEFAULT;
227     Sym->IsUsedInRegularObj = false;
228     Sym->HasUnnamedAddr = true;
229     Sym->ExportDynamic = false;
230     Sym->Traced = V.Traced;
231     std::tie(Name, Sym->VersionId) = getSymbolVersion(Name);
232     SymVector.push_back(Sym);
233   } else {
234     Sym = SymVector[V.Idx];
235   }
236   return {Sym, IsNew};
237 }
238 
239 // Find an existing symbol or create and insert a new one, then apply the given
240 // attributes.
241 template <class ELFT>
242 std::pair<Symbol *, bool>
243 SymbolTable<ELFT>::insert(StringRef &Name, uint8_t Type, uint8_t Visibility,
244                           bool CanOmitFromDynSym, bool HasUnnamedAddr,
245                           InputFile *File) {
246   bool IsUsedInRegularObj = !File || File->kind() == InputFile::ObjectKind;
247   Symbol *S;
248   bool WasInserted;
249   std::tie(S, WasInserted) = insert(Name);
250 
251   // Merge in the new unnamed_addr attribute.
252   S->HasUnnamedAddr &= HasUnnamedAddr;
253   // Merge in the new symbol's visibility.
254   S->Visibility = getMinVisibility(S->Visibility, Visibility);
255   if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic))
256     S->ExportDynamic = true;
257   if (IsUsedInRegularObj)
258     S->IsUsedInRegularObj = true;
259   if (!WasInserted && S->body()->Type != SymbolBody::UnknownType &&
260       ((Type == STT_TLS) != S->body()->isTls()))
261     error("TLS attribute mismatch for symbol: " +
262           conflictMsg(S->body(), File));
263 
264   return {S, WasInserted};
265 }
266 
267 // Construct a string in the form of "Sym in File1 and File2".
268 // Used to construct an error message.
269 template <typename ELFT>
270 std::string SymbolTable<ELFT>::conflictMsg(SymbolBody *Existing,
271                                            InputFile *NewFile) {
272   std::string Sym = Existing->getName();
273   if (Config->Demangle)
274     Sym = demangle(Sym);
275   return Sym + " in " + getFilename(Existing->File) + " and " +
276          getFilename(NewFile);
277 }
278 
279 template <class ELFT> Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name) {
280   return addUndefined(Name, STB_GLOBAL, STV_DEFAULT, /*Type*/ 0,
281                       /*CanOmitFromDynSym*/ false, /*HasUnnamedAddr*/ false,
282                       /*File*/ nullptr);
283 }
284 
285 template <class ELFT>
286 Symbol *SymbolTable<ELFT>::addUndefined(StringRef Name, uint8_t Binding,
287                                         uint8_t StOther, uint8_t Type,
288                                         bool CanOmitFromDynSym,
289                                         bool HasUnnamedAddr, InputFile *File) {
290   Symbol *S;
291   bool WasInserted;
292   std::tie(S, WasInserted) =
293       insert(Name, Type, StOther & 3, CanOmitFromDynSym, HasUnnamedAddr, File);
294   if (WasInserted) {
295     S->Binding = Binding;
296     replaceBody<Undefined>(S, Name, StOther, Type, File);
297     return S;
298   }
299   if (Binding != STB_WEAK) {
300     if (S->body()->isShared() || S->body()->isLazy())
301       S->Binding = Binding;
302     if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(S->body()))
303       SS->file()->IsUsed = true;
304   }
305   if (auto *L = dyn_cast<Lazy>(S->body())) {
306     // An undefined weak will not fetch archive members, but we have to remember
307     // its type. See also comment in addLazyArchive.
308     if (S->isWeak())
309       L->Type = Type;
310     else if (auto F = L->fetch())
311       addFile(std::move(F));
312   }
313   return S;
314 }
315 
316 // We have a new defined symbol with the specified binding. Return 1 if the new
317 // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are
318 // strong defined symbols.
319 static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding) {
320   if (WasInserted)
321     return 1;
322   SymbolBody *Body = S->body();
323   if (Body->isLazy() || Body->isUndefined() || Body->isShared())
324     return 1;
325   if (Binding == STB_WEAK)
326     return -1;
327   if (S->isWeak())
328     return 1;
329   return 0;
330 }
331 
332 // We have a new non-common defined symbol with the specified binding. Return 1
333 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there
334 // is a conflict. If the new symbol wins, also update the binding.
335 static int compareDefinedNonCommon(Symbol *S, bool WasInserted,
336                                    uint8_t Binding) {
337   if (int Cmp = compareDefined(S, WasInserted, Binding)) {
338     if (Cmp > 0)
339       S->Binding = Binding;
340     return Cmp;
341   }
342   if (isa<DefinedCommon>(S->body())) {
343     // Non-common symbols take precedence over common symbols.
344     if (Config->WarnCommon)
345       warning("common " + S->body()->getName() + " is overridden");
346     return 1;
347   }
348   return 0;
349 }
350 
351 template <class ELFT>
352 Symbol *SymbolTable<ELFT>::addCommon(StringRef N, uint64_t Size,
353                                      uint64_t Alignment, uint8_t Binding,
354                                      uint8_t StOther, uint8_t Type,
355                                      bool HasUnnamedAddr, InputFile *File) {
356   Symbol *S;
357   bool WasInserted;
358   std::tie(S, WasInserted) = insert(
359       N, Type, StOther & 3, /*CanOmitFromDynSym*/ false, HasUnnamedAddr, File);
360   int Cmp = compareDefined(S, WasInserted, Binding);
361   if (Cmp > 0) {
362     S->Binding = Binding;
363     replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
364   } else if (Cmp == 0) {
365     auto *C = dyn_cast<DefinedCommon>(S->body());
366     if (!C) {
367       // Non-common symbols take precedence over common symbols.
368       if (Config->WarnCommon)
369         warning("common " + S->body()->getName() + " is overridden");
370       return S;
371     }
372 
373     if (Config->WarnCommon)
374       warning("multiple common of " + S->body()->getName());
375 
376     Alignment = C->Alignment = std::max(C->Alignment, Alignment);
377     if (Size > C->Size)
378       replaceBody<DefinedCommon>(S, N, Size, Alignment, StOther, Type, File);
379   }
380   return S;
381 }
382 
383 template <class ELFT>
384 void SymbolTable<ELFT>::reportDuplicate(SymbolBody *Existing,
385                                         InputFile *NewFile) {
386   std::string Msg = "duplicate symbol: " + conflictMsg(Existing, NewFile);
387   if (Config->AllowMultipleDefinition)
388     warning(Msg);
389   else
390     error(Msg);
391 }
392 
393 template <typename ELFT>
394 Symbol *SymbolTable<ELFT>::addRegular(StringRef Name, const Elf_Sym &Sym,
395                                       InputSectionBase<ELFT> *Section) {
396   Symbol *S;
397   bool WasInserted;
398   std::tie(S, WasInserted) =
399       insert(Name, Sym.getType(), Sym.getVisibility(),
400              /*CanOmitFromDynSym*/ false, /*HasUnnamedAddr*/ false,
401              Section ? Section->getFile() : nullptr);
402   int Cmp = compareDefinedNonCommon(S, WasInserted, Sym.getBinding());
403   if (Cmp > 0)
404     replaceBody<DefinedRegular<ELFT>>(S, Name, Sym, Section);
405   else if (Cmp == 0)
406     reportDuplicate(S->body(), Section->getFile());
407   return S;
408 }
409 
410 template <typename ELFT>
411 Symbol *SymbolTable<ELFT>::addRegular(StringRef Name, uint8_t Binding,
412                                       uint8_t StOther) {
413   Symbol *S;
414   bool WasInserted;
415   std::tie(S, WasInserted) =
416       insert(Name, STT_NOTYPE, StOther & 3, /*CanOmitFromDynSym*/ false,
417              /*HasUnnamedAddr*/ false, nullptr);
418   int Cmp = compareDefinedNonCommon(S, WasInserted, Binding);
419   if (Cmp > 0)
420     replaceBody<DefinedRegular<ELFT>>(S, Name, StOther);
421   else if (Cmp == 0)
422     reportDuplicate(S->body(), nullptr);
423   return S;
424 }
425 
426 template <typename ELFT>
427 Symbol *SymbolTable<ELFT>::addSynthetic(StringRef N,
428                                         OutputSectionBase<ELFT> *Section,
429                                         uintX_t Value, uint8_t StOther) {
430   Symbol *S;
431   bool WasInserted;
432   std::tie(S, WasInserted) = insert(N, STT_NOTYPE, /*Visibility*/ StOther & 0x3,
433                                     /*CanOmitFromDynSym*/ false,
434                                     /*HasUnnamedAddr*/ false, nullptr);
435   int Cmp = compareDefinedNonCommon(S, WasInserted, STB_GLOBAL);
436   if (Cmp > 0)
437     replaceBody<DefinedSynthetic<ELFT>>(S, N, Value, Section);
438   else if (Cmp == 0)
439     reportDuplicate(S->body(), nullptr);
440   return S;
441 }
442 
443 template <typename ELFT>
444 void SymbolTable<ELFT>::addShared(SharedFile<ELFT> *F, StringRef Name,
445                                   const Elf_Sym &Sym,
446                                   const typename ELFT::Verdef *Verdef) {
447   // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT
448   // as the visibility, which will leave the visibility in the symbol table
449   // unchanged.
450   Symbol *S;
451   bool WasInserted;
452   std::tie(S, WasInserted) =
453       insert(Name, Sym.getType(), STV_DEFAULT, /*CanOmitFromDynSym*/ true,
454              /*HasUnnamedAddr*/ false, F);
455   // Make sure we preempt DSO symbols with default visibility.
456   if (Sym.getVisibility() == STV_DEFAULT)
457     S->ExportDynamic = true;
458   if (WasInserted || isa<Undefined>(S->body())) {
459     replaceBody<SharedSymbol<ELFT>>(S, F, Name, Sym, Verdef);
460     if (!S->isWeak())
461       F->IsUsed = true;
462   }
463 }
464 
465 template <class ELFT>
466 Symbol *SymbolTable<ELFT>::addBitcode(StringRef Name, uint8_t Binding,
467                                       uint8_t StOther, uint8_t Type,
468                                       bool CanOmitFromDynSym,
469                                       bool HasUnnamedAddr, BitcodeFile *F) {
470   Symbol *S;
471   bool WasInserted;
472   std::tie(S, WasInserted) =
473       insert(Name, Type, StOther & 3, CanOmitFromDynSym, HasUnnamedAddr, F);
474   int Cmp = compareDefinedNonCommon(S, WasInserted, Binding);
475   if (Cmp > 0)
476     replaceBody<DefinedRegular<ELFT>>(S, Name, StOther, Type, F);
477   else if (Cmp == 0)
478     reportDuplicate(S->body(), F);
479   return S;
480 }
481 
482 template <class ELFT> SymbolBody *SymbolTable<ELFT>::find(StringRef Name) {
483   auto It = Symtab.find(Name);
484   if (It == Symtab.end())
485     return nullptr;
486   SymIndex V = It->second;
487   if (V.Idx == -1)
488     return nullptr;
489   return SymVector[V.Idx]->body();
490 }
491 
492 // Returns a list of defined symbols that match with a given regex.
493 template <class ELFT>
494 std::vector<SymbolBody *> SymbolTable<ELFT>::findAll(const Regex &Re) {
495   std::vector<SymbolBody *> Res;
496   for (Symbol *Sym : SymVector) {
497     SymbolBody *B = Sym->body();
498     StringRef Name = B->getName();
499     if (!B->isUndefined() && const_cast<Regex &>(Re).match(Name))
500       Res.push_back(B);
501   }
502   return Res;
503 }
504 
505 template <class ELFT>
506 void SymbolTable<ELFT>::addLazyArchive(ArchiveFile *F,
507                                        const object::Archive::Symbol Sym) {
508   Symbol *S;
509   bool WasInserted;
510   StringRef Name = Sym.getName();
511   std::tie(S, WasInserted) = insert(Name);
512   if (WasInserted) {
513     replaceBody<LazyArchive>(S, *F, Sym, SymbolBody::UnknownType);
514     return;
515   }
516   if (!S->body()->isUndefined())
517     return;
518 
519   // Weak undefined symbols should not fetch members from archives. If we were
520   // to keep old symbol we would not know that an archive member was available
521   // if a strong undefined symbol shows up afterwards in the link. If a strong
522   // undefined symbol never shows up, this lazy symbol will get to the end of
523   // the link and must be treated as the weak undefined one. We already marked
524   // this symbol as used when we added it to the symbol table, but we also need
525   // to preserve its type. FIXME: Move the Type field to Symbol.
526   if (S->isWeak()) {
527     replaceBody<LazyArchive>(S, *F, Sym, S->body()->Type);
528     return;
529   }
530   MemoryBufferRef MBRef = F->getMember(&Sym);
531   if (!MBRef.getBuffer().empty())
532     addFile(createObjectFile(MBRef, F->getName()));
533 }
534 
535 template <class ELFT>
536 void SymbolTable<ELFT>::addLazyObject(StringRef Name, LazyObjectFile &Obj) {
537   Symbol *S;
538   bool WasInserted;
539   std::tie(S, WasInserted) = insert(Name);
540   if (WasInserted) {
541     replaceBody<LazyObject>(S, Name, Obj, SymbolBody::UnknownType);
542     return;
543   }
544   if (!S->body()->isUndefined())
545     return;
546 
547   // See comment for addLazyArchive above.
548   if (S->isWeak()) {
549     replaceBody<LazyObject>(S, Name, Obj, S->body()->Type);
550   } else {
551     MemoryBufferRef MBRef = Obj.getBuffer();
552     if (!MBRef.getBuffer().empty())
553       addFile(createObjectFile(MBRef));
554   }
555 }
556 
557 // Process undefined (-u) flags by loading lazy symbols named by those flags.
558 template <class ELFT> void SymbolTable<ELFT>::scanUndefinedFlags() {
559   for (StringRef S : Config->Undefined)
560     if (auto *L = dyn_cast_or_null<Lazy>(find(S)))
561       if (std::unique_ptr<InputFile> File = L->fetch())
562         addFile(std::move(File));
563 }
564 
565 // This function takes care of the case in which shared libraries depend on
566 // the user program (not the other way, which is usual). Shared libraries
567 // may have undefined symbols, expecting that the user program provides
568 // the definitions for them. An example is BSD's __progname symbol.
569 // We need to put such symbols to the main program's .dynsym so that
570 // shared libraries can find them.
571 // Except this, we ignore undefined symbols in DSOs.
572 template <class ELFT> void SymbolTable<ELFT>::scanShlibUndefined() {
573   for (std::unique_ptr<SharedFile<ELFT>> &File : SharedFiles)
574     for (StringRef U : File->getUndefinedSymbols())
575       if (SymbolBody *Sym = find(U))
576         if (Sym->isDefined())
577           Sym->symbol()->ExportDynamic = true;
578 }
579 
580 // This function processes --export-dynamic-symbol and --dynamic-list.
581 template <class ELFT> void SymbolTable<ELFT>::scanDynamicList() {
582   for (StringRef S : Config->DynamicList)
583     if (SymbolBody *B = find(S))
584       B->symbol()->ExportDynamic = true;
585 }
586 
587 static void setVersionId(SymbolBody *Body, StringRef VersionName,
588                          StringRef Name, uint16_t Version) {
589   if (!Body || Body->isUndefined()) {
590     if (Config->NoUndefinedVersion)
591       error("version script assignment of " + VersionName + " to symbol " +
592             Name + " failed: symbol not defined");
593     return;
594   }
595 
596   Symbol *Sym = Body->symbol();
597   if (Sym->VersionId != Config->DefaultSymbolVersion)
598     warning("duplicate symbol " + Name + " in version script");
599   Sym->VersionId = Version;
600 }
601 
602 template <class ELFT>
603 std::map<std::string, SymbolBody *> SymbolTable<ELFT>::getDemangledSyms() {
604   std::map<std::string, SymbolBody *> Result;
605   for (Symbol *Sym : SymVector) {
606     SymbolBody *B = Sym->body();
607     Result[demangle(B->getName())] = B;
608   }
609   return Result;
610 }
611 
612 static bool hasExternCpp() {
613   for (VersionDefinition &V : Config->VersionDefinitions)
614     for (SymbolVersion Sym : V.Globals)
615       if (Sym.IsExternCpp)
616         return true;
617   return false;
618 }
619 
620 static SymbolBody *findDemangled(const std::map<std::string, SymbolBody *> &D,
621                                  StringRef Name) {
622   auto I = D.find(Name);
623   if (I != D.end())
624     return I->second;
625   return nullptr;
626 }
627 
628 static std::vector<SymbolBody *>
629 findAllDemangled(const std::map<std::string, SymbolBody *> &D,
630                  const Regex &Re) {
631   std::vector<SymbolBody *> Res;
632   for (auto &P : D) {
633     SymbolBody *Body = P.second;
634     if (!Body->isUndefined() && const_cast<Regex &>(Re).match(P.first))
635       Res.push_back(Body);
636   }
637   return Res;
638 }
639 
640 // This function processes version scripts by updating VersionId
641 // member of symbols.
642 template <class ELFT> void SymbolTable<ELFT>::scanVersionScript() {
643   // If there's only one anonymous version definition in a version
644   // script file, the script does not actullay define any symbol version,
645   // but just specifies symbols visibilities. We assume that the script was
646   // in the form of { global: foo; bar; local *; }. So, local is default.
647   // Here, we make specified symbols global.
648   if (!Config->VersionScriptGlobals.empty()) {
649     std::vector<StringRef> Globs;
650     for (SymbolVersion &Sym : Config->VersionScriptGlobals) {
651       if (hasWildcard(Sym.Name)) {
652         Globs.push_back(Sym.Name);
653         continue;
654       }
655       if (SymbolBody *B = find(Sym.Name))
656         B->symbol()->VersionId = VER_NDX_GLOBAL;
657     }
658     if (Globs.empty())
659       return;
660     Regex Re = compileGlobPatterns(Globs);
661     std::vector<SymbolBody *> Syms = findAll(Re);
662     for (SymbolBody *B : Syms)
663       B->symbol()->VersionId = VER_NDX_GLOBAL;
664     return;
665   }
666 
667   if (Config->VersionDefinitions.empty())
668     return;
669 
670   // Now we have version definitions, so we need to set version ids to symbols.
671   // Each version definition has a glob pattern, and all symbols that match
672   // with the pattern get that version.
673 
674   // Users can use "extern C++ {}" directive to match against demangled
675   // C++ symbols. For example, you can write a pattern such as
676   // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
677   // other than trying to match a regexp against all demangled symbols.
678   // So, if "extern C++" feature is used, we demangle all known symbols.
679   std::map<std::string, SymbolBody *> Demangled;
680   if (hasExternCpp())
681     Demangled = getDemangledSyms();
682 
683   // First, we assign versions to exact matching symbols,
684   // i.e. version definitions not containing any glob meta-characters.
685   for (VersionDefinition &V : Config->VersionDefinitions) {
686     for (SymbolVersion Sym : V.Globals) {
687       if (Sym.HasWildcards)
688         continue;
689       StringRef N = Sym.Name;
690       SymbolBody *B = Sym.IsExternCpp ? findDemangled(Demangled, N) : find(N);
691       setVersionId(B, V.Name, N, V.Id);
692     }
693   }
694 
695   // Next, we assign versions to fuzzy matching symbols,
696   // i.e. version definitions containing glob meta-characters.
697   // Note that because the last match takes precedence over previous matches,
698   // we iterate over the definitions in the reverse order.
699   for (size_t I = Config->VersionDefinitions.size() - 1; I != (size_t)-1; --I) {
700     VersionDefinition &V = Config->VersionDefinitions[I];
701     for (SymbolVersion &Sym : V.Globals) {
702       if (!Sym.HasWildcards)
703         continue;
704       Regex Re = compileGlobPatterns({Sym.Name});
705       std::vector<SymbolBody *> Syms =
706           Sym.IsExternCpp ? findAllDemangled(Demangled, Re) : findAll(Re);
707 
708       // Exact matching takes precendence over fuzzy matching,
709       // so we set a version to a symbol only if no version has been assigned
710       // to the symbol. This behavior is compatible with GNU.
711       for (SymbolBody *B : Syms)
712         if (B->symbol()->VersionId == Config->DefaultSymbolVersion)
713           B->symbol()->VersionId = V.Id;
714     }
715   }
716 }
717 
718 template class elf::SymbolTable<ELF32LE>;
719 template class elf::SymbolTable<ELF32BE>;
720 template class elf::SymbolTable<ELF64LE>;
721 template class elf::SymbolTable<ELF64BE>;
722