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#include "Writer.h"
19
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/BinaryFormat/MachO.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Support/raw_ostream.h"
26
27namespace llvm {
28class DWARFUnit;
29} // namespace llvm
30
31namespace lld::macho {
32
33class Defined;
34class DylibSymbol;
35class LoadCommand;
36class ObjFile;
37class UnwindInfoSection;
38
39class SyntheticSection : public OutputSection {
40public:
41 SyntheticSection(const char *segname, const char *name);
42 virtual ~SyntheticSection() = default;
43
44 static bool classof(const OutputSection *sec) {
45 return sec->kind() == SyntheticKind;
46 }
47
48 StringRef segname;
49 // This fake InputSection makes it easier for us to write code that applies
50 // generically to both user inputs and synthetics.
51 InputSection *isec;
52};
53
54// All sections in __LINKEDIT should inherit from this.
55class LinkEditSection : public SyntheticSection {
56public:
57 LinkEditSection(const char *segname, const char *name)
58 : SyntheticSection(segname, name) {
59 align = target->wordSize;
60 }
61
62 // Implementations of this method can assume that the regular (non-__LINKEDIT)
63 // sections already have their addresses assigned.
64 virtual void finalizeContents() {}
65
66 // Sections in __LINKEDIT are special: their offsets are recorded in the
67 // load commands like LC_DYLD_INFO_ONLY and LC_SYMTAB, instead of in section
68 // headers.
69 bool isHidden() const final { return true; }
70
71 virtual uint64_t getRawSize() const = 0;
72
73 // codesign (or more specifically libstuff) checks that each section in
74 // __LINKEDIT ends where the next one starts -- no gaps are permitted. We
75 // therefore align every section's start and end points to WordSize.
76 //
77 // NOTE: This assumes that the extra bytes required for alignment can be
78 // zero-valued bytes.
79 uint64_t getSize() const final { return llvm::alignTo(Value: getRawSize(), Align: align); }
80};
81
82// The header of the Mach-O file, which must have a file offset of zero.
83class MachHeaderSection final : public SyntheticSection {
84public:
85 MachHeaderSection();
86 bool isHidden() const override { return true; }
87 uint64_t getSize() const override;
88 void writeTo(uint8_t *buf) const override;
89
90 void addLoadCommand(LoadCommand *);
91
92protected:
93 std::vector<LoadCommand *> loadCommands;
94 uint32_t sizeOfCmds = 0;
95};
96
97// A hidden section that exists solely for the purpose of creating the
98// __PAGEZERO segment, which is used to catch null pointer dereferences.
99class PageZeroSection final : public SyntheticSection {
100public:
101 PageZeroSection();
102 bool isHidden() const override { return true; }
103 bool isNeeded() const override { return target->pageZeroSize != 0; }
104 uint64_t getSize() const override { return target->pageZeroSize; }
105 uint64_t getFileSize() const override { return 0; }
106 void writeTo(uint8_t *buf) const override {}
107};
108
109// The __got section, populated by dyld with addresses to non-lazily-loaded
110// dylib symbols, including TLV descriptors.
111class GotSection final : public SyntheticSection {
112public:
113 GotSection();
114 const llvm::SetVector<const Symbol *> &getEntries() const { return entries; }
115 bool isNeeded() const override { return !entries.empty(); }
116 uint64_t getSize() const override {
117 return entries.size() * target->wordSize;
118 }
119 void writeTo(uint8_t *buf) const override;
120 void addEntry(Symbol *sym);
121 uint64_t getVA(uint32_t gotIndex) const {
122 return addr + gotIndex * target->wordSize;
123 }
124
125private:
126 llvm::SetVector<const Symbol *> entries;
127};
128
129struct Location {
130 const InputSection *isec;
131 uint64_t offset;
132
133 Location(const InputSection *isec, uint64_t offset)
134 : isec(isec), offset(offset) {}
135 uint64_t getVA() const { return isec->getVA(off: offset); }
136};
137
138// Stores rebase opcodes, which tell dyld where absolute addresses have been
139// encoded in the binary. If the binary is not loaded at its preferred address,
140// dyld has to rebase these addresses by adding an offset to them.
141class RebaseSection final : public LinkEditSection {
142public:
143 RebaseSection();
144 void finalizeContents() override;
145 uint64_t getRawSize() const override { return contents.size(); }
146 bool isNeeded() const override { return !locations.empty(); }
147 void writeTo(uint8_t *buf) const override;
148
149 void addEntry(const InputSection *isec, uint64_t offset) {
150 if (config->isPic)
151 locations.emplace_back(args&: isec, args&: offset);
152 }
153
154private:
155 std::vector<Location> locations;
156 SmallVector<char, 128> contents;
157};
158
159struct BindingEntry {
160 int64_t addend;
161 Location target;
162 BindingEntry(int64_t addend, Location target)
163 : addend(addend), target(target) {}
164};
165
166template <class Sym>
167using BindingsMap = llvm::DenseMap<Sym, std::vector<BindingEntry>>;
168
169// Stores bind opcodes for telling dyld which symbols to load non-lazily.
170class BindingSection final : public LinkEditSection {
171public:
172 BindingSection();
173 void finalizeContents() override;
174 uint64_t getRawSize() const override { return contents.size(); }
175 bool isNeeded() const override { return !bindingsMap.empty(); }
176 void writeTo(uint8_t *buf) const override;
177
178 void addEntry(const Symbol *dysym, const InputSection *isec, uint64_t offset,
179 int64_t addend = 0) {
180 bindingsMap[dysym].emplace_back(args&: addend, args: Location(isec, offset));
181 }
182
183private:
184 BindingsMap<const Symbol *> bindingsMap;
185 SmallVector<char, 128> contents;
186};
187
188// Stores bind opcodes for telling dyld which weak symbols need coalescing.
189// There are two types of entries in this section:
190//
191// 1) Non-weak definitions: This is a symbol definition that weak symbols in
192// other dylibs should coalesce to.
193//
194// 2) Weak bindings: These tell dyld that a given symbol reference should
195// coalesce to a non-weak definition if one is found. Note that unlike the
196// entries in the BindingSection, the bindings here only refer to these
197// symbols by name, but do not specify which dylib to load them from.
198class WeakBindingSection final : public LinkEditSection {
199public:
200 WeakBindingSection();
201 void finalizeContents() override;
202 uint64_t getRawSize() const override { return contents.size(); }
203 bool isNeeded() const override {
204 return !bindingsMap.empty() || !definitions.empty();
205 }
206
207 void writeTo(uint8_t *buf) const override;
208
209 void addEntry(const Symbol *symbol, const InputSection *isec, uint64_t offset,
210 int64_t addend = 0) {
211 bindingsMap[symbol].emplace_back(args&: addend, args: Location(isec, offset));
212 }
213
214 bool hasEntry() const { return !bindingsMap.empty(); }
215
216 void addNonWeakDefinition(const Defined *defined) {
217 definitions.emplace_back(args&: defined);
218 }
219
220 bool hasNonWeakDefinition() const { return !definitions.empty(); }
221
222private:
223 BindingsMap<const Symbol *> bindingsMap;
224 std::vector<const Defined *> definitions;
225 SmallVector<char, 128> contents;
226};
227
228// The following sections implement lazy symbol binding -- very similar to the
229// PLT mechanism in ELF.
230//
231// ELF's .plt section is broken up into two sections in Mach-O: StubsSection
232// and StubHelperSection. Calls to functions in dylibs will end up calling into
233// StubsSection, which contains indirect jumps to addresses stored in the
234// LazyPointerSection (the counterpart to ELF's .plt.got).
235//
236// We will first describe how non-weak symbols are handled.
237//
238// At program start, the LazyPointerSection contains addresses that point into
239// one of the entry points in the middle of the StubHelperSection. The code in
240// StubHelperSection will push on the stack an offset into the
241// LazyBindingSection. The push is followed by a jump to the beginning of the
242// StubHelperSection (similar to PLT0), which then calls into dyld_stub_binder.
243// dyld_stub_binder is a non-lazily-bound symbol, so this call looks it up in
244// the GOT.
245//
246// The stub binder will look up the bind opcodes in the LazyBindingSection at
247// the given offset. The bind opcodes will tell the binder to update the
248// address in the LazyPointerSection to point to the symbol, so that subsequent
249// calls don't have to redo the symbol resolution. The binder will then jump to
250// the resolved symbol.
251//
252// With weak symbols, the situation is slightly different. Since there is no
253// "weak lazy" lookup, function calls to weak symbols are always non-lazily
254// bound. We emit both regular non-lazy bindings as well as weak bindings, in
255// order that the weak bindings may overwrite the non-lazy bindings if an
256// appropriate symbol is found at runtime. However, the bound addresses will
257// still be written (non-lazily) into the LazyPointerSection.
258//
259// Symbols are always bound eagerly when chained fixups are used. In that case,
260// StubsSection contains indirect jumps to addresses stored in the GotSection.
261// The GOT directly contains the fixup entries, which will be replaced by the
262// address of the target symbols on load. LazyPointerSection and
263// StubHelperSection are not used.
264
265class StubsSection final : public SyntheticSection {
266public:
267 StubsSection();
268 uint64_t getSize() const override;
269 bool isNeeded() const override { return !entries.empty(); }
270 void finalize() override;
271 void writeTo(uint8_t *buf) const override;
272 const llvm::SetVector<Symbol *> &getEntries() const { return entries; }
273 // Creates a stub for the symbol and the corresponding entry in the
274 // LazyPointerSection.
275 void addEntry(Symbol *);
276 uint64_t getVA(uint32_t stubsIndex) const {
277 assert(isFinal || target->usesThunks());
278 // ConcatOutputSection::finalize() can seek the address of a
279 // stub before its address is assigned. Before __stubs is
280 // finalized, return a contrived out-of-range address.
281 return isFinal ? addr + stubsIndex * target->stubSize
282 : TargetInfo::outOfRangeVA;
283 }
284
285 bool isFinal = false; // is address assigned?
286
287private:
288 llvm::SetVector<Symbol *> entries;
289};
290
291class StubHelperSection final : public SyntheticSection {
292public:
293 StubHelperSection();
294 uint64_t getSize() const override;
295 bool isNeeded() const override;
296 void writeTo(uint8_t *buf) const override;
297
298 void setUp();
299
300 DylibSymbol *stubBinder = nullptr;
301 Defined *dyldPrivate = nullptr;
302};
303
304class ObjCSelRefsHelper {
305public:
306 static void initialize();
307 static void cleanup();
308
309 static ConcatInputSection *getSelRef(StringRef methname);
310 static ConcatInputSection *makeSelRef(StringRef methname);
311
312private:
313 static llvm::DenseMap<llvm::CachedHashStringRef, ConcatInputSection *>
314 methnameToSelref;
315};
316
317// Objective-C stubs are hoisted objc_msgSend calls per selector called in the
318// program. Apple Clang produces undefined symbols to each stub, such as
319// '_objc_msgSend$foo', which are then synthesized by the linker. The stubs
320// load the particular selector 'foo' from __objc_selrefs, setting it to the
321// first argument of the objc_msgSend call, and then jumps to objc_msgSend. The
322// actual stub contents are mirrored from ld64.
323class ObjCStubsSection final : public SyntheticSection {
324public:
325 ObjCStubsSection();
326 void addEntry(Symbol *sym);
327 uint64_t getSize() const override;
328 bool isNeeded() const override { return !symbols.empty(); }
329 void finalize() override { isec->isFinal = true; }
330 void writeTo(uint8_t *buf) const override;
331 void setUp();
332
333 static constexpr llvm::StringLiteral symbolPrefix = "_objc_msgSend$";
334 static bool isObjCStubSymbol(Symbol *sym);
335 static StringRef getMethname(Symbol *sym);
336 ArrayRef<Defined *> getSymbols() const { return symbols; }
337
338 /// Stably sort the stubs by \p priorities and reassign their offsets. Must
339 /// run before addresses are assigned.
340 void sortSymbols(const llvm::DenseMap<const Symbol *, int> &priorities);
341
342private:
343 size_t getStubSize() const;
344
345 std::vector<Defined *> symbols;
346 Symbol *objcMsgSend = nullptr;
347};
348
349// Note that this section may also be targeted by non-lazy bindings. In
350// particular, this happens when branch relocations target weak symbols.
351class LazyPointerSection final : public SyntheticSection {
352public:
353 LazyPointerSection();
354 uint64_t getSize() const override;
355 bool isNeeded() const override;
356 void writeTo(uint8_t *buf) const override;
357 uint64_t getVA(uint32_t index) const {
358 return addr + (index << target->p2WordSize);
359 }
360};
361
362class LazyBindingSection final : public LinkEditSection {
363public:
364 LazyBindingSection();
365 void finalizeContents() override;
366 uint64_t getRawSize() const override { return contents.size(); }
367 bool isNeeded() const override { return !entries.empty(); }
368 void writeTo(uint8_t *buf) const override;
369 // Note that every entry here will by referenced by a corresponding entry in
370 // the StubHelperSection.
371 void addEntry(Symbol *dysym);
372 const llvm::SetVector<Symbol *> &getEntries() const { return entries; }
373
374private:
375 uint32_t encode(const Symbol &);
376
377 llvm::SetVector<Symbol *> entries;
378 SmallVector<char, 128> contents;
379 llvm::raw_svector_ostream os{contents};
380};
381
382// Stores a trie that describes the set of exported symbols.
383class ExportSection final : public LinkEditSection {
384public:
385 ExportSection();
386 void finalizeContents() override;
387 uint64_t getRawSize() const override { return size; }
388 bool isNeeded() const override { return size; }
389 void writeTo(uint8_t *buf) const override;
390
391 bool hasWeakSymbol = false;
392
393private:
394 TrieBuilder trieBuilder;
395 size_t size = 0;
396};
397
398// Stores 'data in code' entries that describe the locations of data regions
399// inside code sections. This is used by llvm-objdump to distinguish jump tables
400// and stop them from being disassembled as instructions.
401class DataInCodeSection final : public LinkEditSection {
402public:
403 DataInCodeSection();
404 void finalizeContents() override;
405 uint64_t getRawSize() const override {
406 return sizeof(llvm::MachO::data_in_code_entry) * entries.size();
407 }
408 void writeTo(uint8_t *buf) const override;
409
410private:
411 std::vector<llvm::MachO::data_in_code_entry> entries;
412};
413
414// Stores ULEB128 delta encoded addresses of functions.
415class FunctionStartsSection final : public LinkEditSection {
416public:
417 FunctionStartsSection();
418 void finalizeContents() override;
419 uint64_t getRawSize() const override { return contents.size(); }
420 void writeTo(uint8_t *buf) const override;
421
422private:
423 SmallVector<char, 128> contents;
424};
425
426// Stores the strings referenced by the symbol table.
427class StringTableSection final : public LinkEditSection {
428public:
429 StringTableSection();
430 // Returns the start offset of the added string.
431 uint32_t addString(StringRef);
432 uint64_t getRawSize() const override { return size; }
433 void writeTo(uint8_t *buf) const override;
434
435 static constexpr size_t emptyStringIndex = 1;
436
437private:
438 // ld64 emits string tables which start with a space and a zero byte. We
439 // match its behavior here since some tools depend on it.
440 // Consequently, the empty string will be at index 1, not zero.
441 std::vector<StringRef> strings{" "};
442 llvm::DenseMap<llvm::CachedHashStringRef, uint32_t> stringMap;
443 size_t size = 2;
444};
445
446struct SymtabEntry {
447 Symbol *sym;
448 size_t strx;
449};
450
451struct StabsEntry {
452 uint8_t type = 0;
453 uint32_t strx = StringTableSection::emptyStringIndex;
454 uint8_t sect = 0;
455 uint16_t desc = 0;
456 uint64_t value = 0;
457
458 StabsEntry() = default;
459 explicit StabsEntry(uint8_t type) : type(type) {}
460};
461
462// Symbols of the same type must be laid out contiguously: we choose to emit
463// all local symbols first, then external symbols, and finally undefined
464// symbols. For each symbol type, the LC_DYSYMTAB load command will record the
465// range (start index and total number) of those symbols in the symbol table.
466class SymtabSection : public LinkEditSection {
467public:
468 void finalizeContents() override;
469 uint32_t getNumSymbols() const;
470 uint32_t getNumLocalSymbols() const {
471 return stabs.size() + localSymbols.size();
472 }
473 uint32_t getNumExternalSymbols() const { return externalSymbols.size(); }
474 uint32_t getNumUndefinedSymbols() const { return undefinedSymbols.size(); }
475
476private:
477 void emitBeginSourceStab(StringRef);
478 void emitEndSourceStab();
479 void emitObjectFileStab(ObjFile *);
480 void emitEndFunStab(Defined *);
481 Defined *getFuncBodySym(Defined *);
482 void emitStabs();
483
484protected:
485 SymtabSection(StringTableSection &);
486
487 StringTableSection &stringTableSection;
488 // STABS symbols are always local symbols, but we represent them with special
489 // entries because they may use fields like n_sect and n_desc differently.
490 std::vector<StabsEntry> stabs;
491 std::vector<SymtabEntry> localSymbols;
492 std::vector<SymtabEntry> externalSymbols;
493 std::vector<SymtabEntry> undefinedSymbols;
494};
495
496template <class LP> SymtabSection *makeSymtabSection(StringTableSection &);
497
498// The indirect symbol table is a list of 32-bit integers that serve as indices
499// into the (actual) symbol table. The indirect symbol table is a
500// concatenation of several sub-arrays of indices, each sub-array belonging to
501// a separate section. The starting offset of each sub-array is stored in the
502// reserved1 header field of the respective section.
503//
504// These sub-arrays provide symbol information for sections that store
505// contiguous sequences of symbol references. These references can be pointers
506// (e.g. those in the GOT and TLVP sections) or assembly sequences (e.g.
507// function stubs).
508class IndirectSymtabSection final : public LinkEditSection {
509public:
510 IndirectSymtabSection();
511 void finalizeContents() override;
512 uint32_t getNumSymbols() const;
513 uint64_t getRawSize() const override {
514 return getNumSymbols() * sizeof(uint32_t);
515 }
516 bool isNeeded() const override;
517 void writeTo(uint8_t *buf) const override;
518};
519
520// The code signature comes at the very end of the linked output file.
521class CodeSignatureSection final : public LinkEditSection {
522public:
523 // NOTE: These values are duplicated in llvm-objcopy's MachO/Object.h file
524 // and any changes here, should be repeated there.
525 static constexpr uint8_t blockSizeShift = 12;
526 static constexpr size_t blockSize = (1 << blockSizeShift); // 4 KiB
527 static constexpr size_t hashSize = 256 / 8;
528 static constexpr size_t blobHeadersSize = llvm::alignTo<8>(
529 Value: sizeof(llvm::MachO::CS_SuperBlob) + sizeof(llvm::MachO::CS_BlobIndex));
530 static constexpr uint32_t fixedHeadersSize =
531 blobHeadersSize + sizeof(llvm::MachO::CS_CodeDirectory);
532
533 uint32_t fileNamePad = 0;
534 uint32_t allHeadersSize = 0;
535 StringRef fileName;
536
537 CodeSignatureSection();
538 uint64_t getRawSize() const override;
539 bool isNeeded() const override { return true; }
540 void writeTo(uint8_t *buf) const override;
541 uint32_t getBlockCount() const;
542 void writeHashes(uint8_t *buf) const;
543};
544
545class CStringSection : public SyntheticSection {
546public:
547 CStringSection(const char *name);
548 void addInput(CStringInputSection *);
549 uint64_t getSize() const override { return size; }
550 virtual void finalizeContents();
551 bool isNeeded() const override { return !inputs.empty(); }
552 void writeTo(uint8_t *buf) const override;
553
554 std::vector<CStringInputSection *> inputs;
555
556private:
557 uint64_t size;
558};
559
560class DeduplicatedCStringSection final : public CStringSection {
561public:
562 DeduplicatedCStringSection(const char *name) : CStringSection(name){};
563 uint64_t getSize() const override { return size; }
564 void finalizeContents() override;
565 void writeTo(uint8_t *buf) const override;
566 uint64_t getStringOffset(StringRef str) const;
567
568private:
569 llvm::DenseMap<llvm::CachedHashStringRef, uint64_t> stringOffsetMap;
570 size_t size = 0;
571};
572
573/*
574 * This section contains deduplicated literal values. The 16-byte values are
575 * laid out first, followed by the 8- and then the 4-byte ones.
576 */
577class WordLiteralSection final : public SyntheticSection {
578public:
579 using UInt128 = std::pair<uint64_t, uint64_t>;
580 // I don't think the standard guarantees the size of a pair, so let's make
581 // sure it's exact -- that way we can construct it via `mmap`.
582 static_assert(sizeof(UInt128) == 16);
583
584 WordLiteralSection();
585 void addInput(WordLiteralInputSection *);
586 void finalizeContents();
587 void writeTo(uint8_t *buf) const override;
588
589 uint64_t getSize() const override {
590 return literal16Map.size() * 16 + literal8Map.size() * 8 +
591 literal4Map.size() * 4;
592 }
593
594 bool isNeeded() const override {
595 return !literal16Map.empty() || !literal4Map.empty() ||
596 !literal8Map.empty();
597 }
598
599 uint64_t getLiteral16Offset(uintptr_t buf) const {
600 return literal16Map.at(Val: *reinterpret_cast<const UInt128 *>(buf)) * 16;
601 }
602
603 uint64_t getLiteral8Offset(uintptr_t buf) const {
604 return literal16Map.size() * 16 +
605 literal8Map.at(Val: *reinterpret_cast<const uint64_t *>(buf)) * 8;
606 }
607
608 uint64_t getLiteral4Offset(uintptr_t buf) const {
609 return literal16Map.size() * 16 + literal8Map.size() * 8 +
610 literal4Map.at(Val: *reinterpret_cast<const uint32_t *>(buf)) * 4;
611 }
612
613private:
614 std::vector<WordLiteralInputSection *> inputs;
615
616 // Literal values can be any bit pattern.
617 llvm::DenseMap<UInt128, uint64_t> literal16Map;
618 llvm::DenseMap<uint64_t, uint64_t> literal8Map;
619 llvm::DenseMap<uint32_t, uint64_t> literal4Map;
620};
621
622class ObjCImageInfoSection final : public SyntheticSection {
623public:
624 ObjCImageInfoSection();
625 bool isNeeded() const override { return !files.empty(); }
626 uint64_t getSize() const override { return 8; }
627 void addFile(const InputFile *file) {
628 assert(!file->objCImageInfo.empty());
629 files.push_back(x: file);
630 }
631 void finalizeContents();
632 void writeTo(uint8_t *buf) const override;
633
634private:
635 struct ImageInfo {
636 uint8_t swiftVersion = 0;
637 bool hasCategoryClassProperties = false;
638 } info;
639 static ImageInfo parseImageInfo(const InputFile *);
640 std::vector<const InputFile *> files; // files with image info
641};
642
643// This section stores 32-bit __TEXT segment offsets of initializer functions.
644//
645// The compiler stores pointers to initializers in __mod_init_func. These need
646// to be fixed up at load time, which takes time and dirties memory. By
647// synthesizing InitOffsetsSection from them, this data can live in the
648// read-only __TEXT segment instead. This section is used by default when
649// chained fixups are enabled.
650//
651// There is no similar counterpart to __mod_term_func, as that section is
652// deprecated, and static destructors are instead handled by registering them
653// via __cxa_atexit from an autogenerated initializer function (see D121736).
654class InitOffsetsSection final : public SyntheticSection {
655public:
656 InitOffsetsSection();
657 bool isNeeded() const override { return !sections.empty(); }
658 uint64_t getSize() const override;
659 void writeTo(uint8_t *buf) const override;
660 void setUp();
661
662 void addInput(ConcatInputSection *isec) { sections.push_back(x: isec); }
663 const std::vector<ConcatInputSection *> &inputs() const { return sections; }
664
665private:
666 std::vector<ConcatInputSection *> sections;
667};
668
669// This SyntheticSection is for the __objc_methlist section, which contains
670// relative method lists if the -objc_relative_method_lists option is enabled.
671class ObjCMethListSection final : public SyntheticSection {
672public:
673 ObjCMethListSection();
674
675 static bool isMethodList(const ConcatInputSection *isec);
676 void addInput(ConcatInputSection *isec) { inputs.push_back(x: isec); }
677 std::vector<ConcatInputSection *> getInputs() { return inputs; }
678
679 void setUp();
680 void finalize() override;
681 bool isNeeded() const override { return !inputs.empty(); }
682 uint64_t getSize() const override { return sectionSize; }
683 void writeTo(uint8_t *bufStart) const override;
684
685private:
686 void readMethodListHeader(const uint8_t *buf, uint32_t &structSizeAndFlags,
687 uint32_t &structCount) const;
688 void writeMethodListHeader(uint8_t *buf, uint32_t structSizeAndFlags,
689 uint32_t structCount) const;
690 uint32_t computeRelativeMethodListSize(uint32_t absoluteMethodListSize) const;
691 void writeRelativeOffsetForIsec(const ConcatInputSection *isec, uint8_t *buf,
692 uint32_t &inSecOff, uint32_t &outSecOff,
693 bool useSelRef) const;
694 uint32_t writeRelativeMethodList(const ConcatInputSection *isec,
695 uint8_t *buf) const;
696
697 static constexpr uint32_t methodListHeaderSize =
698 /*structSizeAndFlags*/ sizeof(uint32_t) +
699 /*structCount*/ sizeof(uint32_t);
700 // Relative method lists are supported only for 3-pointer method lists
701 static constexpr uint32_t pointersPerStruct = 3;
702 // The runtime identifies relative method lists via this magic value
703 static constexpr uint32_t relMethodHeaderFlag = 0x80000000;
704 // In the method list header, the first 2 bytes are the size of struct
705 static constexpr uint32_t structSizeMask = 0x0000FFFF;
706 // In the method list header, the last 2 bytes are the flags for the struct
707 static constexpr uint32_t structFlagsMask = 0xFFFF0000;
708 // Relative method lists have 4 byte alignment as all data in the InputSection
709 // is 4 byte
710 static constexpr uint32_t relativeOffsetSize = sizeof(uint32_t);
711
712 // The output size of the __objc_methlist section, computed during finalize()
713 uint32_t sectionSize = 0;
714 std::vector<ConcatInputSection *> inputs;
715};
716
717// Chained fixups are a replacement for classic dyld opcodes. In this format,
718// most of the metadata necessary for binding symbols and rebasing addresses is
719// stored directly in the memory location that will have the fixup applied.
720//
721// The fixups form singly linked lists; each one covering a single page in
722// memory. The __LINKEDIT,__chainfixups section stores the page offset of the
723// first fixup of each page; the rest can be found by walking the chain using
724// the offset that is embedded in each entry.
725//
726// This setup allows pages to be relocated lazily at page-in time and without
727// being dirtied. The kernel can discard and load them again as needed. This
728// technique, called page-in linking, was introduced in macOS 13.
729//
730// The benefits of this format are:
731// - smaller __LINKEDIT segment, as most of the fixup information is stored in
732// the data segment
733// - faster startup, since not all relocations need to be done upfront
734// - slightly lower memory usage, as fewer pages are dirtied
735//
736// Userspace x86_64 and arm64 binaries have two types of fixup entries:
737// - Rebase entries contain an absolute address, to which the object's load
738// address will be added to get the final value. This is used for loading
739// the address of a symbol defined in the same binary.
740// - Binding entries are mostly used for symbols imported from other dylibs,
741// but for weakly bound and interposable symbols as well. They are looked up
742// by a (symbol name, library) pair stored in __chainfixups. This import
743// entry also encodes whether the import is weak (i.e. if the symbol is
744// missing, it should be set to null instead of producing a load error).
745// The fixup encodes an ordinal associated with the import, and an optional
746// addend.
747//
748// The entries are tightly packed 64-bit bitfields. One of the bits specifies
749// which kind of fixup to interpret them as.
750//
751// LLD generates the fixup data in 5 stages:
752// 1. While scanning relocations, we make a note of each location that needs
753// a fixup by calling addRebase() or addBinding(). During this, we assign
754// a unique ordinal for each (symbol name, library, addend) import tuple.
755// 2. After addresses have been assigned to all sections, and thus the memory
756// layout of the linked image is final; finalizeContents() is called. Here,
757// the page offsets of the chain start entries are calculated.
758// 3. ChainedFixupsSection::writeTo() writes the page start offsets and the
759// imports table to the output file.
760// 4. Each section's fixup entries are encoded and written to disk in
761// ConcatInputSection::writeTo(), but without writing the offsets that form
762// the chain.
763// 5. Finally, each page's (which might correspond to multiple sections)
764// fixups are linked together in Writer::buildFixupChains().
765class ChainedFixupsSection final : public LinkEditSection {
766public:
767 ChainedFixupsSection();
768 void finalizeContents() override;
769 uint64_t getRawSize() const override { return size; }
770 bool isNeeded() const override;
771 void writeTo(uint8_t *buf) const override;
772
773 void addRebase(const InputSection *isec, uint64_t offset) {
774 locations.emplace_back(args&: isec, args&: offset);
775 }
776 void addBinding(const Symbol *dysym, const InputSection *isec,
777 uint64_t offset, int64_t addend = 0);
778
779 void setHasNonWeakDefinition() { hasNonWeakDef = true; }
780
781 // Returns an (ordinal, inline addend) tuple used by dyld_chained_ptr_64_bind.
782 std::pair<uint32_t, uint8_t> getBinding(const Symbol *sym,
783 int64_t addend) const;
784
785 const std::vector<Location> &getLocations() const { return locations; }
786
787 bool hasWeakBinding() const { return hasWeakBind; }
788 bool hasNonWeakDefinition() const { return hasNonWeakDef; }
789
790private:
791 // Location::offset initially stores the offset within an InputSection, but
792 // contains output segment offsets after finalizeContents().
793 std::vector<Location> locations;
794 // (target symbol, addend) => import ordinal
795 llvm::MapVector<std::pair<const Symbol *, int64_t>, uint32_t> bindings;
796
797 struct SegmentInfo {
798 SegmentInfo(const OutputSegment *oseg) : oseg(oseg) {}
799
800 const OutputSegment *oseg;
801 // (page index, fixup starts offset)
802 llvm::SmallVector<std::pair<uint16_t, uint16_t>> pageStarts;
803
804 size_t getSize() const;
805 size_t writeTo(uint8_t *buf) const;
806 };
807 llvm::SmallVector<SegmentInfo, 4> fixupSegments;
808
809 size_t symtabSize = 0;
810 size_t size = 0;
811
812 bool needsAddend = false;
813 bool needsLargeAddend = false;
814 bool hasWeakBind = false;
815 bool hasNonWeakDef = false;
816 llvm::MachO::ChainedImportFormat importFormat;
817};
818
819void writeChainedRebase(uint8_t *buf, uint64_t targetVA);
820void writeChainedFixup(uint8_t *buf, const Symbol *sym, int64_t addend);
821
822struct InStruct {
823 const uint8_t *bufferStart = nullptr;
824 MachHeaderSection *header = nullptr;
825 /// The list of cstring sections. Note that this includes \p cStringSection
826 /// and \p objcMethnameSection already.
827 llvm::SmallVector<CStringSection *> cStringSections;
828 CStringSection *cStringSection = nullptr;
829 DeduplicatedCStringSection *objcMethnameSection = nullptr;
830 WordLiteralSection *wordLiteralSection = nullptr;
831 RebaseSection *rebase = nullptr;
832 BindingSection *binding = nullptr;
833 WeakBindingSection *weakBinding = nullptr;
834 LazyBindingSection *lazyBinding = nullptr;
835 ExportSection *exports = nullptr;
836 GotSection *got = nullptr;
837 LazyPointerSection *lazyPointers = nullptr;
838 StubsSection *stubs = nullptr;
839 StubHelperSection *stubHelper = nullptr;
840 ObjCStubsSection *objcStubs = nullptr;
841 UnwindInfoSection *unwindInfo = nullptr;
842 ObjCImageInfoSection *objCImageInfo = nullptr;
843 ConcatInputSection *imageLoaderCache = nullptr;
844 InitOffsetsSection *initOffsets = nullptr;
845 ObjCMethListSection *objcMethList = nullptr;
846 ChainedFixupsSection *chainedFixups = nullptr;
847
848 CStringSection *getOrCreateCStringSection(StringRef name,
849 bool forceDedupStrings = false) {
850 auto [it, didEmplace] =
851 cStringSectionMap.try_emplace(Key: name, Args: cStringSections.size());
852 if (!didEmplace)
853 return cStringSections[it->getValue()];
854
855 std::string &nameData = *make<std::string>(args&: name);
856 CStringSection *sec;
857 if (config->dedupStrings || forceDedupStrings)
858 sec = make<DeduplicatedCStringSection>(args: nameData.c_str());
859 else
860 sec = make<CStringSection>(args: nameData.c_str());
861 cStringSections.push_back(Elt: sec);
862 return sec;
863 }
864
865private:
866 llvm::StringMap<unsigned> cStringSectionMap;
867};
868
869extern InStruct in;
870extern std::vector<SyntheticSection *> syntheticSections;
871
872void createSyntheticSymbols();
873
874} // namespace lld::macho
875
876#endif
877