Path: blob/main/contrib/llvm-project/lld/MachO/SyntheticSections.h
34878 views
//===- SyntheticSections.h -------------------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef LLD_MACHO_SYNTHETIC_SECTIONS_H9#define LLD_MACHO_SYNTHETIC_SECTIONS_H1011#include "Config.h"12#include "ExportTrie.h"13#include "InputSection.h"14#include "OutputSection.h"15#include "OutputSegment.h"16#include "Target.h"17#include "Writer.h"1819#include "llvm/ADT/DenseMap.h"20#include "llvm/ADT/Hashing.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"2627#include <unordered_map>2829namespace llvm {30class DWARFUnit;31} // namespace llvm3233namespace lld::macho {3435class Defined;36class DylibSymbol;37class LoadCommand;38class ObjFile;39class UnwindInfoSection;4041class SyntheticSection : public OutputSection {42public:43SyntheticSection(const char *segname, const char *name);44virtual ~SyntheticSection() = default;4546static bool classof(const OutputSection *sec) {47return sec->kind() == SyntheticKind;48}4950StringRef segname;51// This fake InputSection makes it easier for us to write code that applies52// generically to both user inputs and synthetics.53InputSection *isec;54};5556// All sections in __LINKEDIT should inherit from this.57class LinkEditSection : public SyntheticSection {58public:59LinkEditSection(const char *segname, const char *name)60: SyntheticSection(segname, name) {61align = target->wordSize;62}6364// Implementations of this method can assume that the regular (non-__LINKEDIT)65// sections already have their addresses assigned.66virtual void finalizeContents() {}6768// Sections in __LINKEDIT are special: their offsets are recorded in the69// load commands like LC_DYLD_INFO_ONLY and LC_SYMTAB, instead of in section70// headers.71bool isHidden() const final { return true; }7273virtual uint64_t getRawSize() const = 0;7475// codesign (or more specifically libstuff) checks that each section in76// __LINKEDIT ends where the next one starts -- no gaps are permitted. We77// therefore align every section's start and end points to WordSize.78//79// NOTE: This assumes that the extra bytes required for alignment can be80// zero-valued bytes.81uint64_t getSize() const final { return llvm::alignTo(getRawSize(), align); }82};8384// The header of the Mach-O file, which must have a file offset of zero.85class MachHeaderSection final : public SyntheticSection {86public:87MachHeaderSection();88bool isHidden() const override { return true; }89uint64_t getSize() const override;90void writeTo(uint8_t *buf) const override;9192void addLoadCommand(LoadCommand *);9394protected:95std::vector<LoadCommand *> loadCommands;96uint32_t sizeOfCmds = 0;97};9899// A hidden section that exists solely for the purpose of creating the100// __PAGEZERO segment, which is used to catch null pointer dereferences.101class PageZeroSection final : public SyntheticSection {102public:103PageZeroSection();104bool isHidden() const override { return true; }105bool isNeeded() const override { return target->pageZeroSize != 0; }106uint64_t getSize() const override { return target->pageZeroSize; }107uint64_t getFileSize() const override { return 0; }108void writeTo(uint8_t *buf) const override {}109};110111// This is the base class for the GOT and TLVPointer sections, which are nearly112// functionally identical -- they will both be populated by dyld with addresses113// to non-lazily-loaded dylib symbols. The main difference is that the114// TLVPointerSection stores references to thread-local variables.115class NonLazyPointerSectionBase : public SyntheticSection {116public:117NonLazyPointerSectionBase(const char *segname, const char *name);118const llvm::SetVector<const Symbol *> &getEntries() const { return entries; }119bool isNeeded() const override { return !entries.empty(); }120uint64_t getSize() const override {121return entries.size() * target->wordSize;122}123void writeTo(uint8_t *buf) const override;124void addEntry(Symbol *sym);125uint64_t getVA(uint32_t gotIndex) const {126return addr + gotIndex * target->wordSize;127}128129private:130llvm::SetVector<const Symbol *> entries;131};132133class GotSection final : public NonLazyPointerSectionBase {134public:135GotSection();136};137138class TlvPointerSection final : public NonLazyPointerSectionBase {139public:140TlvPointerSection();141};142143struct Location {144const InputSection *isec;145uint64_t offset;146147Location(const InputSection *isec, uint64_t offset)148: isec(isec), offset(offset) {}149uint64_t getVA() const { return isec->getVA(offset); }150};151152// Stores rebase opcodes, which tell dyld where absolute addresses have been153// encoded in the binary. If the binary is not loaded at its preferred address,154// dyld has to rebase these addresses by adding an offset to them.155class RebaseSection final : public LinkEditSection {156public:157RebaseSection();158void finalizeContents() override;159uint64_t getRawSize() const override { return contents.size(); }160bool isNeeded() const override { return !locations.empty(); }161void writeTo(uint8_t *buf) const override;162163void addEntry(const InputSection *isec, uint64_t offset) {164if (config->isPic)165locations.emplace_back(isec, offset);166}167168private:169std::vector<Location> locations;170SmallVector<char, 128> contents;171};172173struct BindingEntry {174int64_t addend;175Location target;176BindingEntry(int64_t addend, Location target)177: addend(addend), target(target) {}178};179180template <class Sym>181using BindingsMap = llvm::DenseMap<Sym, std::vector<BindingEntry>>;182183// Stores bind opcodes for telling dyld which symbols to load non-lazily.184class BindingSection final : public LinkEditSection {185public:186BindingSection();187void finalizeContents() override;188uint64_t getRawSize() const override { return contents.size(); }189bool isNeeded() const override { return !bindingsMap.empty(); }190void writeTo(uint8_t *buf) const override;191192void addEntry(const Symbol *dysym, const InputSection *isec, uint64_t offset,193int64_t addend = 0) {194bindingsMap[dysym].emplace_back(addend, Location(isec, offset));195}196197private:198BindingsMap<const Symbol *> bindingsMap;199SmallVector<char, 128> contents;200};201202// Stores bind opcodes for telling dyld which weak symbols need coalescing.203// There are two types of entries in this section:204//205// 1) Non-weak definitions: This is a symbol definition that weak symbols in206// other dylibs should coalesce to.207//208// 2) Weak bindings: These tell dyld that a given symbol reference should209// coalesce to a non-weak definition if one is found. Note that unlike the210// entries in the BindingSection, the bindings here only refer to these211// symbols by name, but do not specify which dylib to load them from.212class WeakBindingSection final : public LinkEditSection {213public:214WeakBindingSection();215void finalizeContents() override;216uint64_t getRawSize() const override { return contents.size(); }217bool isNeeded() const override {218return !bindingsMap.empty() || !definitions.empty();219}220221void writeTo(uint8_t *buf) const override;222223void addEntry(const Symbol *symbol, const InputSection *isec, uint64_t offset,224int64_t addend = 0) {225bindingsMap[symbol].emplace_back(addend, Location(isec, offset));226}227228bool hasEntry() const { return !bindingsMap.empty(); }229230void addNonWeakDefinition(const Defined *defined) {231definitions.emplace_back(defined);232}233234bool hasNonWeakDefinition() const { return !definitions.empty(); }235236private:237BindingsMap<const Symbol *> bindingsMap;238std::vector<const Defined *> definitions;239SmallVector<char, 128> contents;240};241242// The following sections implement lazy symbol binding -- very similar to the243// PLT mechanism in ELF.244//245// ELF's .plt section is broken up into two sections in Mach-O: StubsSection246// and StubHelperSection. Calls to functions in dylibs will end up calling into247// StubsSection, which contains indirect jumps to addresses stored in the248// LazyPointerSection (the counterpart to ELF's .plt.got).249//250// We will first describe how non-weak symbols are handled.251//252// At program start, the LazyPointerSection contains addresses that point into253// one of the entry points in the middle of the StubHelperSection. The code in254// StubHelperSection will push on the stack an offset into the255// LazyBindingSection. The push is followed by a jump to the beginning of the256// StubHelperSection (similar to PLT0), which then calls into dyld_stub_binder.257// dyld_stub_binder is a non-lazily-bound symbol, so this call looks it up in258// the GOT.259//260// The stub binder will look up the bind opcodes in the LazyBindingSection at261// the given offset. The bind opcodes will tell the binder to update the262// address in the LazyPointerSection to point to the symbol, so that subsequent263// calls don't have to redo the symbol resolution. The binder will then jump to264// the resolved symbol.265//266// With weak symbols, the situation is slightly different. Since there is no267// "weak lazy" lookup, function calls to weak symbols are always non-lazily268// bound. We emit both regular non-lazy bindings as well as weak bindings, in269// order that the weak bindings may overwrite the non-lazy bindings if an270// appropriate symbol is found at runtime. However, the bound addresses will271// still be written (non-lazily) into the LazyPointerSection.272//273// Symbols are always bound eagerly when chained fixups are used. In that case,274// StubsSection contains indirect jumps to addresses stored in the GotSection.275// The GOT directly contains the fixup entries, which will be replaced by the276// address of the target symbols on load. LazyPointerSection and277// StubHelperSection are not used.278279class StubsSection final : public SyntheticSection {280public:281StubsSection();282uint64_t getSize() const override;283bool isNeeded() const override { return !entries.empty(); }284void finalize() override;285void writeTo(uint8_t *buf) const override;286const llvm::SetVector<Symbol *> &getEntries() const { return entries; }287// Creates a stub for the symbol and the corresponding entry in the288// LazyPointerSection.289void addEntry(Symbol *);290uint64_t getVA(uint32_t stubsIndex) const {291assert(isFinal || target->usesThunks());292// ConcatOutputSection::finalize() can seek the address of a293// stub before its address is assigned. Before __stubs is294// finalized, return a contrived out-of-range address.295return isFinal ? addr + stubsIndex * target->stubSize296: TargetInfo::outOfRangeVA;297}298299bool isFinal = false; // is address assigned?300301private:302llvm::SetVector<Symbol *> entries;303};304305class StubHelperSection final : public SyntheticSection {306public:307StubHelperSection();308uint64_t getSize() const override;309bool isNeeded() const override;310void writeTo(uint8_t *buf) const override;311312void setUp();313314DylibSymbol *stubBinder = nullptr;315Defined *dyldPrivate = nullptr;316};317318class ObjCSelRefsHelper {319public:320static void initialize();321static void cleanup();322323static ConcatInputSection *getSelRef(StringRef methname);324static ConcatInputSection *makeSelRef(StringRef methname);325326private:327static llvm::DenseMap<llvm::CachedHashStringRef, ConcatInputSection *>328methnameToSelref;329};330331// Objective-C stubs are hoisted objc_msgSend calls per selector called in the332// program. Apple Clang produces undefined symbols to each stub, such as333// '_objc_msgSend$foo', which are then synthesized by the linker. The stubs334// load the particular selector 'foo' from __objc_selrefs, setting it to the335// first argument of the objc_msgSend call, and then jumps to objc_msgSend. The336// actual stub contents are mirrored from ld64.337class ObjCStubsSection final : public SyntheticSection {338public:339ObjCStubsSection();340void addEntry(Symbol *sym);341uint64_t getSize() const override;342bool isNeeded() const override { return !symbols.empty(); }343void finalize() override { isec->isFinal = true; }344void writeTo(uint8_t *buf) const override;345void setUp();346347static constexpr llvm::StringLiteral symbolPrefix = "_objc_msgSend$";348static bool isObjCStubSymbol(Symbol *sym);349static StringRef getMethname(Symbol *sym);350351private:352std::vector<Defined *> symbols;353Symbol *objcMsgSend = nullptr;354};355356// Note that this section may also be targeted by non-lazy bindings. In357// particular, this happens when branch relocations target weak symbols.358class LazyPointerSection final : public SyntheticSection {359public:360LazyPointerSection();361uint64_t getSize() const override;362bool isNeeded() const override;363void writeTo(uint8_t *buf) const override;364uint64_t getVA(uint32_t index) const {365return addr + (index << target->p2WordSize);366}367};368369class LazyBindingSection final : public LinkEditSection {370public:371LazyBindingSection();372void finalizeContents() override;373uint64_t getRawSize() const override { return contents.size(); }374bool isNeeded() const override { return !entries.empty(); }375void writeTo(uint8_t *buf) const override;376// Note that every entry here will by referenced by a corresponding entry in377// the StubHelperSection.378void addEntry(Symbol *dysym);379const llvm::SetVector<Symbol *> &getEntries() const { return entries; }380381private:382uint32_t encode(const Symbol &);383384llvm::SetVector<Symbol *> entries;385SmallVector<char, 128> contents;386llvm::raw_svector_ostream os{contents};387};388389// Stores a trie that describes the set of exported symbols.390class ExportSection final : public LinkEditSection {391public:392ExportSection();393void finalizeContents() override;394uint64_t getRawSize() const override { return size; }395bool isNeeded() const override { return size; }396void writeTo(uint8_t *buf) const override;397398bool hasWeakSymbol = false;399400private:401TrieBuilder trieBuilder;402size_t size = 0;403};404405// Stores 'data in code' entries that describe the locations of data regions406// inside code sections. This is used by llvm-objdump to distinguish jump tables407// and stop them from being disassembled as instructions.408class DataInCodeSection final : public LinkEditSection {409public:410DataInCodeSection();411void finalizeContents() override;412uint64_t getRawSize() const override {413return sizeof(llvm::MachO::data_in_code_entry) * entries.size();414}415void writeTo(uint8_t *buf) const override;416417private:418std::vector<llvm::MachO::data_in_code_entry> entries;419};420421// Stores ULEB128 delta encoded addresses of functions.422class FunctionStartsSection final : public LinkEditSection {423public:424FunctionStartsSection();425void finalizeContents() override;426uint64_t getRawSize() const override { return contents.size(); }427void writeTo(uint8_t *buf) const override;428429private:430SmallVector<char, 128> contents;431};432433// Stores the strings referenced by the symbol table.434class StringTableSection final : public LinkEditSection {435public:436StringTableSection();437// Returns the start offset of the added string.438uint32_t addString(StringRef);439uint64_t getRawSize() const override { return size; }440void writeTo(uint8_t *buf) const override;441442static constexpr size_t emptyStringIndex = 1;443444private:445// ld64 emits string tables which start with a space and a zero byte. We446// match its behavior here since some tools depend on it.447// Consequently, the empty string will be at index 1, not zero.448std::vector<StringRef> strings{" "};449size_t size = 2;450};451452struct SymtabEntry {453Symbol *sym;454size_t strx;455};456457struct StabsEntry {458uint8_t type = 0;459uint32_t strx = StringTableSection::emptyStringIndex;460uint8_t sect = 0;461uint16_t desc = 0;462uint64_t value = 0;463464StabsEntry() = default;465explicit StabsEntry(uint8_t type) : type(type) {}466};467468// Symbols of the same type must be laid out contiguously: we choose to emit469// all local symbols first, then external symbols, and finally undefined470// symbols. For each symbol type, the LC_DYSYMTAB load command will record the471// range (start index and total number) of those symbols in the symbol table.472class SymtabSection : public LinkEditSection {473public:474void finalizeContents() override;475uint32_t getNumSymbols() const;476uint32_t getNumLocalSymbols() const {477return stabs.size() + localSymbols.size();478}479uint32_t getNumExternalSymbols() const { return externalSymbols.size(); }480uint32_t getNumUndefinedSymbols() const { return undefinedSymbols.size(); }481482private:483void emitBeginSourceStab(StringRef);484void emitEndSourceStab();485void emitObjectFileStab(ObjFile *);486void emitEndFunStab(Defined *);487void emitStabs();488489protected:490SymtabSection(StringTableSection &);491492StringTableSection &stringTableSection;493// STABS symbols are always local symbols, but we represent them with special494// entries because they may use fields like n_sect and n_desc differently.495std::vector<StabsEntry> stabs;496std::vector<SymtabEntry> localSymbols;497std::vector<SymtabEntry> externalSymbols;498std::vector<SymtabEntry> undefinedSymbols;499};500501template <class LP> SymtabSection *makeSymtabSection(StringTableSection &);502503// The indirect symbol table is a list of 32-bit integers that serve as indices504// into the (actual) symbol table. The indirect symbol table is a505// concatenation of several sub-arrays of indices, each sub-array belonging to506// a separate section. The starting offset of each sub-array is stored in the507// reserved1 header field of the respective section.508//509// These sub-arrays provide symbol information for sections that store510// contiguous sequences of symbol references. These references can be pointers511// (e.g. those in the GOT and TLVP sections) or assembly sequences (e.g.512// function stubs).513class IndirectSymtabSection final : public LinkEditSection {514public:515IndirectSymtabSection();516void finalizeContents() override;517uint32_t getNumSymbols() const;518uint64_t getRawSize() const override {519return getNumSymbols() * sizeof(uint32_t);520}521bool isNeeded() const override;522void writeTo(uint8_t *buf) const override;523};524525// The code signature comes at the very end of the linked output file.526class CodeSignatureSection final : public LinkEditSection {527public:528// NOTE: These values are duplicated in llvm-objcopy's MachO/Object.h file529// and any changes here, should be repeated there.530static constexpr uint8_t blockSizeShift = 12;531static constexpr size_t blockSize = (1 << blockSizeShift); // 4 KiB532static constexpr size_t hashSize = 256 / 8;533static constexpr size_t blobHeadersSize = llvm::alignTo<8>(534sizeof(llvm::MachO::CS_SuperBlob) + sizeof(llvm::MachO::CS_BlobIndex));535static constexpr uint32_t fixedHeadersSize =536blobHeadersSize + sizeof(llvm::MachO::CS_CodeDirectory);537538uint32_t fileNamePad = 0;539uint32_t allHeadersSize = 0;540StringRef fileName;541542CodeSignatureSection();543uint64_t getRawSize() const override;544bool isNeeded() const override { return true; }545void writeTo(uint8_t *buf) const override;546uint32_t getBlockCount() const;547void writeHashes(uint8_t *buf) const;548};549550class CStringSection : public SyntheticSection {551public:552CStringSection(const char *name);553void addInput(CStringInputSection *);554uint64_t getSize() const override { return size; }555virtual void finalizeContents();556bool isNeeded() const override { return !inputs.empty(); }557void writeTo(uint8_t *buf) const override;558559std::vector<CStringInputSection *> inputs;560561private:562uint64_t size;563};564565class DeduplicatedCStringSection final : public CStringSection {566public:567DeduplicatedCStringSection(const char *name) : CStringSection(name){};568uint64_t getSize() const override { return size; }569void finalizeContents() override;570void writeTo(uint8_t *buf) const override;571572struct StringOffset {573uint8_t trailingZeros;574uint64_t outSecOff = UINT64_MAX;575576explicit StringOffset(uint8_t zeros) : trailingZeros(zeros) {}577};578579StringOffset getStringOffset(StringRef str) const;580581private:582llvm::DenseMap<llvm::CachedHashStringRef, StringOffset> stringOffsetMap;583size_t size = 0;584};585586/*587* This section contains deduplicated literal values. The 16-byte values are588* laid out first, followed by the 8- and then the 4-byte ones.589*/590class WordLiteralSection final : public SyntheticSection {591public:592using UInt128 = std::pair<uint64_t, uint64_t>;593// I don't think the standard guarantees the size of a pair, so let's make594// sure it's exact -- that way we can construct it via `mmap`.595static_assert(sizeof(UInt128) == 16);596597WordLiteralSection();598void addInput(WordLiteralInputSection *);599void finalizeContents();600void writeTo(uint8_t *buf) const override;601602uint64_t getSize() const override {603return literal16Map.size() * 16 + literal8Map.size() * 8 +604literal4Map.size() * 4;605}606607bool isNeeded() const override {608return !literal16Map.empty() || !literal4Map.empty() ||609!literal8Map.empty();610}611612uint64_t getLiteral16Offset(uintptr_t buf) const {613return literal16Map.at(*reinterpret_cast<const UInt128 *>(buf)) * 16;614}615616uint64_t getLiteral8Offset(uintptr_t buf) const {617return literal16Map.size() * 16 +618literal8Map.at(*reinterpret_cast<const uint64_t *>(buf)) * 8;619}620621uint64_t getLiteral4Offset(uintptr_t buf) const {622return literal16Map.size() * 16 + literal8Map.size() * 8 +623literal4Map.at(*reinterpret_cast<const uint32_t *>(buf)) * 4;624}625626private:627std::vector<WordLiteralInputSection *> inputs;628629template <class T> struct Hasher {630llvm::hash_code operator()(T v) const { return llvm::hash_value(v); }631};632// We're using unordered_map instead of DenseMap here because we need to633// support all possible integer values -- there are no suitable tombstone634// values for DenseMap.635std::unordered_map<UInt128, uint64_t, Hasher<UInt128>> literal16Map;636std::unordered_map<uint64_t, uint64_t> literal8Map;637std::unordered_map<uint32_t, uint64_t> literal4Map;638};639640class ObjCImageInfoSection final : public SyntheticSection {641public:642ObjCImageInfoSection();643bool isNeeded() const override { return !files.empty(); }644uint64_t getSize() const override { return 8; }645void addFile(const InputFile *file) {646assert(!file->objCImageInfo.empty());647files.push_back(file);648}649void finalizeContents();650void writeTo(uint8_t *buf) const override;651652private:653struct ImageInfo {654uint8_t swiftVersion = 0;655bool hasCategoryClassProperties = false;656} info;657static ImageInfo parseImageInfo(const InputFile *);658std::vector<const InputFile *> files; // files with image info659};660661// This section stores 32-bit __TEXT segment offsets of initializer functions.662//663// The compiler stores pointers to initializers in __mod_init_func. These need664// to be fixed up at load time, which takes time and dirties memory. By665// synthesizing InitOffsetsSection from them, this data can live in the666// read-only __TEXT segment instead. This section is used by default when667// chained fixups are enabled.668//669// There is no similar counterpart to __mod_term_func, as that section is670// deprecated, and static destructors are instead handled by registering them671// via __cxa_atexit from an autogenerated initializer function (see D121736).672class InitOffsetsSection final : public SyntheticSection {673public:674InitOffsetsSection();675bool isNeeded() const override { return !sections.empty(); }676uint64_t getSize() const override;677void writeTo(uint8_t *buf) const override;678void setUp();679680void addInput(ConcatInputSection *isec) { sections.push_back(isec); }681const std::vector<ConcatInputSection *> &inputs() const { return sections; }682683private:684std::vector<ConcatInputSection *> sections;685};686687// This SyntheticSection is for the __objc_methlist section, which contains688// relative method lists if the -objc_relative_method_lists option is enabled.689class ObjCMethListSection final : public SyntheticSection {690public:691ObjCMethListSection();692693static bool isMethodList(const ConcatInputSection *isec);694void addInput(ConcatInputSection *isec) { inputs.push_back(isec); }695std::vector<ConcatInputSection *> getInputs() { return inputs; }696697void setUp();698void finalize() override;699bool isNeeded() const override { return !inputs.empty(); }700uint64_t getSize() const override { return sectionSize; }701void writeTo(uint8_t *bufStart) const override;702703private:704void readMethodListHeader(const uint8_t *buf, uint32_t &structSizeAndFlags,705uint32_t &structCount) const;706void writeMethodListHeader(uint8_t *buf, uint32_t structSizeAndFlags,707uint32_t structCount) const;708uint32_t computeRelativeMethodListSize(uint32_t absoluteMethodListSize) const;709void writeRelativeOffsetForIsec(const ConcatInputSection *isec, uint8_t *buf,710uint32_t &inSecOff, uint32_t &outSecOff,711bool useSelRef) const;712uint32_t writeRelativeMethodList(const ConcatInputSection *isec,713uint8_t *buf) const;714715static constexpr uint32_t methodListHeaderSize =716/*structSizeAndFlags*/ sizeof(uint32_t) +717/*structCount*/ sizeof(uint32_t);718// Relative method lists are supported only for 3-pointer method lists719static constexpr uint32_t pointersPerStruct = 3;720// The runtime identifies relative method lists via this magic value721static constexpr uint32_t relMethodHeaderFlag = 0x80000000;722// In the method list header, the first 2 bytes are the size of struct723static constexpr uint32_t structSizeMask = 0x0000FFFF;724// In the method list header, the last 2 bytes are the flags for the struct725static constexpr uint32_t structFlagsMask = 0xFFFF0000;726// Relative method lists have 4 byte alignment as all data in the InputSection727// is 4 byte728static constexpr uint32_t relativeOffsetSize = sizeof(uint32_t);729730// The output size of the __objc_methlist section, computed during finalize()731uint32_t sectionSize = 0;732std::vector<ConcatInputSection *> inputs;733};734735// Chained fixups are a replacement for classic dyld opcodes. In this format,736// most of the metadata necessary for binding symbols and rebasing addresses is737// stored directly in the memory location that will have the fixup applied.738//739// The fixups form singly linked lists; each one covering a single page in740// memory. The __LINKEDIT,__chainfixups section stores the page offset of the741// first fixup of each page; the rest can be found by walking the chain using742// the offset that is embedded in each entry.743//744// This setup allows pages to be relocated lazily at page-in time and without745// being dirtied. The kernel can discard and load them again as needed. This746// technique, called page-in linking, was introduced in macOS 13.747//748// The benefits of this format are:749// - smaller __LINKEDIT segment, as most of the fixup information is stored in750// the data segment751// - faster startup, since not all relocations need to be done upfront752// - slightly lower memory usage, as fewer pages are dirtied753//754// Userspace x86_64 and arm64 binaries have two types of fixup entries:755// - Rebase entries contain an absolute address, to which the object's load756// address will be added to get the final value. This is used for loading757// the address of a symbol defined in the same binary.758// - Binding entries are mostly used for symbols imported from other dylibs,759// but for weakly bound and interposable symbols as well. They are looked up760// by a (symbol name, library) pair stored in __chainfixups. This import761// entry also encodes whether the import is weak (i.e. if the symbol is762// missing, it should be set to null instead of producing a load error).763// The fixup encodes an ordinal associated with the import, and an optional764// addend.765//766// The entries are tightly packed 64-bit bitfields. One of the bits specifies767// which kind of fixup to interpret them as.768//769// LLD generates the fixup data in 5 stages:770// 1. While scanning relocations, we make a note of each location that needs771// a fixup by calling addRebase() or addBinding(). During this, we assign772// a unique ordinal for each (symbol name, library, addend) import tuple.773// 2. After addresses have been assigned to all sections, and thus the memory774// layout of the linked image is final; finalizeContents() is called. Here,775// the page offsets of the chain start entries are calculated.776// 3. ChainedFixupsSection::writeTo() writes the page start offsets and the777// imports table to the output file.778// 4. Each section's fixup entries are encoded and written to disk in779// ConcatInputSection::writeTo(), but without writing the offsets that form780// the chain.781// 5. Finally, each page's (which might correspond to multiple sections)782// fixups are linked together in Writer::buildFixupChains().783class ChainedFixupsSection final : public LinkEditSection {784public:785ChainedFixupsSection();786void finalizeContents() override;787uint64_t getRawSize() const override { return size; }788bool isNeeded() const override;789void writeTo(uint8_t *buf) const override;790791void addRebase(const InputSection *isec, uint64_t offset) {792locations.emplace_back(isec, offset);793}794void addBinding(const Symbol *dysym, const InputSection *isec,795uint64_t offset, int64_t addend = 0);796797void setHasNonWeakDefinition() { hasNonWeakDef = true; }798799// Returns an (ordinal, inline addend) tuple used by dyld_chained_ptr_64_bind.800std::pair<uint32_t, uint8_t> getBinding(const Symbol *sym,801int64_t addend) const;802803const std::vector<Location> &getLocations() const { return locations; }804805bool hasWeakBinding() const { return hasWeakBind; }806bool hasNonWeakDefinition() const { return hasNonWeakDef; }807808private:809// Location::offset initially stores the offset within an InputSection, but810// contains output segment offsets after finalizeContents().811std::vector<Location> locations;812// (target symbol, addend) => import ordinal813llvm::MapVector<std::pair<const Symbol *, int64_t>, uint32_t> bindings;814815struct SegmentInfo {816SegmentInfo(const OutputSegment *oseg) : oseg(oseg) {}817818const OutputSegment *oseg;819// (page index, fixup starts offset)820llvm::SmallVector<std::pair<uint16_t, uint16_t>> pageStarts;821822size_t getSize() const;823size_t writeTo(uint8_t *buf) const;824};825llvm::SmallVector<SegmentInfo, 4> fixupSegments;826827size_t symtabSize = 0;828size_t size = 0;829830bool needsAddend = false;831bool needsLargeAddend = false;832bool hasWeakBind = false;833bool hasNonWeakDef = false;834llvm::MachO::ChainedImportFormat importFormat;835};836837void writeChainedRebase(uint8_t *buf, uint64_t targetVA);838void writeChainedFixup(uint8_t *buf, const Symbol *sym, int64_t addend);839840struct InStruct {841const uint8_t *bufferStart = nullptr;842MachHeaderSection *header = nullptr;843CStringSection *cStringSection = nullptr;844DeduplicatedCStringSection *objcMethnameSection = nullptr;845WordLiteralSection *wordLiteralSection = nullptr;846RebaseSection *rebase = nullptr;847BindingSection *binding = nullptr;848WeakBindingSection *weakBinding = nullptr;849LazyBindingSection *lazyBinding = nullptr;850ExportSection *exports = nullptr;851GotSection *got = nullptr;852TlvPointerSection *tlvPointers = nullptr;853LazyPointerSection *lazyPointers = nullptr;854StubsSection *stubs = nullptr;855StubHelperSection *stubHelper = nullptr;856ObjCStubsSection *objcStubs = nullptr;857UnwindInfoSection *unwindInfo = nullptr;858ObjCImageInfoSection *objCImageInfo = nullptr;859ConcatInputSection *imageLoaderCache = nullptr;860InitOffsetsSection *initOffsets = nullptr;861ObjCMethListSection *objcMethList = nullptr;862ChainedFixupsSection *chainedFixups = nullptr;863};864865extern InStruct in;866extern std::vector<SyntheticSection *> syntheticSections;867868void createSyntheticSymbols();869870} // namespace lld::macho871872#endif873874875