1//===- SyntheticSections.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_SYNTHETIC_SECTIONS_H
10#define LLD_MACHO_SYNTHETIC_SECTIONS_H
11
12#include "Config.h"
13#include "ExportTrie.h"
14#include "InputSection.h"
15#include "OutputSection.h"
16#include "OutputSegment.h"
17#include "Target.h"
18
19#include "llvm/ADT/PointerUnion.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/Support/MathExtras.h"
22#include "llvm/Support/raw_ostream.h"
23
24namespace llvm {
25class DWARFUnit;
26} // namespace llvm
27
28namespace lld {
29namespace macho {
30
31class Defined;
32class DylibSymbol;
33class LoadCommand;
34class ObjFile;
35class UnwindInfoSection;
36
37class SyntheticSection : public OutputSection {
38public:
39 SyntheticSection(const char *segname, const char *name);
40 virtual ~SyntheticSection() = default;
41
42 static bool classof(const OutputSection *sec) {
43 return sec->kind() == SyntheticKind;
44 }
45
46 const StringRef segname;
47 // This fake InputSection makes it easier for us to write code that applies
48 // generically to both user inputs and synthetics.
49 InputSection *isec;
50};
51
52// All sections in __LINKEDIT should inherit from this.
53class LinkEditSection : public SyntheticSection {
54public:
55 LinkEditSection(const char *segname, const char *name)
56 : SyntheticSection(segname, name) {
57 align = target->wordSize;
58 }
59
60 virtual void finalizeContents() {}
61
62 // Sections in __LINKEDIT are special: their offsets are recorded in the
63 // load commands like LC_DYLD_INFO_ONLY and LC_SYMTAB, instead of in section
64 // headers.
65 bool isHidden() const override final { return true; }
66
67 virtual uint64_t getRawSize() const = 0;
68
69 // codesign (or more specifically libstuff) checks that each section in
70 // __LINKEDIT ends where the next one starts -- no gaps are permitted. We
71 // therefore align every section's start and end points to WordSize.
72 //
73 // NOTE: This assumes that the extra bytes required for alignment can be
74 // zero-valued bytes.
75 uint64_t getSize() const override final {
76 return llvm::alignTo(getRawSize(), align);
77 }
78};
79
80// The header of the Mach-O file, which must have a file offset of zero.
81class MachHeaderSection : public SyntheticSection {
82public:
83 MachHeaderSection();
84 bool isHidden() const override { return true; }
85 uint64_t getSize() const override;
86 void writeTo(uint8_t *buf) const override;
87
88 void addLoadCommand(LoadCommand *);
89
90protected:
91 std::vector<LoadCommand *> loadCommands;
92 uint32_t sizeOfCmds = 0;
93};
94
95// A hidden section that exists solely for the purpose of creating the
96// __PAGEZERO segment, which is used to catch null pointer dereferences.
97class PageZeroSection : public SyntheticSection {
98public:
99 PageZeroSection();
100 bool isHidden() const override { return true; }
101 uint64_t getSize() const override { return target->pageZeroSize; }
102 uint64_t getFileSize() const override { return 0; }
103 void writeTo(uint8_t *buf) const override {}
104};
105
106// This is the base class for the GOT and TLVPointer sections, which are nearly
107// functionally identical -- they will both be populated by dyld with addresses
108// to non-lazily-loaded dylib symbols. The main difference is that the
109// TLVPointerSection stores references to thread-local variables.
110class NonLazyPointerSectionBase : public SyntheticSection {
111public:
112 NonLazyPointerSectionBase(const char *segname, const char *name);
113
114 const llvm::SetVector<const Symbol *> &getEntries() const { return entries; }
115
116 bool isNeeded() const override { return !entries.empty(); }
117
118 uint64_t getSize() const override {
119 return entries.size() * target->wordSize;
120 }
121
122 void writeTo(uint8_t *buf) const override;
123
124 void addEntry(Symbol *sym);
125
126private:
127 llvm::SetVector<const Symbol *> entries;
128};
129
130class GotSection : public NonLazyPointerSectionBase {
131public:
132 GotSection()
133 : NonLazyPointerSectionBase(segment_names::dataConst,
134 section_names::got) {
135 // TODO: section_64::reserved1 should be an index into the indirect symbol
136 // table, which we do not currently emit
137 }
138};
139
140class TlvPointerSection : public NonLazyPointerSectionBase {
141public:
142 TlvPointerSection()
143 : NonLazyPointerSectionBase(segment_names::data,
144 section_names::threadPtrs) {}
145};
146
147struct Location {
148 const InputSection *isec;
149 uint64_t offset;
150
151 Location(const InputSection *isec, uint64_t offset)
152 : isec(isec), offset(offset) {}
153 uint64_t getVA() const { return isec->getVA() + offset; }
154};
155
156// Stores rebase opcodes, which tell dyld where absolute addresses have been
157// encoded in the binary. If the binary is not loaded at its preferred address,
158// dyld has to rebase these addresses by adding an offset to them.
159class RebaseSection : public LinkEditSection {
160public:
161 RebaseSection();
162 void finalizeContents() override;
163 uint64_t getRawSize() const override { return contents.size(); }
164 bool isNeeded() const override { return !locations.empty(); }
165 void writeTo(uint8_t *buf) const override;
166
167 void addEntry(const InputSection *isec, uint64_t offset) {
168 if (config->isPic)
169 locations.push_back({isec, offset});
170 }
171
172private:
173 std::vector<Location> locations;
174 SmallVector<char, 128> contents;
175};
176
177struct BindingEntry {
178 const DylibSymbol *dysym;
179 int64_t addend;
180 Location target;
181 BindingEntry(const DylibSymbol *dysym, int64_t addend, Location target)
182 : dysym(dysym), addend(addend), target(std::move(target)) {}
183};
184
185// Stores bind opcodes for telling dyld which symbols to load non-lazily.
186class BindingSection : public LinkEditSection {
187public:
188 BindingSection();
189 void finalizeContents() override;
190 uint64_t getRawSize() const override { return contents.size(); }
191 bool isNeeded() const override { return !bindings.empty(); }
192 void writeTo(uint8_t *buf) const override;
193
194 void addEntry(const DylibSymbol *dysym, const InputSection *isec,
195 uint64_t offset, int64_t addend = 0) {
196 bindings.emplace_back(dysym, addend, Location(isec, offset));
197 }
198
199private:
200 std::vector<BindingEntry> bindings;
201 SmallVector<char, 128> contents;
202};
203
204struct WeakBindingEntry {
205 const Symbol *symbol;
206 int64_t addend;
207 Location target;
208 WeakBindingEntry(const Symbol *symbol, int64_t addend, Location target)
209 : symbol(symbol), addend(addend), target(std::move(target)) {}
210};
211
212// Stores bind opcodes for telling dyld which weak symbols need coalescing.
213// There are two types of entries in this section:
214//
215// 1) Non-weak definitions: This is a symbol definition that weak symbols in
216// other dylibs should coalesce to.
217//
218// 2) Weak bindings: These tell dyld that a given symbol reference should
219// coalesce to a non-weak definition if one is found. Note that unlike in the
220// entries in the BindingSection, the bindings here only refer to these
221// symbols by name, but do not specify which dylib to load them from.
222class WeakBindingSection : public LinkEditSection {
223public:
224 WeakBindingSection();
225 void finalizeContents() override;
226 uint64_t getRawSize() const override { return contents.size(); }
227 bool isNeeded() const override {
228 return !bindings.empty() || !definitions.empty();
229 }
230
231 void writeTo(uint8_t *buf) const override;
232
233 void addEntry(const Symbol *symbol, const InputSection *isec, uint64_t offset,
234 int64_t addend = 0) {
235 bindings.emplace_back(symbol, addend, Location(isec, offset));
236 }
237
238 bool hasEntry() const { return !bindings.empty(); }
239
240 void addNonWeakDefinition(const Defined *defined) {
241 definitions.emplace_back(defined);
242 }
243
244 bool hasNonWeakDefinition() const { return !definitions.empty(); }
245
246private:
247 std::vector<WeakBindingEntry> bindings;
248 std::vector<const Defined *> definitions;
249 SmallVector<char, 128> contents;
250};
251
252// The following sections implement lazy symbol binding -- very similar to the
253// PLT mechanism in ELF.
254//
255// ELF's .plt section is broken up into two sections in Mach-O: StubsSection
256// and StubHelperSection. Calls to functions in dylibs will end up calling into
257// StubsSection, which contains indirect jumps to addresses stored in the
258// LazyPointerSection (the counterpart to ELF's .plt.got).
259//
260// We will first describe how non-weak symbols are handled.
261//
262// At program start, the LazyPointerSection contains addresses that point into
263// one of the entry points in the middle of the StubHelperSection. The code in
264// StubHelperSection will push on the stack an offset into the
265// LazyBindingSection. The push is followed by a jump to the beginning of the
266// StubHelperSection (similar to PLT0), which then calls into dyld_stub_binder.
267// dyld_stub_binder is a non-lazily-bound symbol, so this call looks it up in
268// the GOT.
269//
270// The stub binder will look up the bind opcodes in the LazyBindingSection at
271// the given offset. The bind opcodes will tell the binder to update the
272// address in the LazyPointerSection to point to the symbol, so that subsequent
273// calls don't have to redo the symbol resolution. The binder will then jump to
274// the resolved symbol.
275//
276// With weak symbols, the situation is slightly different. Since there is no
277// "weak lazy" lookup, function calls to weak symbols are always non-lazily
278// bound. We emit both regular non-lazy bindings as well as weak bindings, in
279// order that the weak bindings may overwrite the non-lazy bindings if an
280// appropriate symbol is found at runtime. However, the bound addresses will
281// still be written (non-lazily) into the LazyPointerSection.
282
283class StubsSection : public SyntheticSection {
284public:
285 StubsSection();
286 uint64_t getSize() const override;
287 bool isNeeded() const override { return !entries.empty(); }
288 void writeTo(uint8_t *buf) const override;
289 const llvm::SetVector<Symbol *> &getEntries() const { return entries; }
290 // Returns whether the symbol was added. Note that every stubs entry will
291 // have a corresponding entry in the LazyPointerSection.
292 bool addEntry(Symbol *);
293
294private:
295 llvm::SetVector<Symbol *> entries;
296};
297
298class StubHelperSection : public SyntheticSection {
299public:
300 StubHelperSection();
301 uint64_t getSize() const override;
302 bool isNeeded() const override;
303 void writeTo(uint8_t *buf) const override;
304
305 void setup();
306
307 DylibSymbol *stubBinder = nullptr;
308 Defined *dyldPrivate = nullptr;
309};
310
311// This section contains space for just a single word, and will be used by dyld
312// to cache an address to the image loader it uses. Note that unlike the other
313// synthetic sections, which are OutputSections, the ImageLoaderCacheSection is
314// an InputSection that gets merged into the __data OutputSection.
315class ImageLoaderCacheSection : public InputSection {
316public:
317 ImageLoaderCacheSection();
318 uint64_t getSize() const override { return target->wordSize; }
319};
320
321// Note that this section may also be targeted by non-lazy bindings. In
322// particular, this happens when branch relocations target weak symbols.
323class LazyPointerSection : public SyntheticSection {
324public:
325 LazyPointerSection();
326 uint64_t getSize() const override;
327 bool isNeeded() const override;
328 void writeTo(uint8_t *buf) const override;
329};
330
331class LazyBindingSection : public LinkEditSection {
332public:
333 LazyBindingSection();
334 void finalizeContents() override;
335 uint64_t getRawSize() const override { return contents.size(); }
336 bool isNeeded() const override { return !entries.empty(); }
337 void writeTo(uint8_t *buf) const override;
338 // Note that every entry here will by referenced by a corresponding entry in
339 // the StubHelperSection.
340 void addEntry(DylibSymbol *dysym);
341 const llvm::SetVector<DylibSymbol *> &getEntries() const { return entries; }
342
343private:
344 uint32_t encode(const DylibSymbol &);
345
346 llvm::SetVector<DylibSymbol *> entries;
347 SmallVector<char, 128> contents;
348 llvm::raw_svector_ostream os{contents};
349};
350
351// Stores a trie that describes the set of exported symbols.
352class ExportSection : public LinkEditSection {
353public:
354 ExportSection();
355 void finalizeContents() override;
356 uint64_t getRawSize() const override { return size; }
357 void writeTo(uint8_t *buf) const override;
358
359 bool hasWeakSymbol = false;
360
361private:
362 TrieBuilder trieBuilder;
363 size_t size = 0;
364};
365
366class FunctionStartsSection : public LinkEditSection {
367public:
368 FunctionStartsSection();
369 void finalizeContents() override;
370 uint64_t getRawSize() const override { return contents.size(); }
371 void writeTo(uint8_t *buf) const override;
372
373private:
374 SmallVector<char, 128> contents;
375};
376
377// Stores the strings referenced by the symbol table.
378class StringTableSection : public LinkEditSection {
379public:
380 StringTableSection();
381 // Returns the start offset of the added string.
382 uint32_t addString(StringRef);
383 uint64_t getRawSize() const override { return size; }
384 void writeTo(uint8_t *buf) const override;
385
386 static constexpr size_t emptyStringIndex = 1;
387
388private:
389 // ld64 emits string tables which start with a space and a zero byte. We
390 // match its behavior here since some tools depend on it.
391 // Consequently, the empty string will be at index 1, not zero.
392 std::vector<StringRef> strings{" "};
393 size_t size = 2;
394};
395
396struct SymtabEntry {
397 Symbol *sym;
398 size_t strx;
399};
400
401struct StabsEntry {
402 uint8_t type = 0;
403 uint32_t strx = StringTableSection::emptyStringIndex;
404 uint8_t sect = 0;
405 uint16_t desc = 0;
406 uint64_t value = 0;
407
408 StabsEntry() = default;
409 explicit StabsEntry(uint8_t type) : type(type) {}
410};
411
412// Symbols of the same type must be laid out contiguously: we choose to emit
413// all local symbols first, then external symbols, and finally undefined
414// symbols. For each symbol type, the LC_DYSYMTAB load command will record the
415// range (start index and total number) of those symbols in the symbol table.
416class SymtabSection : public LinkEditSection {
417public:
418 void finalizeContents() override;
419 uint32_t getNumSymbols() const;
420 uint32_t getNumLocalSymbols() const {
421 return stabs.size() + localSymbols.size();
422 }
423 uint32_t getNumExternalSymbols() const { return externalSymbols.size(); }
424 uint32_t getNumUndefinedSymbols() const { return undefinedSymbols.size(); }
425
426private:
427 void emitBeginSourceStab(llvm::DWARFUnit *compileUnit);
428 void emitEndSourceStab();
429 void emitObjectFileStab(ObjFile *);
430 void emitEndFunStab(Defined *);
431 void emitStabs();
432
433protected:
434 SymtabSection(StringTableSection &);
435
436 StringTableSection &stringTableSection;
437 // STABS symbols are always local symbols, but we represent them with special
438 // entries because they may use fields like n_sect and n_desc differently.
439 std::vector<StabsEntry> stabs;
440 std::vector<SymtabEntry> localSymbols;
441 std::vector<SymtabEntry> externalSymbols;
442 std::vector<SymtabEntry> undefinedSymbols;
443};
444
445template <class LP> SymtabSection *makeSymtabSection(StringTableSection &);
446
447// The indirect symbol table is a list of 32-bit integers that serve as indices
448// into the (actual) symbol table. The indirect symbol table is a
449// concatenation of several sub-arrays of indices, each sub-array belonging to
450// a separate section. The starting offset of each sub-array is stored in the
451// reserved1 header field of the respective section.
452//
453// These sub-arrays provide symbol information for sections that store
454// contiguous sequences of symbol references. These references can be pointers
455// (e.g. those in the GOT and TLVP sections) or assembly sequences (e.g.
456// function stubs).
457class IndirectSymtabSection : public LinkEditSection {
458public:
459 IndirectSymtabSection();
460 void finalizeContents() override;
461 uint32_t getNumSymbols() const;
462 uint64_t getRawSize() const override {
463 return getNumSymbols() * sizeof(uint32_t);
464 }
465 bool isNeeded() const override;
466 void writeTo(uint8_t *buf) const override;
467};
468
469// The code signature comes at the very end of the linked output file.
470class CodeSignatureSection : public LinkEditSection {
471public:
472 static constexpr uint8_t blockSizeShift = 12;
473 static constexpr size_t blockSize = (1 << blockSizeShift); // 4 KiB
474 static constexpr size_t hashSize = 256 / 8;
475 static constexpr size_t blobHeadersSize = llvm::alignTo<8>(
476 sizeof(llvm::MachO::CS_SuperBlob) + sizeof(llvm::MachO::CS_BlobIndex));
477 static constexpr uint32_t fixedHeadersSize =
478 blobHeadersSize + sizeof(llvm::MachO::CS_CodeDirectory);
479
480 uint32_t fileNamePad = 0;
481 uint32_t allHeadersSize = 0;
482 StringRef fileName;
483
484 CodeSignatureSection();
485 uint64_t getRawSize() const override;
486 bool isNeeded() const override { return true; }
487 void writeTo(uint8_t *buf) const override;
488 uint32_t getBlockCount() const;
489 void writeHashes(uint8_t *buf) const;
490};
491
492class BitcodeBundleSection : public SyntheticSection {
493public:
494 BitcodeBundleSection();
495 uint64_t getSize() const override { return xarSize; }
496 void finalize() override;
497 void writeTo(uint8_t *buf) const override;
498
499private:
500 llvm::SmallString<261> xarPath;
501 uint64_t xarSize;
502};
503
504static_assert((CodeSignatureSection::blobHeadersSize % 8) == 0, "");
505static_assert((CodeSignatureSection::fixedHeadersSize % 8) == 0, "");
506
507struct InStruct {
508 MachHeaderSection *header = nullptr;
509 RebaseSection *rebase = nullptr;
510 BindingSection *binding = nullptr;
511 WeakBindingSection *weakBinding = nullptr;
512 LazyBindingSection *lazyBinding = nullptr;
513 ExportSection *exports = nullptr;
514 GotSection *got = nullptr;
515 TlvPointerSection *tlvPointers = nullptr;
516 LazyPointerSection *lazyPointers = nullptr;
517 StubsSection *stubs = nullptr;
518 StubHelperSection *stubHelper = nullptr;
519 ImageLoaderCacheSection *imageLoaderCache = nullptr;
520 UnwindInfoSection *unwindInfo = nullptr;
521};
522
523extern InStruct in;
524extern std::vector<SyntheticSection *> syntheticSections;
525
526void createSyntheticSymbols();
527
528} // namespace macho
529} // namespace lld
530
531#endif
532