1 //===- SymbolTable.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolTable.h"
10 #include "ConcatOutputSection.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "Symbols.h"
15 #include "SyntheticSections.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Memory.h"
18 
19 using namespace llvm;
20 using namespace lld;
21 using namespace lld::macho;
22 
23 Symbol *SymbolTable::find(CachedHashStringRef cachedName) {
24   auto it = symMap.find(cachedName);
25   if (it == symMap.end())
26     return nullptr;
27   return symVector[it->second];
28 }
29 
30 std::pair<Symbol *, bool> SymbolTable::insert(StringRef name,
31                                               const InputFile *file) {
32   auto p = symMap.insert({CachedHashStringRef(name), (int)symVector.size()});
33 
34   Symbol *sym;
35   if (!p.second) {
36     // Name already present in the symbol table.
37     sym = symVector[p.first->second];
38   } else {
39     // Name is a new symbol.
40     sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
41     symVector.push_back(sym);
42   }
43 
44   sym->isUsedInRegularObj |= !file || isa<ObjFile>(file);
45   return {sym, p.second};
46 }
47 
48 Defined *SymbolTable::addDefined(StringRef name, InputFile *file,
49                                  InputSection *isec, uint64_t value,
50                                  uint64_t size, bool isWeakDef,
51                                  bool isPrivateExtern, bool isThumb,
52                                  bool isReferencedDynamically, bool noDeadStrip,
53                                  bool isWeakDefCanBeHidden) {
54   Symbol *s;
55   bool wasInserted;
56   bool overridesWeakDef = false;
57   std::tie(s, wasInserted) = insert(name, file);
58 
59   assert(!isWeakDef || (isa<BitcodeFile>(file) && !isec) ||
60          (isa<ObjFile>(file) && file == isec->getFile()));
61 
62   if (!wasInserted) {
63     if (auto *defined = dyn_cast<Defined>(s)) {
64       if (isWeakDef) {
65         // See further comment in createDefined() in InputFiles.cpp
66         if (defined->isWeakDef()) {
67           defined->privateExtern &= isPrivateExtern;
68           defined->weakDefCanBeHidden &= isWeakDefCanBeHidden;
69           defined->referencedDynamically |= isReferencedDynamically;
70           defined->noDeadStrip |= noDeadStrip;
71         }
72         // FIXME: Handle this for bitcode files.
73         if (auto concatIsec = dyn_cast_or_null<ConcatInputSection>(isec))
74           concatIsec->wasCoalesced = true;
75         return defined;
76       }
77 
78       if (defined->isWeakDef()) {
79         // FIXME: Handle this for bitcode files.
80         if (auto concatIsec =
81                 dyn_cast_or_null<ConcatInputSection>(defined->isec)) {
82           concatIsec->wasCoalesced = true;
83           concatIsec->symbols.erase(llvm::find(concatIsec->symbols, defined));
84         }
85       } else {
86         error("duplicate symbol: " + name + "\n>>> defined in " +
87               toString(defined->getFile()) + "\n>>> defined in " +
88               toString(file));
89       }
90 
91     } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
92       overridesWeakDef = !isWeakDef && dysym->isWeakDef();
93       dysym->unreference();
94     }
95     // Defined symbols take priority over other types of symbols, so in case
96     // of a name conflict, we fall through to the replaceSymbol() call below.
97   }
98 
99   Defined *defined = replaceSymbol<Defined>(
100       s, name, file, isec, value, size, isWeakDef, /*isExternal=*/true,
101       isPrivateExtern, isThumb, isReferencedDynamically, noDeadStrip,
102       overridesWeakDef, isWeakDefCanBeHidden);
103   return defined;
104 }
105 
106 Symbol *SymbolTable::addUndefined(StringRef name, InputFile *file,
107                                   bool isWeakRef) {
108   Symbol *s;
109   bool wasInserted;
110   std::tie(s, wasInserted) = insert(name, file);
111 
112   RefState refState = isWeakRef ? RefState::Weak : RefState::Strong;
113 
114   if (wasInserted)
115     replaceSymbol<Undefined>(s, name, file, refState);
116   else if (auto *lazy = dyn_cast<LazyArchive>(s))
117     lazy->fetchArchiveMember();
118   else if (isa<LazyObject>(s))
119     extract(*s->getFile(), s->getName());
120   else if (auto *dynsym = dyn_cast<DylibSymbol>(s))
121     dynsym->reference(refState);
122   else if (auto *undefined = dyn_cast<Undefined>(s))
123     undefined->refState = std::max(undefined->refState, refState);
124   return s;
125 }
126 
127 Symbol *SymbolTable::addCommon(StringRef name, InputFile *file, uint64_t size,
128                                uint32_t align, bool isPrivateExtern) {
129   Symbol *s;
130   bool wasInserted;
131   std::tie(s, wasInserted) = insert(name, file);
132 
133   if (!wasInserted) {
134     if (auto *common = dyn_cast<CommonSymbol>(s)) {
135       if (size < common->size)
136         return s;
137     } else if (isa<Defined>(s)) {
138       return s;
139     }
140     // Common symbols take priority over all non-Defined symbols, so in case of
141     // a name conflict, we fall through to the replaceSymbol() call below.
142   }
143 
144   replaceSymbol<CommonSymbol>(s, name, file, size, align, isPrivateExtern);
145   return s;
146 }
147 
148 Symbol *SymbolTable::addDylib(StringRef name, DylibFile *file, bool isWeakDef,
149                               bool isTlv) {
150   Symbol *s;
151   bool wasInserted;
152   std::tie(s, wasInserted) = insert(name, file);
153 
154   RefState refState = RefState::Unreferenced;
155   if (!wasInserted) {
156     if (auto *defined = dyn_cast<Defined>(s)) {
157       if (isWeakDef && !defined->isWeakDef())
158         defined->overridesWeakDef = true;
159     } else if (auto *undefined = dyn_cast<Undefined>(s)) {
160       refState = undefined->refState;
161     } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
162       refState = dysym->getRefState();
163     }
164   }
165 
166   bool isDynamicLookup = file == nullptr;
167   if (wasInserted || isa<Undefined>(s) ||
168       (isa<DylibSymbol>(s) &&
169        ((!isWeakDef && s->isWeakDef()) ||
170         (!isDynamicLookup && cast<DylibSymbol>(s)->isDynamicLookup())))) {
171     if (auto *dynsym = dyn_cast<DylibSymbol>(s))
172       dynsym->unreference();
173     replaceSymbol<DylibSymbol>(s, file, name, isWeakDef, refState, isTlv);
174   }
175 
176   return s;
177 }
178 
179 Symbol *SymbolTable::addDynamicLookup(StringRef name) {
180   return addDylib(name, /*file=*/nullptr, /*isWeakDef=*/false, /*isTlv=*/false);
181 }
182 
183 Symbol *SymbolTable::addLazyArchive(StringRef name, ArchiveFile *file,
184                                     const object::Archive::Symbol &sym) {
185   Symbol *s;
186   bool wasInserted;
187   std::tie(s, wasInserted) = insert(name, file);
188 
189   if (wasInserted) {
190     replaceSymbol<LazyArchive>(s, file, sym);
191   } else if (isa<Undefined>(s)) {
192     file->fetch(sym);
193   } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
194     if (dysym->isWeakDef()) {
195       if (dysym->getRefState() != RefState::Unreferenced)
196         file->fetch(sym);
197       else
198         replaceSymbol<LazyArchive>(s, file, sym);
199     }
200   }
201   return s;
202 }
203 
204 Symbol *SymbolTable::addLazyObject(StringRef name, InputFile &file) {
205   Symbol *s;
206   bool wasInserted;
207   std::tie(s, wasInserted) = insert(name, &file);
208 
209   if (wasInserted) {
210     replaceSymbol<LazyObject>(s, file, name);
211   } else if (isa<Undefined>(s)) {
212     extract(file, name);
213   } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
214     if (dysym->isWeakDef()) {
215       if (dysym->getRefState() != RefState::Unreferenced)
216         extract(file, name);
217       else
218         replaceSymbol<LazyObject>(s, file, name);
219     }
220   }
221   return s;
222 }
223 
224 Defined *SymbolTable::addSynthetic(StringRef name, InputSection *isec,
225                                    uint64_t value, bool isPrivateExtern,
226                                    bool includeInSymtab,
227                                    bool referencedDynamically) {
228   Defined *s =
229       addDefined(name, nullptr, isec, value, /*size=*/0,
230                  /*isWeakDef=*/false, isPrivateExtern,
231                  /*isThumb=*/false, referencedDynamically,
232                  /*noDeadStrip=*/false, /*isWeakDefCanBeHidden=*/false);
233   s->includeInSymtab = includeInSymtab;
234   return s;
235 }
236 
237 enum class Boundary {
238   Start,
239   End,
240 };
241 
242 static Defined *createBoundarySymbol(const Undefined &sym) {
243   return symtab->addSynthetic(
244       sym.getName(), /*isec=*/nullptr, /*value=*/-1, /*isPrivateExtern=*/true,
245       /*includeInSymtab=*/false, /*referencedDynamically=*/false);
246 }
247 
248 static void handleSectionBoundarySymbol(const Undefined &sym, StringRef segSect,
249                                         Boundary which) {
250   StringRef segName, sectName;
251   std::tie(segName, sectName) = segSect.split('$');
252 
253   // Attach the symbol to any InputSection that will end up in the right
254   // OutputSection -- it doesn't matter which one we pick.
255   // Don't bother looking through inputSections for a matching
256   // ConcatInputSection -- we need to create ConcatInputSection for
257   // non-existing sections anyways, and that codepath works even if we should
258   // already have a ConcatInputSection with the right name.
259 
260   OutputSection *osec = nullptr;
261   // This looks for __TEXT,__cstring etc.
262   for (SyntheticSection *ssec : syntheticSections)
263     if (ssec->segname == segName && ssec->name == sectName) {
264       osec = ssec->isec->parent;
265       break;
266     }
267 
268   if (!osec) {
269     ConcatInputSection *isec = make<ConcatInputSection>(segName, sectName);
270 
271     // This runs after markLive() and is only called for Undefineds that are
272     // live. Marking the isec live ensures an OutputSection is created that the
273     // start/end symbol can refer to.
274     assert(sym.isLive());
275     isec->live = true;
276 
277     // This runs after gatherInputSections(), so need to explicitly set parent
278     // and add to inputSections.
279     osec = isec->parent = ConcatOutputSection::getOrCreateForInput(isec);
280     inputSections.push_back(isec);
281   }
282 
283   if (which == Boundary::Start)
284     osec->sectionStartSymbols.push_back(createBoundarySymbol(sym));
285   else
286     osec->sectionEndSymbols.push_back(createBoundarySymbol(sym));
287 }
288 
289 static void handleSegmentBoundarySymbol(const Undefined &sym, StringRef segName,
290                                         Boundary which) {
291   OutputSegment *seg = getOrCreateOutputSegment(segName);
292   if (which == Boundary::Start)
293     seg->segmentStartSymbols.push_back(createBoundarySymbol(sym));
294   else
295     seg->segmentEndSymbols.push_back(createBoundarySymbol(sym));
296 }
297 
298 void lld::macho::treatUndefinedSymbol(const Undefined &sym, StringRef source) {
299   // Handle start/end symbols.
300   StringRef name = sym.getName();
301   if (name.consume_front("section$start$"))
302     return handleSectionBoundarySymbol(sym, name, Boundary::Start);
303   if (name.consume_front("section$end$"))
304     return handleSectionBoundarySymbol(sym, name, Boundary::End);
305   if (name.consume_front("segment$start$"))
306     return handleSegmentBoundarySymbol(sym, name, Boundary::Start);
307   if (name.consume_front("segment$end$"))
308     return handleSegmentBoundarySymbol(sym, name, Boundary::End);
309 
310   // Handle -U.
311   if (config->explicitDynamicLookups.count(sym.getName())) {
312     symtab->addDynamicLookup(sym.getName());
313     return;
314   }
315 
316   // Handle -undefined.
317   auto message = [source, &sym]() {
318     std::string message = "undefined symbol";
319     if (config->archMultiple)
320       message += (" for arch " + getArchitectureName(config->arch())).str();
321     message += ": " + toString(sym);
322     if (!source.empty())
323       message += "\n>>> referenced by " + source.str();
324     else
325       message += "\n>>> referenced by " + toString(sym.getFile());
326     return message;
327   };
328   switch (config->undefinedSymbolTreatment) {
329   case UndefinedSymbolTreatment::error:
330     error(message());
331     break;
332   case UndefinedSymbolTreatment::warning:
333     warn(message());
334     LLVM_FALLTHROUGH;
335   case UndefinedSymbolTreatment::dynamic_lookup:
336   case UndefinedSymbolTreatment::suppress:
337     symtab->addDynamicLookup(sym.getName());
338     break;
339   case UndefinedSymbolTreatment::unknown:
340     llvm_unreachable("unknown -undefined TREATMENT");
341   }
342 }
343 
344 std::unique_ptr<SymbolTable> macho::symtab;
345