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