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,
53                                  bool noDeadStrip) {
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 
66         // See further comment in createDefined() in InputFiles.cpp
67         if (defined->isWeakDef()) {
68           defined->privateExtern &= isPrivateExtern;
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   defined->overridesWeakDef = overridesWeakDef;
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<LazySymbol>(s))
117     lazy->fetchArchiveMember();
118   else if (auto *dynsym = dyn_cast<DylibSymbol>(s))
119     dynsym->reference(refState);
120   else if (auto *undefined = dyn_cast<Undefined>(s))
121     undefined->refState = std::max(undefined->refState, refState);
122   return s;
123 }
124 
125 Symbol *SymbolTable::addCommon(StringRef name, InputFile *file, uint64_t size,
126                                uint32_t align, bool isPrivateExtern) {
127   Symbol *s;
128   bool wasInserted;
129   std::tie(s, wasInserted) = insert(name, file);
130 
131   if (!wasInserted) {
132     if (auto *common = dyn_cast<CommonSymbol>(s)) {
133       if (size < common->size)
134         return s;
135     } else if (isa<Defined>(s)) {
136       return s;
137     }
138     // Common symbols take priority over all non-Defined symbols, so in case of
139     // a name conflict, we fall through to the replaceSymbol() call below.
140   }
141 
142   replaceSymbol<CommonSymbol>(s, name, file, size, align, isPrivateExtern);
143   return s;
144 }
145 
146 Symbol *SymbolTable::addDylib(StringRef name, DylibFile *file, bool isWeakDef,
147                               bool isTlv) {
148   Symbol *s;
149   bool wasInserted;
150   std::tie(s, wasInserted) = insert(name, file);
151 
152   RefState refState = RefState::Unreferenced;
153   if (!wasInserted) {
154     if (auto *defined = dyn_cast<Defined>(s)) {
155       if (isWeakDef && !defined->isWeakDef())
156         defined->overridesWeakDef = true;
157     } else if (auto *undefined = dyn_cast<Undefined>(s)) {
158       refState = undefined->refState;
159     } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
160       refState = dysym->getRefState();
161     }
162   }
163 
164   bool isDynamicLookup = file == nullptr;
165   if (wasInserted || isa<Undefined>(s) ||
166       (isa<DylibSymbol>(s) &&
167        ((!isWeakDef && s->isWeakDef()) ||
168         (!isDynamicLookup && cast<DylibSymbol>(s)->isDynamicLookup())))) {
169     if (auto *dynsym = dyn_cast<DylibSymbol>(s))
170       dynsym->unreference();
171     replaceSymbol<DylibSymbol>(s, file, name, isWeakDef, refState, isTlv);
172   }
173 
174   return s;
175 }
176 
177 Symbol *SymbolTable::addDynamicLookup(StringRef name) {
178   return addDylib(name, /*file=*/nullptr, /*isWeakDef=*/false, /*isTlv=*/false);
179 }
180 
181 Symbol *SymbolTable::addLazy(StringRef name, ArchiveFile *file,
182                              const object::Archive::Symbol &sym) {
183   Symbol *s;
184   bool wasInserted;
185   std::tie(s, wasInserted) = insert(name, file);
186 
187   if (wasInserted)
188     replaceSymbol<LazySymbol>(s, file, sym);
189   else if (isa<Undefined>(s) || (isa<DylibSymbol>(s) && s->isWeakDef()))
190     file->fetch(sym);
191   return s;
192 }
193 
194 Defined *SymbolTable::addSynthetic(StringRef name, InputSection *isec,
195                                    uint64_t value, bool isPrivateExtern,
196                                    bool includeInSymtab,
197                                    bool referencedDynamically) {
198   Defined *s = addDefined(name, nullptr, isec, value, /*size=*/0,
199                           /*isWeakDef=*/false, isPrivateExtern,
200                           /*isThumb=*/false, referencedDynamically,
201                           /*noDeadStrip=*/false);
202   s->includeInSymtab = includeInSymtab;
203   return s;
204 }
205 
206 enum class Boundary {
207   Start,
208   End,
209 };
210 
211 static Defined *createBoundarySymbol(const Undefined &sym) {
212   return symtab->addSynthetic(
213       sym.getName(), /*isec=*/nullptr, /*value=*/-1, /*isPrivateExtern=*/true,
214       /*includeInSymtab=*/false, /*referencedDynamically=*/false);
215 }
216 
217 static void handleSectionBoundarySymbol(const Undefined &sym, StringRef segSect,
218                                         Boundary which) {
219   StringRef segName, sectName;
220   std::tie(segName, sectName) = segSect.split('$');
221 
222   // Attach the symbol to any InputSection that will end up in the right
223   // OutputSection -- it doesn't matter which one we pick.
224   // Don't bother looking through inputSections for a matching
225   // ConcatInputSection -- we need to create ConcatInputSection for
226   // non-existing sections anyways, and that codepath works even if we should
227   // already have a ConcatInputSection with the right name.
228 
229   OutputSection *osec = nullptr;
230   // This looks for __TEXT,__cstring etc.
231   for (SyntheticSection *ssec : syntheticSections)
232     if (ssec->segname == segName && ssec->name == sectName) {
233       osec = ssec->isec->parent;
234       break;
235     }
236 
237   if (!osec) {
238     ConcatInputSection *isec = make<ConcatInputSection>(segName, sectName);
239 
240     // This runs after markLive() and is only called for Undefineds that are
241     // live. Marking the isec live ensures an OutputSection is created that the
242     // start/end symbol can refer to.
243     assert(sym.isLive());
244     isec->live = true;
245 
246     // This runs after gatherInputSections(), so need to explicitly set parent
247     // and add to inputSections.
248     osec = isec->parent = ConcatOutputSection::getOrCreateForInput(isec);
249     inputSections.push_back(isec);
250   }
251 
252   if (which == Boundary::Start)
253     osec->sectionStartSymbols.push_back(createBoundarySymbol(sym));
254   else
255     osec->sectionEndSymbols.push_back(createBoundarySymbol(sym));
256 }
257 
258 static void handleSegmentBoundarySymbol(const Undefined &sym, StringRef segName,
259                                         Boundary which) {
260   OutputSegment *seg = getOrCreateOutputSegment(segName);
261   if (which == Boundary::Start)
262     seg->segmentStartSymbols.push_back(createBoundarySymbol(sym));
263   else
264     seg->segmentEndSymbols.push_back(createBoundarySymbol(sym));
265 }
266 
267 void lld::macho::treatUndefinedSymbol(const Undefined &sym, StringRef source) {
268   // Handle start/end symbols.
269   StringRef name = sym.getName();
270   if (name.consume_front("section$start$"))
271     return handleSectionBoundarySymbol(sym, name, Boundary::Start);
272   if (name.consume_front("section$end$"))
273     return handleSectionBoundarySymbol(sym, name, Boundary::End);
274   if (name.consume_front("segment$start$"))
275     return handleSegmentBoundarySymbol(sym, name, Boundary::Start);
276   if (name.consume_front("segment$end$"))
277     return handleSegmentBoundarySymbol(sym, name, Boundary::End);
278 
279   // Handle -U.
280   if (config->explicitDynamicLookups.count(sym.getName())) {
281     symtab->addDynamicLookup(sym.getName());
282     return;
283   }
284 
285   // Handle -undefined.
286   auto message = [source, &sym]() {
287     std::string message = "undefined symbol";
288     if (config->archMultiple)
289       message += (" for arch " + getArchitectureName(config->arch())).str();
290     message += ": " + toString(sym);
291     if (!source.empty())
292       message += "\n>>> referenced by " + source.str();
293     else
294       message += "\n>>> referenced by " + toString(sym.getFile());
295     return message;
296   };
297   switch (config->undefinedSymbolTreatment) {
298   case UndefinedSymbolTreatment::error:
299     error(message());
300     break;
301   case UndefinedSymbolTreatment::warning:
302     warn(message());
303     LLVM_FALLTHROUGH;
304   case UndefinedSymbolTreatment::dynamic_lookup:
305   case UndefinedSymbolTreatment::suppress:
306     symtab->addDynamicLookup(sym.getName());
307     break;
308   case UndefinedSymbolTreatment::unknown:
309     llvm_unreachable("unknown -undefined TREATMENT");
310   }
311 }
312 
313 SymbolTable *macho::symtab;
314