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         std::string src1 = defined->getSourceLocation();
87         std::string src2 = isec ? isec->getSourceLocation(value) : "";
88 
89         std::string message =
90             "duplicate symbol: " + toString(*defined) + "\n>>> defined in ";
91         if (!src1.empty())
92           message += src1 + "\n>>>            ";
93         message += toString(defined->getFile()) + "\n>>> defined in ";
94         if (!src2.empty())
95           message += src2 + "\n>>>            ";
96         error(message + toString(file));
97       }
98 
99     } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
100       overridesWeakDef = !isWeakDef && dysym->isWeakDef();
101       dysym->unreference();
102     }
103     // Defined symbols take priority over other types of symbols, so in case
104     // of a name conflict, we fall through to the replaceSymbol() call below.
105   }
106 
107   // With -flat_namespace, all extern symbols in dylibs are interposable.
108   // FIXME: Add support for `-interposable` (PR53680).
109   bool interposable = config->namespaceKind == NamespaceKind::flat &&
110                       config->outputType != MachO::MH_EXECUTE &&
111                       !isPrivateExtern;
112   Defined *defined = replaceSymbol<Defined>(
113       s, name, file, isec, value, size, isWeakDef, /*isExternal=*/true,
114       isPrivateExtern, /*includeInSymtab=*/true, isThumb,
115       isReferencedDynamically, noDeadStrip, overridesWeakDef,
116       isWeakDefCanBeHidden, interposable);
117   return defined;
118 }
119 
120 Symbol *SymbolTable::addUndefined(StringRef name, InputFile *file,
121                                   bool isWeakRef) {
122   Symbol *s;
123   bool wasInserted;
124   std::tie(s, wasInserted) = insert(name, file);
125 
126   RefState refState = isWeakRef ? RefState::Weak : RefState::Strong;
127 
128   if (wasInserted)
129     replaceSymbol<Undefined>(s, name, file, refState);
130   else if (auto *lazy = dyn_cast<LazyArchive>(s))
131     lazy->fetchArchiveMember();
132   else if (isa<LazyObject>(s))
133     extract(*s->getFile(), s->getName());
134   else if (auto *dynsym = dyn_cast<DylibSymbol>(s))
135     dynsym->reference(refState);
136   else if (auto *undefined = dyn_cast<Undefined>(s))
137     undefined->refState = std::max(undefined->refState, refState);
138   return s;
139 }
140 
141 Symbol *SymbolTable::addCommon(StringRef name, InputFile *file, uint64_t size,
142                                uint32_t align, bool isPrivateExtern) {
143   Symbol *s;
144   bool wasInserted;
145   std::tie(s, wasInserted) = insert(name, file);
146 
147   if (!wasInserted) {
148     if (auto *common = dyn_cast<CommonSymbol>(s)) {
149       if (size < common->size)
150         return s;
151     } else if (isa<Defined>(s)) {
152       return s;
153     }
154     // Common symbols take priority over all non-Defined symbols, so in case of
155     // a name conflict, we fall through to the replaceSymbol() call below.
156   }
157 
158   replaceSymbol<CommonSymbol>(s, name, file, size, align, isPrivateExtern);
159   return s;
160 }
161 
162 Symbol *SymbolTable::addDylib(StringRef name, DylibFile *file, bool isWeakDef,
163                               bool isTlv) {
164   Symbol *s;
165   bool wasInserted;
166   std::tie(s, wasInserted) = insert(name, file);
167 
168   RefState refState = RefState::Unreferenced;
169   if (!wasInserted) {
170     if (auto *defined = dyn_cast<Defined>(s)) {
171       if (isWeakDef && !defined->isWeakDef())
172         defined->overridesWeakDef = true;
173     } else if (auto *undefined = dyn_cast<Undefined>(s)) {
174       refState = undefined->refState;
175     } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
176       refState = dysym->getRefState();
177     }
178   }
179 
180   bool isDynamicLookup = file == nullptr;
181   if (wasInserted || isa<Undefined>(s) ||
182       (isa<DylibSymbol>(s) &&
183        ((!isWeakDef && s->isWeakDef()) ||
184         (!isDynamicLookup && cast<DylibSymbol>(s)->isDynamicLookup())))) {
185     if (auto *dynsym = dyn_cast<DylibSymbol>(s))
186       dynsym->unreference();
187     replaceSymbol<DylibSymbol>(s, file, name, isWeakDef, refState, isTlv);
188   }
189 
190   return s;
191 }
192 
193 Symbol *SymbolTable::addDynamicLookup(StringRef name) {
194   return addDylib(name, /*file=*/nullptr, /*isWeakDef=*/false, /*isTlv=*/false);
195 }
196 
197 Symbol *SymbolTable::addLazyArchive(StringRef name, ArchiveFile *file,
198                                     const object::Archive::Symbol &sym) {
199   Symbol *s;
200   bool wasInserted;
201   std::tie(s, wasInserted) = insert(name, file);
202 
203   if (wasInserted) {
204     replaceSymbol<LazyArchive>(s, file, sym);
205   } else if (isa<Undefined>(s)) {
206     file->fetch(sym);
207   } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
208     if (dysym->isWeakDef()) {
209       if (dysym->getRefState() != RefState::Unreferenced)
210         file->fetch(sym);
211       else
212         replaceSymbol<LazyArchive>(s, file, sym);
213     }
214   }
215   return s;
216 }
217 
218 Symbol *SymbolTable::addLazyObject(StringRef name, InputFile &file) {
219   Symbol *s;
220   bool wasInserted;
221   std::tie(s, wasInserted) = insert(name, &file);
222 
223   if (wasInserted) {
224     replaceSymbol<LazyObject>(s, file, name);
225   } else if (isa<Undefined>(s)) {
226     extract(file, name);
227   } else if (auto *dysym = dyn_cast<DylibSymbol>(s)) {
228     if (dysym->isWeakDef()) {
229       if (dysym->getRefState() != RefState::Unreferenced)
230         extract(file, name);
231       else
232         replaceSymbol<LazyObject>(s, file, name);
233     }
234   }
235   return s;
236 }
237 
238 Defined *SymbolTable::addSynthetic(StringRef name, InputSection *isec,
239                                    uint64_t value, bool isPrivateExtern,
240                                    bool includeInSymtab,
241                                    bool referencedDynamically) {
242   assert(!isec || !isec->getFile()); // See makeSyntheticInputSection().
243   Defined *s =
244       addDefined(name, /*file=*/nullptr, isec, value, /*size=*/0,
245                  /*isWeakDef=*/false, isPrivateExtern, /*isThumb=*/false,
246                  referencedDynamically, /*noDeadStrip=*/false,
247                  /*isWeakDefCanBeHidden=*/false);
248   s->includeInSymtab = includeInSymtab;
249   return s;
250 }
251 
252 enum class Boundary {
253   Start,
254   End,
255 };
256 
257 static Defined *createBoundarySymbol(const Undefined &sym) {
258   return symtab->addSynthetic(
259       sym.getName(), /*isec=*/nullptr, /*value=*/-1, /*isPrivateExtern=*/true,
260       /*includeInSymtab=*/false, /*referencedDynamically=*/false);
261 }
262 
263 static void handleSectionBoundarySymbol(const Undefined &sym, StringRef segSect,
264                                         Boundary which) {
265   StringRef segName, sectName;
266   std::tie(segName, sectName) = segSect.split('$');
267 
268   // Attach the symbol to any InputSection that will end up in the right
269   // OutputSection -- it doesn't matter which one we pick.
270   // Don't bother looking through inputSections for a matching
271   // ConcatInputSection -- we need to create ConcatInputSection for
272   // non-existing sections anyways, and that codepath works even if we should
273   // already have a ConcatInputSection with the right name.
274 
275   OutputSection *osec = nullptr;
276   // This looks for __TEXT,__cstring etc.
277   for (SyntheticSection *ssec : syntheticSections)
278     if (ssec->segname == segName && ssec->name == sectName) {
279       osec = ssec->isec->parent;
280       break;
281     }
282 
283   if (!osec) {
284     ConcatInputSection *isec = makeSyntheticInputSection(segName, sectName);
285 
286     // This runs after markLive() and is only called for Undefineds that are
287     // live. Marking the isec live ensures an OutputSection is created that the
288     // start/end symbol can refer to.
289     assert(sym.isLive());
290     isec->live = true;
291 
292     // This runs after gatherInputSections(), so need to explicitly set parent
293     // and add to inputSections.
294     osec = isec->parent = ConcatOutputSection::getOrCreateForInput(isec);
295     inputSections.push_back(isec);
296   }
297 
298   if (which == Boundary::Start)
299     osec->sectionStartSymbols.push_back(createBoundarySymbol(sym));
300   else
301     osec->sectionEndSymbols.push_back(createBoundarySymbol(sym));
302 }
303 
304 static void handleSegmentBoundarySymbol(const Undefined &sym, StringRef segName,
305                                         Boundary which) {
306   OutputSegment *seg = getOrCreateOutputSegment(segName);
307   if (which == Boundary::Start)
308     seg->segmentStartSymbols.push_back(createBoundarySymbol(sym));
309   else
310     seg->segmentEndSymbols.push_back(createBoundarySymbol(sym));
311 }
312 
313 // Try to find a definition for an undefined symbol.
314 // Returns true if a definition was found and no diagnostics are needed.
315 static bool recoverFromUndefinedSymbol(const Undefined &sym) {
316   // Handle start/end symbols.
317   StringRef name = sym.getName();
318   if (name.consume_front("section$start$")) {
319     handleSectionBoundarySymbol(sym, name, Boundary::Start);
320     return true;
321   }
322   if (name.consume_front("section$end$")) {
323     handleSectionBoundarySymbol(sym, name, Boundary::End);
324     return true;
325   }
326   if (name.consume_front("segment$start$")) {
327     handleSegmentBoundarySymbol(sym, name, Boundary::Start);
328     return true;
329   }
330   if (name.consume_front("segment$end$")) {
331     handleSegmentBoundarySymbol(sym, name, Boundary::End);
332     return true;
333   }
334 
335   // Handle -U.
336   if (config->explicitDynamicLookups.count(sym.getName())) {
337     symtab->addDynamicLookup(sym.getName());
338     return true;
339   }
340 
341   // Handle -undefined.
342   if (config->undefinedSymbolTreatment ==
343           UndefinedSymbolTreatment::dynamic_lookup ||
344       config->undefinedSymbolTreatment == UndefinedSymbolTreatment::suppress) {
345     symtab->addDynamicLookup(sym.getName());
346     return true;
347   }
348 
349   // We do not return true here, as we still need to print diagnostics.
350   if (config->undefinedSymbolTreatment == UndefinedSymbolTreatment::warning)
351     symtab->addDynamicLookup(sym.getName());
352 
353   return false;
354 }
355 
356 namespace {
357 struct UndefinedDiag {
358   struct SectionAndOffset {
359     const InputSection *isec;
360     uint64_t offset;
361   };
362 
363   std::vector<SectionAndOffset> codeReferences;
364   std::vector<std::string> otherReferences;
365 };
366 
367 MapVector<const Undefined *, UndefinedDiag> undefs;
368 }
369 
370 void macho::reportPendingUndefinedSymbols() {
371   for (const auto &undef : undefs) {
372     const UndefinedDiag &locations = undef.second;
373 
374     std::string message = "undefined symbol";
375     if (config->archMultiple)
376       message += (" for arch " + getArchitectureName(config->arch())).str();
377     message += ": " + toString(*undef.first);
378 
379     const size_t maxUndefinedReferences = 3;
380     size_t i = 0;
381     for (const std::string &loc : locations.otherReferences) {
382       if (i >= maxUndefinedReferences)
383         break;
384       message += "\n>>> referenced by " + loc;
385       ++i;
386     }
387 
388     for (const UndefinedDiag::SectionAndOffset &loc :
389          locations.codeReferences) {
390       if (i >= maxUndefinedReferences)
391         break;
392       message += "\n>>> referenced by ";
393       std::string src = loc.isec->getSourceLocation(loc.offset);
394       if (!src.empty())
395         message += src + "\n>>>               ";
396       message += loc.isec->getLocation(loc.offset);
397       ++i;
398     }
399 
400     size_t totalReferences =
401         locations.otherReferences.size() + locations.codeReferences.size();
402     if (totalReferences > i)
403       message +=
404           ("\n>>> referenced " + Twine(totalReferences - i) + " more times")
405               .str();
406 
407     if (config->undefinedSymbolTreatment == UndefinedSymbolTreatment::error)
408       error(message);
409     else if (config->undefinedSymbolTreatment ==
410              UndefinedSymbolTreatment::warning)
411       warn(message);
412     else
413       assert(false &&
414              "diagnostics make sense for -undefined error|warning only");
415   }
416 
417   // This function is called multiple times during execution. Clear the printed
418   // diagnostics to avoid printing the same things again the next time.
419   undefs.clear();
420 }
421 
422 void macho::treatUndefinedSymbol(const Undefined &sym, StringRef source) {
423   if (recoverFromUndefinedSymbol(sym))
424     return;
425 
426   undefs[&sym].otherReferences.push_back(source.str());
427 }
428 
429 void macho::treatUndefinedSymbol(const Undefined &sym, const InputSection *isec,
430                                  uint64_t offset) {
431   if (recoverFromUndefinedSymbol(sym))
432     return;
433 
434   undefs[&sym].codeReferences.push_back({isec, offset});
435 }
436 
437 std::unique_ptr<SymbolTable> macho::symtab;
438