1 //===- SyntheticSections.h -------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLD_MACHO_SYNTHETIC_SECTIONS_H
10 #define LLD_MACHO_SYNTHETIC_SECTIONS_H
13 #include "ExportTrie.h"
14 #include "InputSection.h"
15 #include "OutputSection.h"
16 #include "OutputSegment.h"
19 #include "llvm/ADT/PointerUnion.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/Support/raw_ostream.h"
26 namespace section_names
{
28 constexpr const char pageZero
[] = "__pagezero";
29 constexpr const char common
[] = "__common";
30 constexpr const char header
[] = "__mach_header";
31 constexpr const char rebase
[] = "__rebase";
32 constexpr const char binding
[] = "__binding";
33 constexpr const char weakBinding
[] = "__weak_binding";
34 constexpr const char lazyBinding
[] = "__lazy_binding";
35 constexpr const char export_
[] = "__export";
36 constexpr const char symbolTable
[] = "__symbol_table";
37 constexpr const char indirectSymbolTable
[] = "__ind_sym_tab";
38 constexpr const char stringTable
[] = "__string_table";
39 constexpr const char got
[] = "__got";
40 constexpr const char threadPtrs
[] = "__thread_ptrs";
41 constexpr const char unwindInfo
[] = "__unwind_info";
42 // these are not synthetic, but in service of synthetic __unwind_info
43 constexpr const char compactUnwind
[] = "__compact_unwind";
44 constexpr const char ehFrame
[] = "__eh_frame";
46 } // namespace section_names
52 class SyntheticSection
: public OutputSection
{
54 SyntheticSection(const char *segname
, const char *name
);
55 virtual ~SyntheticSection() = default;
57 static bool classof(const OutputSection
*sec
) {
58 return sec
->kind() == SyntheticKind
;
61 const StringRef segname
;
64 // All sections in __LINKEDIT should inherit from this.
65 class LinkEditSection
: public SyntheticSection
{
67 LinkEditSection(const char *segname
, const char *name
)
68 : SyntheticSection(segname
, name
) {
72 // Sections in __LINKEDIT are special: their offsets are recorded in the
73 // load commands like LC_DYLD_INFO_ONLY and LC_SYMTAB, instead of in section
75 bool isHidden() const override final
{ return true; }
77 virtual uint64_t getRawSize() const = 0;
79 // codesign (or more specifically libstuff) checks that each section in
80 // __LINKEDIT ends where the next one starts -- no gaps are permitted. We
81 // therefore align every section's start and end points to WordSize.
83 // NOTE: This assumes that the extra bytes required for alignment can be
85 uint64_t getSize() const override final
{
86 return llvm::alignTo(getRawSize(), WordSize
);
90 // The header of the Mach-O file, which must have a file offset of zero.
91 class MachHeaderSection
: public SyntheticSection
{
94 void addLoadCommand(LoadCommand
*);
95 bool isHidden() const override
{ return true; }
96 uint64_t getSize() const override
;
97 void writeTo(uint8_t *buf
) const override
;
100 std::vector
<LoadCommand
*> loadCommands
;
101 uint32_t sizeOfCmds
= 0;
104 // A hidden section that exists solely for the purpose of creating the
105 // __PAGEZERO segment, which is used to catch null pointer dereferences.
106 class PageZeroSection
: public SyntheticSection
{
109 bool isHidden() const override
{ return true; }
110 uint64_t getSize() const override
{ return PageZeroSize
; }
111 uint64_t getFileSize() const override
{ return 0; }
112 void writeTo(uint8_t *buf
) const override
{}
115 // This is the base class for the GOT and TLVPointer sections, which are nearly
116 // functionally identical -- they will both be populated by dyld with addresses
117 // to non-lazily-loaded dylib symbols. The main difference is that the
118 // TLVPointerSection stores references to thread-local variables.
119 class NonLazyPointerSectionBase
: public SyntheticSection
{
121 NonLazyPointerSectionBase(const char *segname
, const char *name
);
123 const llvm::SetVector
<const Symbol
*> &getEntries() const { return entries
; }
125 bool isNeeded() const override
{ return !entries
.empty(); }
127 uint64_t getSize() const override
{ return entries
.size() * WordSize
; }
129 void writeTo(uint8_t *buf
) const override
;
131 void addEntry(Symbol
*sym
);
134 llvm::SetVector
<const Symbol
*> entries
;
137 class GotSection
: public NonLazyPointerSectionBase
{
140 : NonLazyPointerSectionBase(segment_names::dataConst
,
141 section_names::got
) {
142 // TODO: section_64::reserved1 should be an index into the indirect symbol
143 // table, which we do not currently emit
147 class TlvPointerSection
: public NonLazyPointerSectionBase
{
150 : NonLazyPointerSectionBase(segment_names::data
,
151 section_names::threadPtrs
) {}
154 using SectionPointerUnion
=
155 llvm::PointerUnion
<const InputSection
*, const OutputSection
*>;
158 SectionPointerUnion section
= nullptr;
161 Location(SectionPointerUnion section
, uint64_t offset
)
162 : section(section
), offset(offset
) {}
163 uint64_t getVA() const;
166 // Stores rebase opcodes, which tell dyld where absolute addresses have been
167 // encoded in the binary. If the binary is not loaded at its preferred address,
168 // dyld has to rebase these addresses by adding an offset to them.
169 class RebaseSection
: public LinkEditSection
{
172 void finalizeContents();
173 uint64_t getRawSize() const override
{ return contents
.size(); }
174 bool isNeeded() const override
{ return !locations
.empty(); }
175 void writeTo(uint8_t *buf
) const override
;
177 void addEntry(SectionPointerUnion section
, uint64_t offset
) {
179 locations
.push_back({section
, offset
});
183 std::vector
<Location
> locations
;
184 SmallVector
<char, 128> contents
;
187 struct BindingEntry
{
188 const DylibSymbol
*dysym
;
191 BindingEntry(const DylibSymbol
*dysym
, int64_t addend
, Location target
)
192 : dysym(dysym
), addend(addend
), target(std::move(target
)) {}
195 // Stores bind opcodes for telling dyld which symbols to load non-lazily.
196 class BindingSection
: public LinkEditSection
{
199 void finalizeContents();
200 uint64_t getRawSize() const override
{ return contents
.size(); }
201 bool isNeeded() const override
{ return !bindings
.empty(); }
202 void writeTo(uint8_t *buf
) const override
;
204 void addEntry(const DylibSymbol
*dysym
, SectionPointerUnion section
,
205 uint64_t offset
, int64_t addend
= 0) {
206 bindings
.emplace_back(dysym
, addend
, Location(section
, offset
));
210 std::vector
<BindingEntry
> bindings
;
211 SmallVector
<char, 128> contents
;
214 struct WeakBindingEntry
{
215 const Symbol
*symbol
;
218 WeakBindingEntry(const Symbol
*symbol
, int64_t addend
, Location target
)
219 : symbol(symbol
), addend(addend
), target(std::move(target
)) {}
222 // Stores bind opcodes for telling dyld which weak symbols need coalescing.
223 // There are two types of entries in this section:
225 // 1) Non-weak definitions: This is a symbol definition that weak symbols in
226 // other dylibs should coalesce to.
228 // 2) Weak bindings: These tell dyld that a given symbol reference should
229 // coalesce to a non-weak definition if one is found. Note that unlike in the
230 // entries in the BindingSection, the bindings here only refer to these
231 // symbols by name, but do not specify which dylib to load them from.
232 class WeakBindingSection
: public LinkEditSection
{
234 WeakBindingSection();
235 void finalizeContents();
236 uint64_t getRawSize() const override
{ return contents
.size(); }
237 bool isNeeded() const override
{
238 return !bindings
.empty() || !definitions
.empty();
241 void writeTo(uint8_t *buf
) const override
;
243 void addEntry(const Symbol
*symbol
, SectionPointerUnion section
,
244 uint64_t offset
, int64_t addend
= 0) {
245 bindings
.emplace_back(symbol
, addend
, Location(section
, offset
));
248 bool hasEntry() const { return !bindings
.empty(); }
250 void addNonWeakDefinition(const Defined
*defined
) {
251 definitions
.emplace_back(defined
);
254 bool hasNonWeakDefinition() const { return !definitions
.empty(); }
257 std::vector
<WeakBindingEntry
> bindings
;
258 std::vector
<const Defined
*> definitions
;
259 SmallVector
<char, 128> contents
;
262 // Whether a given symbol's address can only be resolved at runtime.
263 bool needsBinding(const Symbol
*);
265 // Add bindings for symbols that need weak or non-lazy bindings.
266 void addNonLazyBindingEntries(const Symbol
*, SectionPointerUnion
,
267 uint64_t offset
, int64_t addend
= 0);
269 // The following sections implement lazy symbol binding -- very similar to the
270 // PLT mechanism in ELF.
272 // ELF's .plt section is broken up into two sections in Mach-O: StubsSection
273 // and StubHelperSection. Calls to functions in dylibs will end up calling into
274 // StubsSection, which contains indirect jumps to addresses stored in the
275 // LazyPointerSection (the counterpart to ELF's .plt.got).
277 // We will first describe how non-weak symbols are handled.
279 // At program start, the LazyPointerSection contains addresses that point into
280 // one of the entry points in the middle of the StubHelperSection. The code in
281 // StubHelperSection will push on the stack an offset into the
282 // LazyBindingSection. The push is followed by a jump to the beginning of the
283 // StubHelperSection (similar to PLT0), which then calls into dyld_stub_binder.
284 // dyld_stub_binder is a non-lazily-bound symbol, so this call looks it up in
287 // The stub binder will look up the bind opcodes in the LazyBindingSection at
288 // the given offset. The bind opcodes will tell the binder to update the
289 // address in the LazyPointerSection to point to the symbol, so that subsequent
290 // calls don't have to redo the symbol resolution. The binder will then jump to
291 // the resolved symbol.
293 // With weak symbols, the situation is slightly different. Since there is no
294 // "weak lazy" lookup, function calls to weak symbols are always non-lazily
295 // bound. We emit both regular non-lazy bindings as well as weak bindings, in
296 // order that the weak bindings may overwrite the non-lazy bindings if an
297 // appropriate symbol is found at runtime. However, the bound addresses will
298 // still be written (non-lazily) into the LazyPointerSection.
300 class StubsSection
: public SyntheticSection
{
303 uint64_t getSize() const override
;
304 bool isNeeded() const override
{ return !entries
.empty(); }
305 void writeTo(uint8_t *buf
) const override
;
306 const llvm::SetVector
<Symbol
*> &getEntries() const { return entries
; }
307 // Returns whether the symbol was added. Note that every stubs entry will
308 // have a corresponding entry in the LazyPointerSection.
309 bool addEntry(Symbol
*);
312 llvm::SetVector
<Symbol
*> entries
;
315 class StubHelperSection
: public SyntheticSection
{
318 uint64_t getSize() const override
;
319 bool isNeeded() const override
;
320 void writeTo(uint8_t *buf
) const override
;
324 DylibSymbol
*stubBinder
= nullptr;
327 // This section contains space for just a single word, and will be used by dyld
328 // to cache an address to the image loader it uses. Note that unlike the other
329 // synthetic sections, which are OutputSections, the ImageLoaderCacheSection is
330 // an InputSection that gets merged into the __data OutputSection.
331 class ImageLoaderCacheSection
: public InputSection
{
333 ImageLoaderCacheSection();
334 uint64_t getSize() const override
{ return WordSize
; }
337 // Note that this section may also be targeted by non-lazy bindings. In
338 // particular, this happens when branch relocations target weak symbols.
339 class LazyPointerSection
: public SyntheticSection
{
341 LazyPointerSection();
342 uint64_t getSize() const override
;
343 bool isNeeded() const override
;
344 void writeTo(uint8_t *buf
) const override
;
347 class LazyBindingSection
: public LinkEditSection
{
349 LazyBindingSection();
350 void finalizeContents();
351 uint64_t getRawSize() const override
{ return contents
.size(); }
352 bool isNeeded() const override
{ return !entries
.empty(); }
353 void writeTo(uint8_t *buf
) const override
;
354 // Note that every entry here will by referenced by a corresponding entry in
355 // the StubHelperSection.
356 void addEntry(DylibSymbol
*dysym
);
357 const llvm::SetVector
<DylibSymbol
*> &getEntries() const { return entries
; }
360 uint32_t encode(const DylibSymbol
&);
362 llvm::SetVector
<DylibSymbol
*> entries
;
363 SmallVector
<char, 128> contents
;
364 llvm::raw_svector_ostream os
{contents
};
367 // Adds stubs and bindings where necessary (e.g. if the symbol is a
369 void prepareBranchTarget(Symbol
*);
371 // Stores a trie that describes the set of exported symbols.
372 class ExportSection
: public LinkEditSection
{
375 void finalizeContents();
376 uint64_t getRawSize() const override
{ return size
; }
377 void writeTo(uint8_t *buf
) const override
;
379 bool hasWeakSymbol
= false;
382 TrieBuilder trieBuilder
;
386 // Stores the strings referenced by the symbol table.
387 class StringTableSection
: public LinkEditSection
{
389 StringTableSection();
390 // Returns the start offset of the added string.
391 uint32_t addString(StringRef
);
392 uint64_t getRawSize() const override
{ return size
; }
393 void writeTo(uint8_t *buf
) const override
;
396 // An n_strx value of 0 always indicates the empty string, so we must locate
397 // our non-empty string values at positive offsets in the string table.
398 // Therefore we insert a dummy value at position zero.
399 std::vector
<StringRef
> strings
{"\0"};
408 class SymtabSection
: public LinkEditSection
{
410 SymtabSection(StringTableSection
&);
411 void finalizeContents();
412 size_t getNumSymbols() const { return symbols
.size(); }
413 uint64_t getRawSize() const override
;
414 void writeTo(uint8_t *buf
) const override
;
417 StringTableSection
&stringTableSection
;
418 std::vector
<SymtabEntry
> symbols
;
421 // The indirect symbol table is a list of 32-bit integers that serve as indices
422 // into the (actual) symbol table. The indirect symbol table is a
423 // concatentation of several sub-arrays of indices, each sub-array belonging to
424 // a separate section. The starting offset of each sub-array is stored in the
425 // reserved1 header field of the respective section.
427 // These sub-arrays provide symbol information for sections that store
428 // contiguous sequences of symbol references. These references can be pointers
429 // (e.g. those in the GOT and TLVP sections) or assembly sequences (e.g.
431 class IndirectSymtabSection
: public LinkEditSection
{
433 IndirectSymtabSection();
434 void finalizeContents();
435 uint32_t getNumSymbols() const;
436 uint64_t getRawSize() const override
{
437 return getNumSymbols() * sizeof(uint32_t);
439 bool isNeeded() const override
;
440 void writeTo(uint8_t *buf
) const override
;
444 MachHeaderSection
*header
= nullptr;
445 RebaseSection
*rebase
= nullptr;
446 BindingSection
*binding
= nullptr;
447 WeakBindingSection
*weakBinding
= nullptr;
448 LazyBindingSection
*lazyBinding
= nullptr;
449 ExportSection
*exports
= nullptr;
450 GotSection
*got
= nullptr;
451 TlvPointerSection
*tlvPointers
= nullptr;
452 LazyPointerSection
*lazyPointers
= nullptr;
453 StubsSection
*stubs
= nullptr;
454 StubHelperSection
*stubHelper
= nullptr;
455 ImageLoaderCacheSection
*imageLoaderCache
= nullptr;
459 extern std::vector
<SyntheticSection
*> syntheticSections
;