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