1//===- Symbols.h ------------------------------------------------*- C++ -*-===//
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#ifndef LLD_MACHO_SYMBOLS_H
10#define LLD_MACHO_SYMBOLS_H
11
12#include "Config.h"
13#include "InputFiles.h"
14#include "Target.h"
15
16#include "lld/Common/Utils.h"
17#include "llvm/Object/Archive.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20
21#include <atomic>
22
23namespace lld {
24namespace macho {
25
26class MachHeaderSection;
27
28class Symbol {
29public:
30 enum Kind {
31 DefinedKind,
32 UndefinedKind,
33 CommonKind,
34 DylibKind,
35 LazyArchiveKind,
36 LazyObjectKind,
37 AliasKind,
38 };
39
40 // Enum that describes the type of Identical Code Folding (ICF) applied to a
41 // symbol. This information is crucial for accurately representing symbol
42 // sizes in the map file.
43 enum ICFFoldKind {
44 None, // No folding is applied.
45 Body, // The entire body (function or data) is folded.
46 Thunk // The function body is folded into a single branch thunk.
47 };
48
49 virtual ~Symbol() {}
50
51 Kind kind() const { return symbolKind; }
52
53 StringRef getName() const { return {nameData, nameSize}; }
54
55 bool isLive() const {
56 return utils::atomicRef(x: used).load(m: std::memory_order_relaxed);
57 }
58 bool isLazy() const {
59 return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind;
60 }
61
62 virtual uint64_t getVA() const { return 0; }
63
64 virtual bool isWeakDef() const { return false; }
65
66 // Only undefined or dylib symbols can be weak references. A weak reference
67 // need not be satisfied at runtime, e.g. due to the symbol not being
68 // available on a given target platform.
69 virtual bool isWeakRef() const { return false; }
70
71 virtual bool isTlv() const { return false; }
72
73 // Whether this symbol has a non-lazy pointer slot.
74 bool isInGot() const { return gotIndex != UINT32_MAX; }
75
76 // Whether this symbol is in the StubsSection.
77 bool isInStubs() const { return stubsIndex != UINT32_MAX; }
78
79 uint64_t getStubVA() const;
80 uint64_t getLazyPtrVA() const;
81 uint64_t getGotVA() const;
82 uint64_t resolveBranchVA() const {
83 assert(isa<Defined>(this) || isa<DylibSymbol>(this));
84 return isInStubs() ? getStubVA() : getVA();
85 }
86 // The address of this symbol's non-lazy pointer slot, or the symbol's own
87 // address if it has none.
88 uint64_t resolveNonLazyPtrVA() const {
89 return isInGot() ? getGotVA() : getVA();
90 }
91
92 // The index of this symbol's non-lazy pointer slot in __got.
93 uint32_t gotIndex = UINT32_MAX;
94 uint32_t lazyBindOffset = UINT32_MAX;
95 uint32_t stubsHelperIndex = UINT32_MAX;
96 uint32_t stubsIndex = UINT32_MAX;
97 uint32_t symtabIndex = UINT32_MAX;
98
99 InputFile *getFile() const { return file; }
100
101protected:
102 Symbol(Kind k, StringRef name, InputFile *file)
103 : symbolKind(k), nameData(name.data()), file(file), nameSize(name.size()),
104 isUsedInRegularObj(!file || isa<ObjFile>(Val: file)),
105 used(!config->deadStrip) {}
106
107 Kind symbolKind;
108 const char *nameData;
109 InputFile *file;
110 uint32_t nameSize;
111
112public:
113 // True if this symbol was referenced by a regular (non-bitcode) object.
114 bool isUsedInRegularObj : 1;
115
116 // True if this symbol is used from a live section.
117 bool used;
118};
119
120class Defined : public Symbol {
121public:
122 Defined(StringRef name, InputFile *file, InputSection *isec, uint64_t value,
123 uint64_t size, bool isWeakDef, bool isExternal, bool isPrivateExtern,
124 bool includeInSymtab, bool isReferencedDynamically, bool noDeadStrip,
125 bool canOverrideWeakDef = false, bool isWeakDefCanBeHidden = false,
126 bool interposable = false, bool cold = false);
127
128 bool isWeakDef() const override { return weakDef; }
129 bool isExternalWeakDef() const {
130 return isWeakDef() && isExternal() && !privateExtern;
131 }
132 bool isTlv() const override;
133
134 bool isExternal() const { return external; }
135 bool isAbsolute() const { return originalIsec == nullptr; }
136 bool isCold() const { return cold; }
137
138 uint64_t getVA() const override;
139
140 // Returns the object file that this symbol was defined in. This value differs
141 // from `getFile()` if the symbol originated from a bitcode file.
142 ObjFile *getObjectFile() const;
143
144 std::string getSourceLocation();
145
146 // Get the canonical InputSection of the symbol.
147 InputSection *isec() const;
148
149 // Get the canonical unwind entry of the symbol.
150 ConcatInputSection *unwindEntry() const;
151
152 static bool classof(const Symbol *s) { return s->kind() == DefinedKind; }
153
154 // Place the bitfields first so that they can get placed in the tail padding
155 // of the parent class, on platforms which support it.
156 bool overridesWeakDef : 1;
157 // Whether this symbol should appear in the output binary's export trie.
158 bool privateExtern : 1;
159 // Whether this symbol should appear in the output symbol table.
160 bool includeInSymtab : 1;
161 // The ICF folding kind of this symbol: None / Body / Thunk.
162 LLVM_PREFERRED_TYPE(ICFFoldKind)
163 uint8_t identicalCodeFoldingKind : 2;
164 // Symbols marked referencedDynamically won't be removed from the output's
165 // symbol table by tools like strip. In theory, this could be set on arbitrary
166 // symbols in input object files. In practice, it's used solely for the
167 // synthetic __mh_execute_header symbol.
168 // This is information for the static linker, and it's also written to the
169 // output file's symbol table for tools running later (such as `strip`).
170 bool referencedDynamically : 1;
171 // Set on symbols that should not be removed by dead code stripping.
172 // Set for example on `__attribute__((used))` globals, or on some Objective-C
173 // metadata. This is information only for the static linker and not written
174 // to the output.
175 bool noDeadStrip : 1;
176 // Whether references to this symbol can be interposed at runtime to point to
177 // a different symbol definition (with the same name). For example, if both
178 // dylib A and B define an interposable symbol _foo, and we load A before B at
179 // runtime, then all references to _foo within dylib B will point to the
180 // definition in dylib A.
181 //
182 // Only extern symbols may be interposable.
183 bool interposable : 1;
184
185 bool weakDefCanBeHidden : 1;
186
187 // Whether this symbol has the N_COLD_FUNC nlist flag set. Populated from the
188 // symbol table of input object files.
189 bool cold : 1;
190
191 // Whether this symbol represents a synthesized branch-extension thunk.
192 bool branchExtensionThunk : 1;
193
194private:
195 const bool weakDef : 1;
196 const bool external : 1;
197
198public:
199 // The native InputSection of the symbol. The symbol may be moved to another
200 // InputSection in which case originalIsec->canonical() will point to the new
201 // InputSection
202 InputSection *originalIsec;
203 // Contains the offset from the containing subsection. Note that this is
204 // different from nlist::n_value, which is the absolute address of the symbol.
205 uint64_t value;
206 // size is only calculated for regular (non-bitcode) symbols.
207 uint64_t size;
208 // This can be a subsection of either __compact_unwind or __eh_frame.
209 ConcatInputSection *originalUnwindEntry = nullptr;
210};
211
212// This enum does double-duty: as a symbol property, it indicates whether & how
213// a dylib symbol is referenced. As a DylibFile property, it indicates the kind
214// of referenced symbols contained within the file. If there are both weak
215// and strong references to the same file, we will count the file as
216// strongly-referenced.
217enum class RefState : uint8_t { Unreferenced = 0, Weak = 1, Strong = 2 };
218
219class Undefined : public Symbol {
220public:
221 Undefined(StringRef name, InputFile *file, RefState refState,
222 bool wasBitcodeSymbol)
223 : Symbol(UndefinedKind, name, file), refState(refState),
224 wasBitcodeSymbol(wasBitcodeSymbol) {
225 assert(refState != RefState::Unreferenced);
226 }
227
228 bool isWeakRef() const override { return refState == RefState::Weak; }
229
230 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
231
232 RefState refState : 2;
233 bool wasBitcodeSymbol;
234};
235
236// On Unix, it is traditionally allowed to write variable definitions without
237// initialization expressions (such as "int foo;") to header files. These are
238// called tentative definitions.
239//
240// Using tentative definitions is usually considered a bad practice; you should
241// write only declarations (such as "extern int foo;") to header files.
242// Nevertheless, the linker and the compiler have to do something to support
243// bad code by allowing duplicate definitions for this particular case.
244//
245// The compiler creates common symbols when it sees tentative definitions.
246// (You can suppress this behavior and let the compiler create a regular
247// defined symbol by passing -fno-common. -fno-common is the default in clang
248// as of LLVM 11.0.) When linking the final binary, if there are remaining
249// common symbols after name resolution is complete, the linker converts them
250// to regular defined symbols in a __common section.
251class CommonSymbol : public Symbol {
252public:
253 CommonSymbol(StringRef name, InputFile *file, uint64_t size, uint32_t align,
254 bool isPrivateExtern)
255 : Symbol(CommonKind, name, file), size(size),
256 align(align != 1 ? align : llvm::PowerOf2Ceil(A: size)),
257 privateExtern(isPrivateExtern) {
258 // TODO: cap maximum alignment
259 }
260
261 static bool classof(const Symbol *s) { return s->kind() == CommonKind; }
262
263 const uint64_t size;
264 const uint32_t align;
265 const bool privateExtern;
266};
267
268class DylibSymbol : public Symbol {
269public:
270 DylibSymbol(DylibFile *file, StringRef name, bool isWeakDef,
271 RefState refState, bool isTlv)
272 : Symbol(DylibKind, name, file), shouldReexport(false),
273 refState(refState), weakDef(isWeakDef), tlv(isTlv) {
274 if (file && refState > RefState::Unreferenced)
275 file->numReferencedSymbols++;
276 }
277
278 uint64_t getVA() const override;
279 bool isWeakDef() const override { return weakDef; }
280
281 // Symbols from weak libraries/frameworks are also weakly-referenced.
282 bool isWeakRef() const override {
283 return refState == RefState::Weak ||
284 (file && getFile()->umbrella->forceWeakImport);
285 }
286 bool isReferenced() const { return refState != RefState::Unreferenced; }
287 bool isTlv() const override { return tlv; }
288 bool isDynamicLookup() const { return file == nullptr; }
289 bool hasStubsHelper() const { return stubsHelperIndex != UINT32_MAX; }
290
291 DylibFile *getFile() const {
292 assert(!isDynamicLookup());
293 return cast<DylibFile>(Val: file);
294 }
295
296 static bool classof(const Symbol *s) { return s->kind() == DylibKind; }
297
298 RefState getRefState() const { return refState; }
299
300 void reference(RefState newState) {
301 assert(newState > RefState::Unreferenced);
302 if (refState == RefState::Unreferenced && file)
303 getFile()->numReferencedSymbols++;
304 refState = std::max(a: refState, b: newState);
305 }
306
307 void unreference() {
308 // dynamic_lookup symbols have no file.
309 if (refState > RefState::Unreferenced && file) {
310 assert(getFile()->numReferencedSymbols > 0);
311 getFile()->numReferencedSymbols--;
312 }
313 }
314
315 bool shouldReexport : 1;
316
317private:
318 RefState refState : 2;
319 const bool weakDef : 1;
320 const bool tlv : 1;
321};
322
323class LazyArchive : public Symbol {
324public:
325 LazyArchive(ArchiveFile *file, const llvm::object::Archive::Symbol &sym)
326 : Symbol(LazyArchiveKind, sym.getName(), file), sym(sym) {}
327
328 ArchiveFile *getFile() const { return cast<ArchiveFile>(Val: file); }
329 void fetchArchiveMember();
330
331 static bool classof(const Symbol *s) { return s->kind() == LazyArchiveKind; }
332
333private:
334 const llvm::object::Archive::Symbol sym;
335};
336
337// A defined symbol in an ObjFile/BitcodeFile surrounded by --start-lib and
338// --end-lib.
339class LazyObject : public Symbol {
340public:
341 LazyObject(InputFile &file, StringRef name)
342 : Symbol(LazyObjectKind, name, &file) {
343 isUsedInRegularObj = false;
344 }
345
346 static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
347};
348
349// Represents N_INDR symbols. Note that if we are given valid, linkable inputs,
350// then all AliasSymbol instances will be converted into one of the other Symbol
351// types after `createAliases()` runs.
352class AliasSymbol final : public Symbol {
353public:
354 AliasSymbol(InputFile *file, StringRef name, StringRef aliasedName,
355 bool isPrivateExtern)
356 : Symbol(AliasKind, name, file), privateExtern(isPrivateExtern),
357 aliasedName(aliasedName) {}
358
359 StringRef getAliasedName() const { return aliasedName; }
360
361 static bool classof(const Symbol *s) { return s->kind() == AliasKind; }
362
363 const bool privateExtern;
364
365private:
366 StringRef aliasedName;
367};
368
369union SymbolUnion {
370 alignas(Defined) char a[sizeof(Defined)];
371 alignas(Undefined) char b[sizeof(Undefined)];
372 alignas(CommonSymbol) char c[sizeof(CommonSymbol)];
373 alignas(DylibSymbol) char d[sizeof(DylibSymbol)];
374 alignas(LazyArchive) char e[sizeof(LazyArchive)];
375 alignas(LazyObject) char f[sizeof(LazyObject)];
376 alignas(AliasSymbol) char g[sizeof(AliasSymbol)];
377};
378
379template <typename T, typename... ArgT>
380T *replaceSymbol(Symbol *s, ArgT &&...arg) {
381 static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
382 static_assert(alignof(T) <= alignof(SymbolUnion),
383 "SymbolUnion not aligned enough");
384 assert(static_cast<Symbol *>(static_cast<T *>(nullptr)) == nullptr &&
385 "Not a Symbol");
386
387 bool isUsedInRegularObj = s->isUsedInRegularObj;
388 bool used = s->used;
389 T *sym = new (s) T(std::forward<ArgT>(arg)...);
390 sym->isUsedInRegularObj |= isUsedInRegularObj;
391 sym->used |= used;
392 return sym;
393}
394
395// Can a symbol's address only be resolved at runtime?
396inline bool needsBinding(const Symbol *sym) {
397 if (isa<DylibSymbol>(Val: sym))
398 return true;
399 if (const auto *defined = dyn_cast<Defined>(Val: sym))
400 return defined->isExternalWeakDef() || defined->interposable;
401 return false;
402}
403
404// Symbols with `l` or `L` as a prefix are linker-private and never appear in
405// the output.
406inline bool isPrivateLabel(StringRef name) {
407 return name.starts_with(Prefix: "l") || name.starts_with(Prefix: "L");
408}
409} // namespace macho
410
411std::string toString(const macho::Symbol &);
412std::string toMachOString(const llvm::object::Archive::Symbol &);
413
414} // namespace lld
415
416#endif
417