XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
kclink: definitions at one place, common symbols and arm64e objects; pointer checks and kccompare's status; tests/kclink and CI
Fred Nixcea635964717
diff --git a/.github/workflows/kclink.yml b/.github/workflows/kclink.ymlnew file mode 100644index 0000000..01a90da--- /dev/null+++ b/.github/workflows/kclink.yml@@ -0,0 +1,14 @@+# SPDX-License-Identifier: GPL-2.0-only+# The tests of the kernel collection linker (scripts/kclink), in tests/kclink: python3 and, for the tests that compile+# their objects, the runner's clang; nothing of Apple's. A test file added there is run without a change to this file.+name: kclink+on:+ push:+ pull_request:+jobs:+ test:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - name: The kernel collection linker's tests+ run: python3 -m unittest discover -s tests/kclink -vdiff --git a/scripts/kclink/kccompare.py b/scripts/kclink/kccompare.pyindex cfd38e0..434cc9b 100755--- a/scripts/kclink/kccompare.py+++ b/scripts/kclink/kccompare.py@@ -3,7 +3,9 @@"""Compares two kernel collections: their fixups (decoded), their fileset entries' segments and sections, the bytes ofeach entry's segments with pointers taken out, and their prelink info. For checking kclink against another linker.- kccompare.py A B"""+ kccompare.py A B++Its exit status is 1 when they differ."""import plistlibimport structimport sys@@ -30,13 +32,15 @@ def main():bufa, imga, hdra, fxa, ea, ia = Abufb, imgb, hdrb, fxb, eb, ib = Bprint(f'header {hdra:#x} / {hdrb:#x}; {len(fxa)} / {len(fxb)} pointers; {len(ea)} / {len(eb)} entries')+ problems = 0 # everything said below is a difference and counts as onefor sa, sb in zip(imga.segments, imgb.segments):if (sa.name, sa.vmaddr, sa.vmsize) != (sb.name, sb.vmaddr, sb.vmsize):print(f' segment {sa.name} {sa.vmaddr:#x}+{sa.vmsize:#x} / {sb.name} {sb.vmaddr:#x}+{sb.vmsize:#x}')+ problems += 1only = set(ea) ^ set(eb)if only:print(' entries in one only:', sorted(only))- problems = 0+ problems += len(only)for name in sorted(set(ea) & set(eb)):xa, xb = ea[name], eb[name]segs_a = [(s.name, s.vmaddr, s.vmsize) for s in xa.segments if s.name != '__LINKEDIT']@@ -79,6 +83,7 @@ def main():db = {d['CFBundleIdentifier']: d for d in ib['_PrelinkInfoDictionary']}if set(da) != set(db):print('prelink info: entries in one only:', sorted(set(da) ^ set(db)))+ problems += len(set(da) ^ set(db))for k in sorted(set(da) & set(db)):if da[k] != db[k]:keys = sorted(x for x in set(da[k]) | set(db[k]) if da[k].get(x) != db[k].get(x))@@ -87,8 +92,10 @@ def main():if {x: y for x, y in ia.items() if x != '_PrelinkInfoDictionary'} != \{x: y for x, y in ib.items() if x != '_PrelinkInfoDictionary'}:print('prelink info: top-level keys differ')+ problems += 1print(f'{problems} differences')+ return problemsif __name__ == '__main__':- main()+ sys.exit(1 if main() else 0)diff --git a/scripts/kclink/kclink.py b/scripts/kclink/kclink.pyindex 9f0eea6..6bb75a1 100755--- a/scripts/kclink/kclink.py+++ b/scripts/kclink/kclink.py@@ -309,10 +309,17 @@ def main():if spec['bundle'] in keep or spec['bundle'] in (s['bundle'] for s, _ in specs):fail(f'{path}: {spec["bundle"]} is in the collection already')objects = json.loads(Path(spec['objects']).read_text())- specs.append((spec, kextld.Kext(spec, objects)))+ try:+ specs.append((spec, kextld.Kext(spec, objects)))+ except kextld.LinkError as e:+ fail(f'{spec["bundle"]}: {e}')for spec, kx in specs:addrs = {}- for seg, (size, al) in kx.layout().items():+ try:+ sizes = kx.layout()+ except kextld.LinkError as e:+ fail(f'{spec["bundle"]}: {e}')+ for seg, (size, al) in sizes.items():region = KEXT_REGION[seg]off = holes[region].fit(size, al)if off is None:diff --git a/scripts/kclink/kextld.py b/scripts/kclink/kextld.pyindex e760e47..5ac7c06 100644--- a/scripts/kclink/kextld.py+++ b/scripts/kclink/kextld.py@@ -46,6 +46,7 @@ ZEROFILL = {'__bss', '__common'}# arm64 relocation typesUNSIGNED, SUBTRACTOR, BRANCH26, PAGE21, PAGEOFF12, GOT_LOAD_PAGE21, GOT_LOAD_PAGEOFF12, POINTER_TO_GOT = range(8)ADDEND, AUTHENTICATED_POINTER = 10, 11+CPU_SUBTYPE_ARM64E = 2# kmod_info_t (<mach/kmod.h>, 4-byte packed): next, info_version, id, name[64], version[64], reference_count,# reference_list, address, size, hdr_size, start, stop@@ -76,8 +77,11 @@ class Obj:self.path = pathself.buf = open(path, 'rb').read()self.img = Image(self.buf)- if self.img.filetype != MH_OBJECT or self.img.cputype != CPU_TYPE_ARM64:- raise LinkError(f'{path}: not an arm64 object')+ # arm64e only (the subtype's low 24 bits; the rest is the pointer authentication ABI's version): an arm64 object+ # signs none of its pointers, and the kext is an arm64e one whatever went into it+ if (self.img.filetype != MH_OBJECT or self.img.cputype != CPU_TYPE_ARM64 or+ self.img.cpusubtype & 0xffffff != CPU_SUBTYPE_ARM64E):+ raise LinkError(f'{path}: not an arm64e object')self.sects = self.img.sections() # input sections, 1-based in nlist n_sectself.syms = self.img.symbols()self.where = {} # input section index -> (OutSection, offset)@@ -118,11 +122,13 @@ class Kext:out.pieces.append((oi, si, off))out.size, out.align = off + s.size, max(out.align, s.align)o.where[si] = (out, off)- # common symbols: zero-filled storage in __DATA,__common+ # common symbols: zero-filled storage in __DATA,__common (but for one an object defines: that is the symbol)common = {}+ defined = {n for o in self.objs for n, t, sc, d, v in o.syms+ if not t & N_STAB and t & (N_EXT | N_PEXT) and (t & N_TYPE) == N_SECT}for o in self.objs:for n, t, sc, d, v in o.syms:- if not t & N_STAB and (t & N_TYPE) == N_UNDF and t & N_EXT and v:+ if not t & N_STAB and (t & N_TYPE) == N_UNDF and t & N_EXT and v and n not in defined:size, al = common.get(n, (0, 0))common[n] = (max(size, v), max(al, (d >> 8) & 0xf))if common:@@ -146,7 +152,9 @@ class Kext:prev = self.globals[n]raise LinkError(f'{n} defined twice (in {o.path} and at {prev[0].seg},{prev[0].name})')weak.discard(n) # over a weak one- elif d & 0x80:+ elif not d & 0x80:+ weak.discard(n) # (at the place of a weak one too: the two are one, not weak)+ elif n not in self.globals:weak.add(n)self.globals[n] = where# a GOT entry for every symbol the code loads through one@@ -273,7 +281,10 @@ class Kext:target, name = None, Noneif typ in (UNSIGNED, AUTHENTICATED_POINTER):if length != 3:- raise LinkError(f'{o.path}: {length * 8}-bit pointer at {s.sectname}+{raddr:#x}')+ raise LinkError(f'{o.path}: {8 << length}-bit pointer at {s.sectname}+{raddr:#x}')+ if place & 3: # (a collection's chained fixups are at multiples of 4)+ raise LinkError(f'{o.path}: pointer at {s.sectname}+{raddr:#x} not at a multiple of 4 '+ f'bytes ({place:#x})')raw = struct.unpack_from('<Q', out.data, pos)[0]if typ == AUTHENTICATED_POINTER:add = raw & 0xffffffffdiff --git a/tests/kclink/mkcollection.py b/tests/kclink/mkcollection.pynew file mode 100644index 0000000..b82e86e--- /dev/null+++ b/tests/kclink/mkcollection.py@@ -0,0 +1,217 @@+# SPDX-License-Identifier: GPL-2.0-only+"""A kernel collection to test with, made the way scripts/free-kc/build.sh makes one (mk-template.py's empty collection,+then kclink.py) from stand-ins: a kernel of a few pages with threaded rebases and four symbols, kexts from objects+built by mkmacho.py, made-up property lists for XNU's pseudo-extensions. And a reader of the result."""+import json+import os+import plistlib+import shutil+import struct+import subprocess+import sys+import tempfile++import mkmacho+from mkmacho import (BL, BRANCH26, GOT_LOAD_PAGE21, GOT_LOAD_PAGEOFF12, KEY_DA, KEY_IA, LC_FUNCTION_STARTS, PAGE21,+ PAGEOFF12, RET, S_CSTRING_LITERALS, S_ZEROFILL, TEXT_FLAGS, Object, add, adrp, movz, words)++REPO = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')+MK_TEMPLATE = os.path.join(REPO, 'scripts', 'free-kc', 'mk-template.py')+KCLINK = os.path.join(REPO, 'scripts', 'kclink', 'kclink.py')+KCCOMPARE = os.path.join(REPO, 'scripts', 'kclink', 'kccompare.py')+BASE = 0xfffffff007004000 # where mk-template.py's collection is+PAGE = 0x4000+NO_ADDRESS = 0x7fffffffffffffff+# a collection of 24 pages, laid out like scripts/free-kc/layout.json+LAYOUT = {'segments': [['__TEXT', '0x0', '0x4000', 1, None], ['__PRELINK_TEXT', '0x4000', '0x1c000', 1, '__text'],+ ['__DATA_CONST', '0x20000', '0x10000', 1, None], ['__TEXT_EXEC', '0x30000', '0x10000', 5, None],+ ['__PRELINK_INFO', '0x40000', '0x8000', 3, '__info'], ['__DATA', '0x48000', '0x10000', 3, None],+ ['__LINKEDIT', '0x58000', '0x8000', 1, None]],+ 'kernel_header': '0x4000', 'kernel_linkinfo': ['0x58000', '0x4000'], 'kernel_linkedit': '0x60000'}+KPI = {'BSDKernel': 'com.apple.kpi.bsd', 'MACFramework': 'com.apple.kpi.dsep', 'IOKit': 'com.apple.kpi.iokit',+ 'Libkern': 'com.apple.kpi.libkern', 'Mach': 'com.apple.kpi.mach', 'Private': 'com.apple.kpi.private',+ 'Unsupported': 'com.apple.kpi.unsupported'}+VERSION = '27.2.0'+++def region(layout, name):+ """(offset, size) of one of the collection's segments."""+ return next((int(off, 16), int(size, 16)) for n, off, size, prot, sect in layout['segments'] if n == name)+++def stand_in_kernel(layout=LAYOUT, base=BASE, data_at=0, prelink_data=None, more=()):+ """A kernel for a collection of this layout whose header is at base: each segment at the start of its region.+ data_at: where in its data _kernel_data is; prelink_data: the offset in the collection of an empty __PRELINK_DATA+ segment (where a kernel has its kexts' data start); more: further segments, (name, offset in the collection).+ Returns (the file, {symbol: address}, [(address of a pointer, its target, how it is signed)])."""+ regions = ('__PRELINK_TEXT', '__DATA_CONST', '__TEXT_EXEC', '__DATA')+ text, dc, exec_, data = (base + region(layout, n)[0] for n in regions)+ info = base + int(layout['kernel_linkinfo'][0], 16)+ symbols = [('_kernel_start', exec_, True), ('_kernel_func', exec_ + 4, True),+ ('_kernel_private', exec_ + 12, False), ('_kernel_data', data + data_at, True)]+ # threaded rebases: two chains, one with its last pointer over the end of a page+ chains = [[(dc, exec_ + 4, None), (dc + 8, exec_ + 4, (KEY_IA, 0x1234, 1))],+ [(dc + 0x3ffc, data, None), (dc + 0x4008, data + 8, (KEY_DA, 0, 0))]]+ segs = [('__TEXT', text, bytes(2 * PAGE), [('__const', 0x2000, 0x100, 0)]),+ ('__DATA_CONST', dc, bytes(2 * PAGE), [('__const', 0, 2 * PAGE, 0)]),+ ('__TEXT_EXEC', exec_, words(RET, movz(0, 7), RET, RET) + bytes(PAGE - 16),+ [('__text', 0, 16, TEXT_FLAGS)]),+ ('__DATA', data, struct.pack('<Q', 0x1122334455667788) + bytes(PAGE - 8),+ [('__data', 0, 0x100, 0), ('__bss', 0x100, 0x200, S_ZEROFILL)])]+ if prelink_data is not None:+ segs.append(('__PRELINK_DATA', base + prelink_data, b'', []))+ segs += [(name, base + off, bytes(PAGE), []) for name, off in more]+ segs.append(('__LINKINFO', info, b'link info' + bytes(PAGE - 9), []))+ buf = mkmacho.kernel(segs, symbols, chains, extra=[struct.pack('<4I', LC_FUNCTION_STARTS, 16, 0, 0)])+ return buf, {n: a for n, a, ext in symbols}, [p for chain in chains for p in chain]+++def kext_one(answer=9, diversity=0x1111, message=b'hello from a kext\0'):+ """Two objects of a kext that calls the kernel, loads the address of its data through a GOT and has pointers to+ the kernel, to itself (signed) and to a symbol of the kernel that is not exported."""+ one, two = Object(), Object()+ t = one.text(BL, BL, adrp(1), 0xf9400021, adrp(1), add(1, 1), RET, RET)+ d = one.section('__DATA', '__data', bytes(24), 3)+ one.section('__DATA', '__bss', align_=4, zerofill=64)+ s = {n: one.undefined(n) for n in ('_helper', '_kernel_func', '_kernel_data', '_message')}+ start = one.define('_one_start', t)+ one.define('_one_stop', t, 28)+ one.define('_pointers', d)+ one.reloc(t, 0, BRANCH26, s['_helper'], pcrel=1)+ one.reloc(t, 4, BRANCH26, s['_kernel_func'], pcrel=1)+ one.reloc(t, 8, GOT_LOAD_PAGE21, s['_kernel_data'], pcrel=1)+ one.reloc(t, 12, GOT_LOAD_PAGEOFF12, s['_kernel_data'])+ one.reloc(t, 16, PAGE21, s['_message'], pcrel=1)+ one.reloc(t, 20, PAGEOFF12, s['_message'])+ one.pointer(d, 0, s['_kernel_data'])+ one.auth_pointer(d, 8, start, KEY_IA, diversity, 1)+ one.pointer(d, 16, s['_message'])+ helper = two.define('_helper', two.text(movz(0, answer), RET))+ two.define('_message', two.section('__TEXT', '__cstring', message, 0, S_CSTRING_LITERALS))+ c = two.section('__DATA', '__const', bytes(16), 3)+ two.define('_table', c)+ two.auth_pointer(c, 0, helper, KEY_IA, 0)+ two.pointer(c, 8, two.undefined('_kernel_private'))+ return [one, two]+++def kext_two():+ """A kext that calls the first one's _helper."""+ o = Object()+ t = o.text(BL, RET, RET)+ o.define('_two_start', t)+ o.define('_two_stop', t, 8)+ o.reloc(t, 0, BRANCH26, o.undefined('_helper'), pcrel=1)+ return [o]+++def kext_three(pointer_to='_helper'):+ """A kext with a pointer to a symbol of the first one (and no word of it among its libraries)."""+ o = Object()+ t = o.text(RET, RET)+ d = o.section('__DATA', '__data', bytes(8), 3)+ o.define('_three_start', t)+ o.define('_three_stop', t, 4)+ o.define('_three_pointer', d)+ o.pointer(d, 0, o.undefined(pointer_to))+ return [o]+++SPEC_ONE = {'name': 'One', 'bundle': 'org.example.kext.one', 'version': '1.0.0', 'start': '_one_start',+ 'stop': '_one_stop', 'libraries': {'com.apple.kpi.libkern': '8.0'},+ 'personalities': {'One': {'IOClass': 'One', 'IOProviderClass': 'IOResources'}}}+SPEC_TWO = {'name': 'Two', 'bundle': 'org.example.kext.two', 'version': '2.0', 'start': '_two_start',+ 'stop': '_two_stop', 'libraries': {'org.example.kext.one': '1.0'}}+++SPEC_THREE = {'name': 'Three', 'bundle': 'org.example.kext.three', 'version': '3', 'start': '_three_start',+ 'stop': '_three_stop'}+++class Workdir:+ """A directory to build collections in: XNU's pseudo-extension property lists (made up), a layout."""++ def __init__(self, cleanup, layout=LAYOUT, env=None):+ self.dir = tempfile.mkdtemp()+ cleanup(shutil.rmtree, self.dir)+ self.layout, self.env = layout, dict(os.environ, **(env or {}))+ for bundle, ident in KPI.items():+ d = self.path('xnu', 'config', 'System.kext', 'PlugIns', bundle + '.kext')+ os.makedirs(d)+ with open(os.path.join(d, 'Info.plist'), 'wb') as f:+ plistlib.dump({'CFBundleIdentifier': ident, 'CFBundleName': bundle, 'OSKernelResource': True,+ 'CFBundleVersion': '###KERNEL_VERSION_LONG###', 'OSBundleCompatibleVersion': '8.0.0b1',+ 'CFBundleShortVersionString': '###KERNEL_VERSION_SHORT###'}, f)+ with open(self.path('layout.json'), 'w') as f:+ json.dump(layout, f)++ def path(self, *parts):+ return os.path.join(self.dir, *parts)++ def read(self, name):+ with open(self.path(name), 'rb') as f:+ return f.read()++ def write(self, name, content):+ with open(self.path(name), 'wb' if isinstance(content, bytes) else 'w') as f:+ f.write(content)+ return name++ def run(self, script, *args):+ """Runs one of the scripts in the directory; returns (exit status, what it printed, what it complained of)."""+ r = subprocess.run([sys.executable, script] + list(args), cwd=self.dir, capture_output=True, text=True,+ env=self.env)+ return r.returncode, r.stdout, r.stderr++ def template(self, name='template.kc', version=VERSION, layout='layout.json'):+ status, out, err = self.run(MK_TEMPLATE, layout, 'xnu', version, name)+ assert status == 0, err+ return self.read(name)++ def kernel(self, name='kernel', base=BASE, **how):+ buf, symbols, pointers = stand_in_kernel(self.layout, base, **how)+ self.write(name, buf)+ return symbols, pointers++ def native(self, spec, objects):+ """Writes a kext's objects and its spec; returns the spec's name."""+ stem = spec['name'].lower()+ paths = [o.write(self.dir, f'{stem}{i}.o') for i, o in enumerate(objects)]+ self.write(stem + '.objects.json', json.dumps([os.path.basename(p) for p in paths]))+ return self.write(stem + '.json', json.dumps(dict(spec, objects=stem + '.objects.json')))++ def link(self, *args, base='template.kc', kernel='kernel', output='out.kc'):+ return self.run(KCLINK, base, kernel, output, *args)++ def collection(self, name='out.kc'):+ """The collection of this name, read back, with the symbols of its kexts kclink wrote beside it."""+ return Collection(self.read(name), json.loads(self.read(os.path.splitext(name)[0] + '.natives.json')))+++class Collection:+ """A collection read back: its segments, its entries, its chained fixups, its prelink info."""++ def __init__(self, buf, natives=None):+ self.buf = buf+ self.segments = {s['name']: s for s in mkmacho.segments(buf)}+ self.base = self.segments['__TEXT']['vmaddr']+ self.entries = mkmacho.fileset_entries(buf)+ self.header, self.starts, self.pointers = mkmacho.chained_fixups(buf)+ info = self.segments['__PRELINK_INFO']+ self.plist = buf[info['fileoff']:info['fileoff'] + info['sections'][0]['size']]+ self.info = plistlib.loads(self.plist)+ self.kexts = {d['CFBundleIdentifier']: d for d in self.info['_PrelinkInfoDictionary']}+ self.natives = natives or {}++ def u32(self, va):+ return struct.unpack_from('<I', self.buf, va - self.base)[0]++ def pointer(self, va):+ """(target, signing) of the chained fixup at an address."""+ p = self.pointers[va - self.base]+ return self.base + p.target, p.signing()++ def entry(self, name):+ """(the offset of an entry's header, its segments by name)."""+ off = self.entries[name][1]+ return off, {s['name']: s for s in mkmacho.segments(self.buf, off)}diff --git a/tests/kclink/mkmacho.py b/tests/kclink/mkmacho.pynew file mode 100644index 0000000..809db79--- /dev/null+++ b/tests/kclink/mkmacho.py@@ -0,0 +1,541 @@+# SPDX-License-Identifier: GPL-2.0-only+"""What the tests of scripts/kclink link and how they read the result back, written from the formats alone+(<mach-o/loader.h>, <mach-o/nlist.h>, <mach-o/reloc.h>, <mach-o/arm64/reloc.h>, <mach-o/fixup-chains.h>, the A64+instruction encodings) and sharing no code with scripts/kclink, so that a mistake there is not made here too:++ Object an arm64e object file in the making: sections, symbols, relocations (no compiler)+ kernel() a stand-in kernel: an executable with threaded rebases (__TEXT,__thread_starts) and symbols+ commands() ... a reader of load commands, segments and symbol tables+ chained_fixups() a walk of a collection's LC_DYLD_CHAINED_FIXUPS+ bl, adrp ... the instructions relocations are applied to, and their operands read back+ compile() clang, for the tests that link what a compiler really emits (skipped where there is none)+"""+import functools+import glob+import os+import shlex+import shutil+import struct+import subprocess+import sys+import tempfile+import unittest+import warnings++KCLINK = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'scripts', 'kclink')+sys.path.insert(0, KCLINK) # for the tests' `import kextld`, `import macho`++MH_MAGIC_64, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64E = 0xfeedfacf, 0x0100000c, 2+PTRAUTH_ABI = 0x80000000 # in the subtype: the pointer authentication ABI is versioned (what a compiler writes)+MH_OBJECT, MH_EXECUTE, MH_KEXT_BUNDLE, MH_FILESET = 1, 2, 0xb, 0xc+LC_SEGMENT_64, LC_SYMTAB, LC_UNIXTHREAD, LC_DYSYMTAB, LC_UUID, LC_FUNCTION_STARTS = 0x19, 0x2, 0x5, 0xb, 0x1b, 0x26+LC_DYLD_CHAINED_FIXUPS, LC_FILESET_ENTRY = 0x80000034, 0x80000035+N_EXT, N_PEXT, N_UNDF, N_ABS, N_SECT, N_WEAK_DEF = 0x01, 0x10, 0x0, 0x2, 0xe, 0x80+S_ZEROFILL, S_CSTRING_LITERALS, S_ATTR_DEBUG, TEXT_FLAGS = 0x1, 0x2, 0x02000000, 0x80000400+# <mach-o/arm64/reloc.h>+(UNSIGNED, SUBTRACTOR, BRANCH26, PAGE21, PAGEOFF12, GOT_LOAD_PAGE21, GOT_LOAD_PAGEOFF12, POINTER_TO_GOT, TLVP_PAGE21,+ TLVP_PAGEOFF12, ADDEND, AUTHENTICATED_POINTER) = range(12)+KEY_IA, KEY_IB, KEY_DA, KEY_DB = range(4) # <ptrauth.h>+DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8+MASK64 = (1 << 64) - 1+++def align(v, a):+ return -(-v // a) * a+++def name16(s):+ return s.encode().ljust(16, b'\0')+++def sext(v, bits):+ return v - (1 << bits) if v >> (bits - 1) & 1 else v+++def words(*insns):+ return struct.pack(f'<{len(insns)}I', *insns)+++# ---- instructions (their immediates zero, as an assembler leaves what a relocation fills in) ----+BL, B, NOP, RET = 0x94000000, 0x14000000, 0xd503201f, 0xd65f03c0+++def adrp(rd):+ return 0x90000000 | rd+++def add(rd, rn): # add xd, xn, #0+ return 0x91000000 | rn << 5 | rd+++def movz(rd, imm16): # mov wd, #imm16+ return 0x52800000 | imm16 << 5 | rd+++# name: (the load or store of register 2 at [x1, #0], log2 of the bytes it moves: what its 12-bit offset counts in)+LOADS = {+ 'strb w': (0x39000000, 0), 'ldrb w': (0x39400000, 0), 'ldrsb x': (0x39800000, 0), 'ldrsb w': (0x39c00000, 0),+ 'strh w': (0x79000000, 1), 'ldrh w': (0x79400000, 1), 'ldrsh x': (0x79800000, 1), 'ldrsh w': (0x79c00000, 1),+ 'str w': (0xb9000000, 2), 'ldr w': (0xb9400000, 2), 'ldrsw x': (0xb9800000, 2),+ 'str x': (0xf9000000, 3), 'ldr x': (0xf9400000, 3), 'prfm': (0xf9800000, 3),+ 'str b': (0x3d000000, 0), 'ldr b': (0x3d400000, 0), 'str h': (0x7d000000, 1), 'ldr h': (0x7d400000, 1),+ 'str s': (0xbd000000, 2), 'ldr s': (0xbd400000, 2), 'str d': (0xfd000000, 3), 'ldr d': (0xfd400000, 3),+ 'str q': (0x3d800000, 4), 'ldr q': (0x3dc00000, 4),+}+LOADS = {k: (v | 1 << 5 | 2, s) for k, (v, s) in LOADS.items()}+++def branch_target(insn, pc):+ """Where the b or bl at pc goes."""+ return pc + (sext(insn & 0x3ffffff, 26) << 2)+++def adrp_page(insn, pc):+ """The page the adrp at pc computes."""+ return (((pc >> 12) + sext((insn >> 5 & 0x7ffff) << 2 | insn >> 29 & 3, 21)) << 12) & MASK64+++def imm12(insn):+ return insn >> 10 & 0xfff+++# ---- an object file ----+class Object:+ """An arm64e MH_OBJECT: one unnamed segment, its sections one after the other from address 0, a symbol table.+ Sections and symbols are numbered as n_sect and r_symbolnum number them (from 1, from 0)."""++ def __init__(self, subtype=CPU_SUBTYPE_ARM64E | PTRAUTH_ABI):+ self.subtype = subtype+ self.sects = [] # [segment, name, data or None, size, log2 alignment, flags, address, relocations]+ self.syms = [] # (name, n_type, n_sect, n_desc, n_value)++ def section(self, seg, name, data=b'', align_=0, flags=0, zerofill=None):+ """A section with this content (zerofill: of that many bytes, with no content); returns its number."""+ addr = align(self.sects[-1][6] + self.sects[-1][3] if self.sects else 0, 1 << align_)+ if zerofill is not None:+ data, flags = None, flags | S_ZEROFILL+ self.sects.append([seg, name, None if data is None else bytearray(data),+ zerofill if data is None else len(data), align_, flags, addr, []])+ return len(self.sects)++ def text(self, *insns):+ return self.section('__TEXT', '__text', words(*insns), 2, TEXT_FLAGS)++ def addr(self, sect, off=0):+ """The address in the object of an offset into a section."""+ return self.sects[sect - 1][6] + off++ def data(self, sect):+ return self.sects[sect - 1][2]++ def define(self, name, sect, off=0, ext=True, weak=False, private=False):+ """A symbol at an offset into a section; returns its index."""+ self.syms.append((name, N_SECT | (N_EXT if ext else 0) | (N_PEXT if private else 0), sect,+ N_WEAK_DEF if weak else 0, self.addr(sect, off)))+ return len(self.syms) - 1++ def undefined(self, name):+ self.syms.append((name, N_UNDF | N_EXT, 0, 0, 0))+ return len(self.syms) - 1++ def absolute(self, name, value, ext=True):+ self.syms.append((name, N_ABS | (N_EXT if ext else 0), 0, 0, value))+ return len(self.syms) - 1++ def reloc(self, sect, off, typ, num, pcrel=0, length=2, extern=1, addend=None, minus=None):+ """A relocation_info for the bytes at an offset into a section. num: a symbol's index, or a section's number+ when extern is 0. addend: an ARM64_RELOC_ADDEND in front of it; minus: an ARM64_RELOC_SUBTRACTOR of that+ symbol in front of it (the two are a pair)."""+ def info(typ, num, pcrel, length, extern):+ return struct.pack('<iI', off, num & 0xffffff | pcrel << 24 | length << 25 | extern << 27 | typ << 28)+ entries = info(typ, num, pcrel, length, extern)+ if addend is not None:+ entries = info(ADDEND, addend, 0, 2, 0) + entries+ if minus is not None:+ entries = info(SUBTRACTOR, minus, 0, length, 1) + entries+ self.sects[sect - 1][7].append(entries)++ def pointer(self, sect, off, sym, addend=0):+ """.quad sym + addend"""+ struct.pack_into('<q', self.data(sect), off, addend)+ self.reloc(sect, off, UNSIGNED, sym, length=3)++ def auth_pointer(self, sect, off, sym, key, diversity=0, addr_div=0, addend=0):+ """.quad sym + addend@AUTH(key, diversity[, addr]): what the 8 bytes hold until the pointer is signed is+ addend:32 diversity:16 addrDiv:1 key:2 and, top bit, that it is to be signed."""+ struct.pack_into('<Q', self.data(sect), off, addend & 0xffffffff | diversity << 32 | addr_div << 48 |+ key << 49 | 1 << 63)+ self.reloc(sect, off, AUTHENTICATED_POINTER, sym, length=3)++ def build(self):+ nsects = len(self.sects)+ ncmds_size = 72 + 80 * nsects + 24+ pos = 32 + ncmds_size+ body, offsets = bytearray(), []+ for seg, name, data, size, al, flags, addr, relocs in self.sects:+ if data is None:+ offsets.append(0)+ continue+ pad = align(pos + len(body), 1 << al) - pos - len(body)+ body += bytes(pad)+ offsets.append(pos + len(body))+ body += data+ body += bytes(align(len(body), 8) - len(body))+ reloffs = []+ for s in self.sects:+ reloffs.append(pos + len(body) if s[7] else 0)+ body += b''.join(reversed(s[7])) # as an assembler writes them: the last one first+ strtab, nlists = bytearray(b'\0'), bytearray()+ for name, typ, sect, desc, value in self.syms:+ nlists += struct.pack('<IBBHQ', len(strtab), typ, sect, desc, value)+ strtab += name.encode() + b'\0'+ symoff = pos + len(body)+ end = self.sects[-1][6] + self.sects[-1][3] if self.sects else 0+ filesize = sum(s[3] for s in self.sects if s[2] is not None)+ cmds = struct.pack('<II16sQQQQiiII', LC_SEGMENT_64, 72 + 80 * nsects, b'', 0, end, pos, filesize, 7, 7, nsects,+ 0)+ for (seg, name, data, size, al, flags, addr, relocs), off, reloff in zip(self.sects, offsets, reloffs):+ cmds += struct.pack('<16s16sQQIIIIIIII', name16(name), name16(seg), addr, size, off, al, reloff,+ sum(map(len, relocs)) // 8, flags, 0, 0, 0)+ cmds += struct.pack('<IIIIII', LC_SYMTAB, 24, symoff, len(self.syms), symoff + len(nlists), len(strtab))+ return struct.pack('<IIIIIIII', MH_MAGIC_64, CPU_TYPE_ARM64, self.subtype, MH_OBJECT, 2, len(cmds), 0, 0) + \+ cmds + bytes(body) + bytes(nlists) + bytes(strtab)++ def write(self, directory, name):+ path = os.path.join(directory, name)+ with open(path, 'wb') as f:+ f.write(self.build())+ return path+++# ---- reading a Mach-O ----+def commands(buf, off=0):+ """[(cmd, its bytes)] of the image whose header is at off."""+ magic, _, _, _, ncmds, _, _, _ = struct.unpack_from('<8I', buf, off)+ assert magic == MH_MAGIC_64, hex(magic)+ out, p = [], off + 32+ for _ in range(ncmds):+ cmd, size = struct.unpack_from('<II', buf, p)+ out.append((cmd, bytes(buf[p:p + size])))+ p += size+ return out+++def segments(buf, off=0):+ """[{name, vmaddr, vmsize, fileoff, filesize, maxprot, initprot, flags, sections: [{sectname, segname, addr, size,+ offset, align, reloff, nreloc, flags}]}] of the image at off, in load command order."""+ out = []+ for cmd, raw in commands(buf, off):+ if cmd != LC_SEGMENT_64:+ continue+ n, vmaddr, vmsize, fileoff, filesize, maxprot, initprot, nsects, flags = struct.unpack_from('<16s4Q4I', raw, 8)+ seg = dict(name=n.rstrip(b'\0').decode(), vmaddr=vmaddr, vmsize=vmsize, fileoff=fileoff, filesize=filesize,+ maxprot=maxprot, initprot=initprot, flags=flags, sections=[])+ for i in range(nsects):+ sn, sg, addr, size, offset, al, reloff, nreloc, sflags = struct.unpack_from('<16s16sQQIIIII', raw,+ 72 + 80 * i)+ seg['sections'].append(dict(sectname=sn.rstrip(b'\0').decode(), segname=sg.rstrip(b'\0').decode(),+ addr=addr, size=size, offset=offset, align=al, reloff=reloff, nreloc=nreloc,+ flags=sflags))+ out.append(seg)+ return out+++def symtab(buf, off=0, base=0):+ """[(name, n_type, n_sect, n_desc, n_value)] of the image at off (its file offsets counted from base)."""+ for cmd, raw in commands(buf, off):+ if cmd == LC_SYMTAB:+ symoff, nsyms, stroff, strsize = struct.unpack_from('<4I', raw, 8)+ out = []+ for i in range(nsyms):+ strx, typ, sect, desc, value = struct.unpack_from('<IBBHQ', buf, base + symoff + 16 * i)+ end = buf.index(b'\0', base + stroff + strx)+ out.append((bytes(buf[base + stroff + strx:end]).decode(), typ, sect, desc, value))+ return out+ return []+++def fileset_entries(buf):+ """{name: (vmaddr, fileoff)} of a collection's LC_FILESET_ENTRY commands."""+ out = {}+ for cmd, raw in commands(buf):+ if cmd == LC_FILESET_ENTRY:+ vmaddr, fileoff, name_off = struct.unpack_from('<QQI', raw, 8)+ out[raw[name_off:].split(b'\0')[0].decode()] = (vmaddr, fileoff)+ return out+++class Pointer:+ """One dyld_chained_ptr_64_kernel_cache_rebase: target:30 cacheLevel:2 diversity:16 addrDiv:1 key:2 next:12+ isAuth:1, from the lowest bit up."""++ def __init__(self, raw):+ self.raw = raw+ self.target, self.cache_level = raw & 0x3fffffff, raw >> 30 & 3+ self.diversity, self.addr_div, self.key = raw >> 32 & 0xffff, raw >> 48 & 1, raw >> 49 & 3+ self.next, self.auth = raw >> 51 & 0xfff, raw >> 63++ def signing(self):+ """(key, diversity, address diversity) of a signed pointer, None of a plain one."""+ return (self.key, self.diversity, self.addr_div) if self.auth else None+++def chained_fixups(buf, payload=None):+ """Walks the chains of a collection's LC_DYLD_CHAINED_FIXUPS (or of the payload at (offset, size) of buf).+ Returns (header, starts, pointers):+ header: the dyld_chained_fixups_header's seven fields; starts: per segment of the collection, None or+ {offset, size, page_size, pointer_format, segment_offset, max_valid_pointer, page_start: [...]}, offset from the+ payload's start; pointers: {offset from the collection's header: Pointer}, in the order the chains are walked."""+ if payload is None:+ raw = next(raw for cmd, raw in commands(buf) if cmd == LC_DYLD_CHAINED_FIXUPS)+ payload = struct.unpack_from('<II', raw, 8)+ dataoff, datasize = payload+ header = struct.unpack_from('<7I', buf, dataoff)+ image = dataoff + header[1] # dyld_chained_starts_in_image+ seg_count = struct.unpack_from('<I', buf, image)[0]+ starts, pointers = [], {}+ for i in range(seg_count):+ info = struct.unpack_from('<I', buf, image + 4 + 4 * i)[0]+ if not info:+ starts.append(None)+ continue+ assert image + info + 22 <= dataoff + datasize+ size, page_size, fmt, seg_off, max_valid, page_count = struct.unpack_from('<IHHQIH', buf, image + info)+ page_start = list(struct.unpack_from(f'<{page_count}H', buf, image + info + 22))+ starts.append(dict(offset=header[1] + info, size=size, page_size=page_size, pointer_format=fmt,+ segment_offset=seg_off, max_valid_pointer=max_valid, page_start=page_start))+ for page, start in enumerate(page_start):+ if start == 0xffff: # DYLD_CHAINED_PTR_START_NONE+ continue+ loc = seg_off + page * page_size + start+ while True:+ p = pointers[loc] = Pointer(struct.unpack_from('<Q', buf, loc)[0])+ if not p.next:+ break+ loc += 4 * p.next # DYLD_CHAINED_PTR_64_KERNEL_CACHE: a stride of 4+ return header, starts, pointers+++# ---- a stand-in kernel ----+def thread_pointer(target, nxt=0, sign=None, text=0):+ """A threaded rebase as the static linker leaves it in a kernel (what XNU's rebase_threaded_starts reads):+ plain: the address' low 43 bits, its top byte in bits 43-50; signed (key, diversity, address diversity): the+ 32-bit offset from __TEXT, then diversity:16 addrDiv:1 key:2; next:11 at bit 51, isBind at 62, isAuth at 63."""+ if sign is None:+ return target & 0x7ffffffffff | (target >> 56) << 43 | nxt << 51+ key, diversity, addr_div = sign+ return (target - text) & 0xffffffff | diversity << 32 | addr_div << 48 | key << 49 | nxt << 51 | 1 << 63+++def kernel(segs, symbols=(), chains=(), stride=4, extra=()):+ """An arm64e executable like a kernel linked for a collection.+ segs: [(name, vmaddr, content, [(section name, offset in the segment, size, flags)])], __TEXT first: its first+ 0x1000 bytes are left for the header, and it gets the __thread_starts section, at 0x1000.+ symbols: [(name, address, external)]; chains: [[(address, target, signing or None)]], each one chain of+ threaded rebases in address order; extra: more load commands, as bytes."""+ segs = [(n, va, bytearray(c), list(sects)) for n, va, c, sects in segs]+ text = segs[0]+ assert text[0] == '__TEXT'++ def at(va):+ for n, base, content, _ in segs:+ if base <= va < base + len(content):+ return content, va - base+ raise ValueError(hex(va))++ starts = [0 if stride == 4 else 1]+ for chain in chains:+ starts.append(chain[0][0] - text[1])+ for (va, target, sign), following in zip(chain, list(chain[1:]) + [None]):+ nxt = (following[0] - va) // stride if following else 0+ assert nxt < 0x800 and (not following or (following[0] - va) % stride == 0), 'too far for one chain'+ content, off = at(va)+ struct.pack_into('<Q', content, off, thread_pointer(target, nxt, sign, text[1]))+ starts.append(0xffffffff)+ text[2][0x1000:0x1000 + 4 * len(starts)] = words(*starts)+ text[3].insert(0, ('__thread_starts', 0x1000, 4 * len(starts), 0))++ sections = [(n, va + off) for n, va, c, sects in segs for sn, off, size, fl in sects]+ strtab, nlists = bytearray(b'\0'), bytearray()+ for name, value, external in symbols:+ n_sect = max(i + 1 for i, (seg, a) in enumerate(sections) if a <= value) # the section it lies in+ nlists += struct.pack('<IBBHQ', len(strtab), N_SECT | (N_EXT if external else 0), n_sect, 0, value)+ strtab += name.encode() + b'\0'+ cmds, fileoff = [], 0+ for n, va, content, sects in segs:+ cmd = struct.pack('<II16sQQQQiiII', LC_SEGMENT_64, 72 + 80 * len(sects), name16(n), va, len(content), fileoff,+ len(content), 3, 3, len(sects), 0)+ for sn, off, size, fl in sects:+ cmd += struct.pack('<16s16sQQIIIIIIII', name16(sn), name16(n), va + off, size, fileoff + off, 0, 0, 0, fl,+ 0, 0, 0)+ cmds.append(cmd)+ fileoff += len(content)+ linkedit = bytes(nlists) + bytes(strtab)+ last = segs[-1]+ cmds.append(struct.pack('<II16sQQQQiiII', LC_SEGMENT_64, 72, name16('__LINKEDIT'), last[1] + len(last[2]),+ align(len(linkedit), 0x4000), fileoff, len(linkedit), 1, 1, 0, 0))+ cmds.append(struct.pack('<IIIIII', LC_SYMTAB, 24, fileoff, len(symbols), fileoff + len(nlists), len(strtab)))+ cmds.append(struct.pack('<II', LC_UNIXTHREAD, 288) + struct.pack('<II', 6, 68) + bytes(256) ++ struct.pack('<QQ', symbols[0][1] if symbols else 0, 0)) # ARM_THREAD_STATE64: pc+ cmds += extra+ body = b''.join(cmds)+ assert 32 + len(body) <= 0x1000+ text[2][0:32 + len(body)] = struct.pack('<IIIIIIII', MH_MAGIC_64, CPU_TYPE_ARM64, 0xc0000002, MH_EXECUTE,+ len(cmds), len(body), 0x200001, 0) + body+ return b''.join(bytes(c) for n, va, c, sects in segs) + linkedit+++# ---- linking a kext with kextld, the way kclink.py does ----+SPEC = {'name': 'Test', 'bundle': 'org.example.kext.test', 'version': '1.2.3', 'start': '_test_start',+ 'stop': '_test_stop'}+HEADER_VA = 0xfffffff007004000 # the collection's header+KEXT_VA = {'__TEXT': HEADER_VA + 0x100000, '__TEXT_EXEC': HEADER_VA + 0x2000000, '__DATA_CONST': HEADER_VA + 0x1000000,+ '__DATA': HEADER_VA + 0x3000000}+OUTSIDE = {'_test_start': HEADER_VA + 0x2f00000, '_test_stop': HEADER_VA + 0x2f00040} # what the kext links against+++class Linked:+ """A kext linked by kextld: its segments' bytes at their addresses, its pointers, its symbols."""++ def __init__(self, kx, result, addrs):+ self.kx, self.addrs = kx, addrs+ self.segments, self.fixups, self.symbols = result['segments'], result['fixups'], result['symbols']++ def bytes(self, va, n):+ for seg, b in self.segments.items():+ if self.addrs[seg] <= va and va + n <= self.addrs[seg] + len(b):+ return bytes(b[va - self.addrs[seg]:va - self.addrs[seg] + n])+ raise ValueError(f'{va:#x} is in no segment')++ def u32(self, va):+ return struct.unpack('<I', self.bytes(va, 4))[0]++ def u64(self, va):+ return struct.unpack('<Q', self.bytes(va, 8))[0]++ def section(self, seg, name):+ """(address, size) of a section of the kext."""+ s = self.kx.out[(seg, name)]+ return s.addr, s.size+++def kext(objects, spec=None):+ """A kextld.Kext of object files (paths), with the spec's keys over SPEC's."""+ import kextld+ with warnings.catch_warnings():+ warnings.simplefilter('ignore', ResourceWarning) # (kextld leaves closing its objects to the collector)+ return kextld.Kext(dict(SPEC, **(spec or {})), objects)+++def link(objects, outside=None, spec=None, addrs=None, inherited=None):+ """Links object files (paths) into a kext placed at KEXT_VA (or addrs); outside: {symbol: address} of what is not+ in the kext. Raises kextld.LinkError as kextld does."""+ kx = kext(objects, spec)+ sizes = kx.layout()+ addrs = dict(KEXT_VA, **(addrs or {}))+ for seg, (size, al) in sizes.items():+ assert addrs[seg] % al == 0, (seg, al)+ kx.place(addrs, HEADER_VA)+ return Linked(kx, kx.link(dict(OUTSIDE, **(outside or {})).get, inherited), addrs)+++# ---- a compiler, where there is one ----+PROBES = { # what a test needs of the compiler: (file suffix, a source that shows it, a relocation type it gives)+ 'asm': ('.s', '.text\n_f:\n\tbl _g\n', BRANCH26),+ 'auth': ('.s', '.data\n_p:\n\t.quad _g@AUTH(ia,7)\n', AUTHENTICATED_POINTER),+ 'c': ('.c', 'extern int g(int);\nint f(int x) { return g(x) + 1; }\n', BRANCH26),+}+CFLAGS = ['-O1', '-ffreestanding', '-nostdinc', '-fno-stack-protector']+++def relocation_types(buf):+ return {struct.unpack_from('<I', buf, s['reloff'] + 8 * i + 4)[0] >> 28+ for seg in segments(buf) for s in seg['sections'] for i in range(s['nreloc'])}+++def run_compiler(cc, source, suffix, directory, name='probe'):+ """(the object's path, None), or (None, what the compiler said)."""+ src, obj = os.path.join(directory, name + suffix), os.path.join(directory, name + '.o')+ with open(src, 'w') as f:+ f.write(source)+ try:+ r = subprocess.run(cc + ['--target=arm64e-apple-macos'] + (CFLAGS if suffix == '.c' else []) ++ ['-c', src, '-o', obj], capture_output=True, text=True)+ except OSError as e:+ return None, str(e)+ return (obj, None) if r.returncode == 0 else (None, r.stderr.strip() or f'exit status {r.returncode}')++[email protected]_cache(maxsize=None)+def compiler(kind):+ """(command, None) of a clang that makes arm64e Mach-O objects of this kind of source, or (None, why not).+ $KCLINK_TEST_CC names the compiler to use instead of the clang on the path."""+ named = os.environ.get('KCLINK_TEST_CC')+ if named:+ candidates = [shlex.split(named)]+ else: # clang, then clang-NN, the newest first+ versioned = {os.path.basename(p) for d in os.get_exec_path() for p in glob.glob(os.path.join(d, 'clang-*'))}+ versioned = sorted((c for c in versioned if c[6:].isdigit()), key=lambda c: -int(c[6:]))+ candidates = [[c] for c in ['clang'] + versioned if shutil.which(c)]+ suffix, source, reloc = PROBES[kind]+ why = 'no clang on the path'+ for cc in candidates:+ with tempfile.TemporaryDirectory() as d:+ obj, err = run_compiler(cc, source, suffix, d)+ if obj is None:+ why = f'{" ".join(cc)} makes no arm64e object of it: {err.splitlines()[-1]}'+ continue+ with open(obj, 'rb') as f:+ buf = f.read()+ magic, cpu, sub, filetype = struct.unpack_from('<4I', buf)+ if (magic, cpu, sub & 0xffffff, filetype) != (MH_MAGIC_64, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64E, MH_OBJECT):+ why = f'{" ".join(cc)} --target=arm64e-apple-macos made something else than an arm64e object'+ elif reloc not in relocation_types(buf):+ why = f'{" ".join(cc)} wrote no relocation of type {reloc} for it'+ else:+ return cc, None+ return None, why+++def compile(test, source, kind='asm', name='t'):+ """Compiles a source of this kind ('asm', 'auth': assembly with signed pointers, 'c') for the test, which is+ skipped where no compiler does that; returns the object's path."""+ cc, why = compiler(kind)+ if cc is None:+ raise unittest.SkipTest(f'needs a compiler ({kind}): {why}')+ d = tempfile.mkdtemp()+ test.addCleanup(shutil.rmtree, d)+ obj, err = run_compiler(cc, source, PROBES[kind][0], d, name)+ if obj is None:+ test.fail(f'{" ".join(cc)} compiles the probe but not this source:\n{err}')+ return obj+++def relocations(buf):+ """[(section number, r_address, type, symbolnum, extern, length, pcrel)] of an object, in the file's order."""+ out = []+ sects = [s for seg in segments(buf) for s in seg['sections']]+ for n, s in enumerate(sects, 1):+ for i in range(s['nreloc']):+ addr, info = struct.unpack_from('<iI', buf, s['reloff'] + 8 * i)+ out.append((n, addr, info >> 28, info & 0xffffff, info >> 27 & 1, info >> 25 & 3, info >> 24 & 1))+ return out+++def describe(buf):+ """What an object says, with nothing of how its symbol table happens to be numbered: each section's bytes, its+ relocations in the file's order with their symbols by name, and where its external symbols are."""+ sects = [s for seg in segments(buf) for s in seg['sections']]+ syms = symtab(buf)+ out = {}+ for n, s in enumerate(sects, 1):+ zerofill = s['flags'] & 0xff == S_ZEROFILL+ relocs = [(addr, typ, syms[num][0] if ext else num, ext, length, pcrel)+ for sn, addr, typ, num, ext, length, pcrel in relocations(buf) if sn == n]+ content = s['size'] if zerofill else bytes(buf[s['offset']:s['offset'] + s['size']])+ out[(s['segname'], s['sectname'])] = (content, s['align'], relocs)+ for name, typ, sect, desc, value in syms:+ if typ & N_EXT:+ where = (sects[sect - 1]['sectname'], value - sects[sect - 1]['addr']) if typ & 0xe == N_SECT else None+ out[name] = (typ, desc, where)+ return outdiff --git a/tests/kclink/test_kccompare.py b/tests/kclink/test_kccompare.pynew file mode 100755index 0000000..25648ea--- /dev/null+++ b/tests/kclink/test_kccompare.py@@ -0,0 +1,138 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""scripts/kclink/kccompare.py on collections that are the same and on ones made to differ in one thing: a word of a+kext's code, a byte of a string, where a pointer goes, how it is signed, a kext's zero-filled data, a byte of the+kernel, a kext's entry in the prelink info, a kext that only one has, the size of a segment of the collection, a key+of the prelink info itself. The collections are those of mkcollection.py.++ python3 tests/kclink/test_kccompare.py+"""+import os+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import mkmacho # noqa: E402+from mkcollection import (BASE, KCCOMPARE, SPEC_ONE, SPEC_THREE, Workdir, kext_one, kext_three) # noqa: E402++ONE, THREE = 'org.example.kext.one', 'org.example.kext.three'+++class Compared(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.w = w = Workdir(cls.addClassCleanup)+ w.template()+ w.kernel()+ cls.link('a.kc')++ @classmethod+ def link(cls, output, one=None, three=None, spec_one=SPEC_ONE, kernel='kernel'):+ """A collection with the kexts One and Three, made of these objects."""+ w = cls.w+ status, out, err = w.link('--native', w.native(spec_one, one or kext_one()),+ w.native(SPEC_THREE, three or kext_three('_kernel_data')), output=output,+ kernel=kernel)+ assert status == 0, err+ return output++ def compare(self, a, b):+ """kccompare's lines about two collections, after the first (the two headers and counts)."""+ status, out, err = self.w.run(KCCOMPARE, a, b)+ self.assertEqual(err, '')+ lines = out.splitlines()+ self.assertTrue(lines[0].startswith(f'header {BASE:#x} / {BASE:#x}; '), lines[0])+ self.assertEqual(status, 0 if lines[-1] == '0 differences' else 1, 'its exit status says whether they differ')+ return lines[1:]++ def one_difference(self, other, about):+ """The one line kccompare has about `a.kc` and this other collection, whichever is named first."""+ for a, b in (('a.kc', other), (other, 'a.kc')):+ lines = self.compare(a, b)+ self.assertEqual(lines[1:], ['1 differences'], lines)+ self.assertTrue(lines[0].startswith(about), lines[0])+ return self.compare('a.kc', other)[0]++ def test_the_same(self):+ self.assertEqual(self.compare('a.kc', 'a.kc'), ['0 differences'])+ self.assertEqual(self.compare('a.kc', self.link('again.kc')), ['0 differences'])+ status, out, err = self.w.run(KCCOMPARE, 'a.kc', 'a.kc')+ self.assertEqual(status, 0)+ self.assertEqual(out.splitlines()[0], f'header {BASE:#x} / {BASE:#x}; 15 / 15 pointers; 3 / 3 entries')++ def test_a_word_of_code(self):+ line = self.one_difference(self.link('b.kc', one=kext_one(answer=10)),+ f'{ONE} __TEXT_EXEC: 0 pointers and 1 words')+ helper = self.w.collection('a.kc').natives['_helper']+ self.assertIn(f"first words ['{helper - BASE:#x}']", line)++ def test_a_byte_of_a_string(self):+ self.one_difference(self.link('b.kc', one=kext_one(message=b'hello from a kexT\0')),+ f'{ONE} __TEXT: 0 pointers and 1 words')++ def test_where_a_pointer_goes(self):+ line = self.one_difference(self.link('b.kc', three=kext_three('_kernel_func')),+ f'{THREE} __DATA: 1 pointers and 0 words')+ a = self.w.collection('a.kc')+ self.assertIn(f'{a.natives["_three_pointer"] - BASE:#x}', line)++ def test_how_a_pointer_is_signed(self):+ line = self.one_difference(self.link('b.kc', one=kext_one(diversity=0x2222)),+ f'{ONE} __DATA: 1 pointers and 0 words')+ self.assertIn('div 0x1111', line)+ self.assertIn('div 0x2222', line)++ def test_a_pointer_where_the_other_has_none(self):+ plain = kext_three('_kernel_data')+ del plain[0].sects[1][7][:] # its pointer's relocation: 8 bytes of zero stay+ self.one_difference(self.link('b.kc', three=plain), f'{THREE} __DATA: 1 pointers and 0 words')++ def test_zero_filled_data(self):+ more = kext_three('_kernel_data')+ more[0].section('__DATA', '__bss', zerofill=64)+ self.one_difference(self.link('b.kc', three=more), f'{THREE}: segments differ')++ def test_a_byte_of_the_kernel(self):+ buf = bytearray(self.w.read('kernel'))+ data = next(s for s in mkmacho.segments(buf) if s['name'] == '__DATA')+ buf[data['fileoff'] + 0x20] ^= 1+ self.w.write('kernel.b', bytes(buf))+ self.one_difference(self.link('b.kc', kernel='kernel.b'), 'com.apple.kernel __DATA: 0 pointers and 1 words')++ def test_a_kexts_entry_in_the_prelink_info(self):+ spec = dict(SPEC_ONE, libraries={'com.apple.kpi.libkern': '9.0'})+ line = self.one_difference(self.link('b.kc', spec_one=spec), f'prelink info {ONE}: ')+ self.assertIn("('OSBundleLibraries', {'com.apple.kpi.libkern': '8.0'}, {'com.apple.kpi.libkern': '9.0'})", line)++ def test_a_kext_that_only_one_has(self):+ """Its entry in the collection and its entry in the prelink info: two differences, not none."""+ w = self.w+ status, out, err = w.link('--native', w.native(SPEC_ONE, kext_one()), output='b.kc')+ self.assertEqual((status, err), (0, ''))+ for a, b in (('a.kc', 'b.kc'), ('b.kc', 'a.kc')):+ self.assertEqual(self.compare(a, b), [f" entries in one only: ['{THREE}']",+ f"prelink info: entries in one only: ['{THREE}']", '2 differences'])++ def test_a_segment_of_the_collection(self):+ """A prelink info of two pages where the other's has one: __PRELINK_INFO is another size."""+ spec = dict(SPEC_ONE, plist={'Padding': 'x' * 0x4000})+ lines = self.compare('a.kc', self.link('b.kc', spec_one=spec))+ self.assertEqual(len(lines), 3, lines)+ self.assertEqual(lines[0], f' segment __PRELINK_INFO {BASE + 0x40000:#x}+0x4000 / __PRELINK_INFO '+ f'{BASE + 0x40000:#x}+0x8000')+ self.assertTrue(lines[1].startswith(f"prelink info {ONE}: [('Padding', None, 'xxxx"), lines[1])+ self.assertEqual(lines[2], '2 differences')++ def test_a_key_of_the_prelink_info_itself(self):+ template = self.w.read('template.kc')+ self.assertEqual(template.count(b'xnulinux-free-kc'), 1)+ self.w.write('other.kc', template.replace(b'xnulinux-free-kc', b'xnulinux-free-kd'))+ w = self.w+ status, out, err = w.link('--native', w.native(SPEC_ONE, kext_one()),+ w.native(SPEC_THREE, kext_three('_kernel_data')), base='other.kc', output='b.kc')+ self.assertEqual((status, err), (0, ''))+ self.assertEqual(self.compare('a.kc', 'b.kc'), ['prelink info: top-level keys differ', '1 differences'])+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_kclink_collection.py b/tests/kclink/test_kclink_collection.pynew file mode 100755index 0000000..bcd1e79--- /dev/null+++ b/tests/kclink/test_kclink_collection.py@@ -0,0 +1,344 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""A whole kernel collection, the way scripts/free-kc/build.sh makes one: mk-template.py's empty collection, a kernel+and a kext from objects linked into it by kclink.py. Nothing of a real kernel is used: the kernel is a stand-in of a+few pages with threaded rebases and four symbols, the kext is two objects built here, XNU's pseudo-extension property+lists are made up (mkcollection.py). Checked: the empty collection; the linked one's load commands, the kernel and the+kext in it, every chained fixup (walked by a reader of its own: page starts, the last pointer of a page, one over a+page's end) and the prelink info.++ python3 tests/kclink/test_kclink_collection.py+"""+import json+import os+import plistlib+import struct+import sys+import unittest+import uuid++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import mkmacho # noqa: E402+from mkmacho import (KEY_IA, LC_DYLD_CHAINED_FIXUPS, LC_FILESET_ENTRY, LC_FUNCTION_STARTS, LC_SEGMENT_64, # noqa: E402+ LC_SYMTAB, LC_UNIXTHREAD, LC_UUID, MH_EXECUTE, MH_FILESET, MH_KEXT_BUNDLE, S_ZEROFILL,+ adrp_page, branch_target, imm12, movz)+from mkcollection import (BASE, KPI, LAYOUT, MK_TEMPLATE, NO_ADDRESS, PAGE, REPO, SPEC_ONE, VERSION, # noqa: E402+ Workdir, kext_one, region)+import macho # noqa: E402+++class Template(unittest.TestCase):+ def setUp(self):+ self.w = Workdir(self.addCleanup)+ self.buf = self.w.template()++ def test_the_load_commands(self):+ magic, cpu, sub, filetype, ncmds, size, flags, _ = struct.unpack_from('<8I', self.buf)+ self.assertEqual((magic, cpu, sub & 0xffffff, filetype), (0xfeedfacf, 0x0100000c, 2, MH_FILESET))+ cmds = mkmacho.commands(self.buf)+ self.assertEqual(sum(len(raw) for cmd, raw in cmds), size)+ self.assertEqual([cmd for cmd, raw in cmds], [LC_UUID, 0x32, LC_UNIXTHREAD, LC_DYLD_CHAINED_FIXUPS] ++ [LC_SEGMENT_64] * 7 + [LC_FILESET_ENTRY])+ self.assertTrue(all(len(raw) % 8 == 0 for cmd, raw in cmds))+ self.assertEqual(len(cmds[2][1]), 288) # room for the kernel's thread state+ self.assertEqual(mkmacho.fileset_entries(self.buf), {'com.apple.kernel': (BASE + 0x4000, 0x4000)})+ self.assertLessEqual(32 + size, 0x4000)++ def test_the_segments_are_the_layouts(self):+ segs = mkmacho.segments(self.buf)+ self.assertEqual([[s['name'], hex(s['fileoff']), hex(s['filesize']), s['initprot'],+ s['sections'][0]['sectname'] if s['sections'] else None] for s in segs], LAYOUT['segments'])+ for s in segs:+ self.assertEqual((s['vmaddr'], s['vmsize'], s['maxprot']),+ (BASE + s['fileoff'], s['filesize'], s['initprot']))+ for sect in s['sections']: # __PRELINK_TEXT,__text and __PRELINK_INFO,__info+ self.assertEqual((sect['addr'], sect['size'], sect['offset'], sect['segname']),+ (s['vmaddr'], s['vmsize'], s['fileoff'], s['name']))+ self.assertEqual(len(self.buf), 0x60000) # it ends where the kernel's link-edit data will start++ def test_nothing_in_it_but_the_prelink_info(self):+ info, size = region(LAYOUT, '__PRELINK_INFO')+ blank = bytearray(self.buf)+ for a, b in ((0, 32 + struct.unpack_from('<I', self.buf, 20)[0]), (0x4000, 0x4000 + 32 + 144),+ (info, info + size), (0x5c000, 0x5c020)):+ blank[a:b] = bytes(b - a)+ self.assertEqual(blank, bytes(len(self.buf)))++ def test_the_kernels_slot(self):+ """A header where the kernel's will be, with the kernel's __LINKINFO slot and the shared __LINKEDIT."""+ img = macho.Image(self.buf, 0x4000)+ self.assertEqual((img.filetype, [s.name for s in img.segments]), (MH_EXECUTE, ['__LINKINFO', '__LINKEDIT']))+ self.assertEqual([(s.vmaddr - BASE, s.vmsize, s.fileoff) for s in img.segments],+ [(0x58000, 0x4000, 0x58000), (0x60000, 0, 0x60000)])++ def test_chained_fixups_with_no_chains(self):+ header, starts, pointers = mkmacho.chained_fixups(self.buf)+ self.assertEqual((header[0], header[4], starts, pointers), (0, 0, [], {}))+ raw = next(raw for cmd, raw in mkmacho.commands(self.buf) if cmd == LC_DYLD_CHAINED_FIXUPS)+ off, size = struct.unpack_from('<II', raw, 8)+ self.assertEqual(off, 0x5c000) # after the kernel's __LINKINFO slot+ self.assertLessEqual(header[1] + 4, size)+ self.assertEqual(macho.kc_read_fixups(self.buf, BASE, None), {})++ def test_the_prelink_info(self):+ info, size = region(LAYOUT, '__PRELINK_INFO')+ raw = self.buf[info:info + size].rstrip(b'\0')+ self.assertEqual(self.buf[info + len(raw)], 0) # a C string+ d = plistlib.loads(raw)+ self.assertEqual(sorted(d), ['KMBuildVersion', 'ManagerVersion', 'OSPrelinkInfoContainsUUIDs',+ '_PrelinkInfoDictionary', '_PrelinkKCID'])+ self.assertEqual(len(d['_PrelinkKCID']), 16)+ self.assertEqual([e['CFBundleIdentifier'] for e in d['_PrelinkInfoDictionary']], list(KPI.values()))+ for (bundle, ident), e in zip(KPI.items(), d['_PrelinkInfoDictionary']):+ self.assertEqual((e['CFBundleVersion'], e['CFBundleShortVersionString']), ('27.2.0', '27.2'))+ self.assertEqual(e['_PrelinkBundlePath'], f'/System/Library/Extensions/System.kext/PlugIns/{bundle}.kext')+ self.assertEqual((e['_PrelinkExecutableLoadAddr'], e['_PrelinkExecutableSourceAddr']),+ (NO_ADDRESS, NO_ADDRESS)) # no code: the kernel's own symbols+ self.assertIs(e['OSKernelResource'], True)++ def test_the_same_from_the_same_and_another_for_another_kernel(self):+ self.assertEqual(self.w.template('again.kc'), self.buf)+ other = self.w.template('other.kc', version='27.3.0')+ self.assertNotEqual(other, self.buf)+ ids = [plistlib.loads(b[0x40000:0x48000].rstrip(b'\0'))['_PrelinkKCID'] for b in (self.buf, other)]+ self.assertNotEqual(ids[0], ids[1])+ uuids = [next(raw for cmd, raw in mkmacho.commands(b) if cmd == LC_UUID) for b in (self.buf, other)]+ self.assertNotEqual(uuids[0], uuids[1])++ def test_a_pseudo_extension_that_is_missing(self):+ os.remove(self.w.path('xnu', 'config', 'System.kext', 'PlugIns', 'Mach.kext', 'Info.plist'))+ status, out, err = self.w.run(MK_TEMPLATE, 'layout.json', 'xnu', VERSION, 'none.kc')+ self.assertNotEqual(status, 0)+ self.assertFalse(os.path.exists(self.w.path('none.kc')))++ def test_the_layout_of_the_repository(self):+ """scripts/free-kc/layout.json: the segments follow each other on page boundaries, the kernel's header is at+ the start of __PRELINK_TEXT, its __LINKINFO slot and the chained fixups are in __LINKEDIT, and mk-template.py+ makes a collection of it."""+ with open(os.path.join(REPO, 'scripts', 'free-kc', 'layout.json')) as f:+ layout = json.load(f)+ end = 0+ for name, off, size, prot, sect in layout['segments']:+ self.assertEqual((int(off, 16), int(size, 16) % PAGE), (end, 0), name)+ end += int(size, 16)+ self.assertEqual([n for n, *rest in layout['segments']], [n for n, *rest in LAYOUT['segments']])+ self.assertEqual(int(layout['kernel_header'], 16), region(layout, '__PRELINK_TEXT')[0])+ self.assertEqual(int(layout['kernel_linkinfo'][0], 16), region(layout, '__LINKEDIT')[0])+ self.assertEqual(int(layout['kernel_linkedit'], 16), end)+ w = Workdir(self.addCleanup, layout)+ buf = w.template()+ self.assertEqual(len(buf), end)+ self.assertEqual([(s['name'], s['fileoff'], s['filesize']) for s in mkmacho.segments(buf)],+ [(n, int(off, 16), int(size, 16)) for n, off, size, prot, sect in layout['segments']])+++class Linked(unittest.TestCase):+ """The template, the stand-in kernel and one kext from two objects, linked by kclink.py."""++ @classmethod+ def setUpClass(cls):+ cls.w = w = Workdir(cls.addClassCleanup)+ w.template()+ cls.ksyms, cls.kpointers = w.kernel()+ status, cls.log, err = w.link('--native', w.native(SPEC_ONE, kext_one()))+ assert status == 0, err+ cls.kc = w.collection()++ def test_the_collections_load_commands(self):+ kc, template = self.kc, self.w.read('template.kc')+ cmds, before = mkmacho.commands(kc.buf), mkmacho.commands(template)+ self.assertEqual(struct.unpack_from('<8I', kc.buf)[:4], struct.unpack_from('<8I', template)[:4])+ self.assertEqual(sum(len(raw) for cmd, raw in cmds), struct.unpack_from('<I', kc.buf, 20)[0])+ self.assertEqual([cmd for cmd, raw in cmds], [cmd for cmd, raw in before] + [LC_FILESET_ENTRY])+ self.assertEqual(cmds[:2], before[:2]) # LC_UUID, LC_BUILD_VERSION+ kernel_thread = next(raw for cmd, raw in mkmacho.commands(self.w.read('kernel')) if cmd == LC_UNIXTHREAD)+ self.assertEqual(cmds[2][1], kernel_thread)+ self.assertEqual(struct.unpack_from('<Q', kernel_thread, 16 + 32 * 8)[0], self.ksyms['_kernel_start'])+ self.assertEqual(list(kc.entries), ['com.apple.kernel', 'org.example.kext.one'])+ for name, (va, off) in kc.entries.items():+ self.assertEqual(va - BASE, off, name)+ self.assertEqual(struct.unpack_from('<I', kc.buf, off)[0], 0xfeedfacf, name)++ def test_the_collections_segments(self):+ kc = self.kc+ self.assertEqual(list(kc.segments), [n for n, *rest in LAYOUT['segments']])+ end = 0+ for s in kc.segments.values():+ self.assertEqual((s['vmaddr'] - BASE, s['vmsize']), (s['fileoff'], s['filesize']), s['name'])+ self.assertEqual((s['fileoff'] % PAGE, s['filesize'] % PAGE), (0, 0), s['name'])+ self.assertGreaterEqual(s['fileoff'], end, s['name'])+ end = s['fileoff'] + s['filesize']+ self.assertEqual(end, len(kc.buf)) # __LINKEDIT runs to the end of the file+ for name in ('__TEXT', '__PRELINK_TEXT', '__DATA_CONST', '__TEXT_EXEC', '__DATA'):+ self.assertEqual((kc.segments[name]['fileoff'], kc.segments[name]['filesize']), region(LAYOUT, name))+ text = kc.segments['__PRELINK_TEXT']+ self.assertEqual((text['sections'][0]['addr'], text['sections'][0]['size']), (text['vmaddr'], text['vmsize']))++ def test_the_kernel_in_it(self):+ kc, kernel = self.kc, self.w.read('kernel')+ off, segs = kc.entry('com.apple.kernel')+ self.assertEqual(off, 0x4000)+ magic, cpu, sub, filetype, ncmds, size, flags, _ = struct.unpack_from('<8I', kc.buf, off)+ self.assertEqual(filetype, MH_EXECUTE)+ self.assertEqual(flags, struct.unpack_from('<I', kernel, 24)[0] | 0x80000000) # MH_DYLIB_IN_CACHE+ cmds, before = mkmacho.commands(kc.buf, off), mkmacho.commands(kernel)+ self.assertEqual([cmd for cmd, raw in cmds], [cmd for cmd, raw in before if cmd != LC_FUNCTION_STARTS])+ was = {s['name']: s for s in mkmacho.segments(kernel)}+ self.assertEqual(list(segs), list(was))+ for name, s in segs.items():+ if name == '__LINKEDIT':+ continue+ self.assertEqual((s['vmaddr'], s['vmsize'], s['filesize']),+ (was[name]['vmaddr'], was[name]['vmsize'], was[name]['filesize']), name)+ self.assertEqual(s['fileoff'], s['vmaddr'] - BASE, name)+ for sect, old in zip(s['sections'], was[name]['sections']):+ self.assertEqual((sect['sectname'], sect['addr'], sect['size'], sect['flags']),+ (old['sectname'], old['addr'], old['size'], old['flags']))+ self.assertEqual(sect['offset'], 0 if sect['flags'] == S_ZEROFILL else sect['addr'] - BASE)+ # its bytes, but for the pointers and the header (both rewritten)+ mine = bytearray(kc.buf[s['fileoff']:s['fileoff'] + s['filesize']])+ theirs = bytearray(kernel[was[name]['fileoff']:was[name]['fileoff'] + s['filesize']])+ for buf in (mine, theirs):+ if name == '__TEXT':+ buf[0:0x1000] = bytes(0x1000)+ for va, target, sign in self.kpointers:+ if s['vmaddr'] <= va < s['vmaddr'] + s['vmsize']:+ buf[va - s['vmaddr']:va - s['vmaddr'] + 8] = bytes(8)+ self.assertEqual(mine, theirs, name)+ # its symbols, in the link-edit data every entry shares to the end of the file+ self.assertEqual(mkmacho.symtab(kc.buf, off), mkmacho.symtab(kernel))+ le = segs['__LINKEDIT']+ self.assertEqual(le['fileoff'] + le['filesize'], len(kc.buf))+ self.assertEqual(le['vmaddr'] - BASE, le['fileoff'])+ symoff = struct.unpack_from('<I', next(raw for cmd, raw in cmds if cmd == LC_SYMTAB), 8)[0]+ self.assertGreaterEqual(symoff, le['fileoff'])++ def test_the_kext_in_it(self):+ kc, n = self.kc, self.kc.natives+ off, segs = kc.entry('org.example.kext.one')+ magic, cpu, sub, filetype, ncmds, size, flags, _ = struct.unpack_from('<8I', kc.buf, off)+ self.assertEqual((filetype, sub & 0xffffff), (MH_KEXT_BUNDLE, 2))+ self.assertEqual(list(segs), ['__TEXT', '__TEXT_EXEC', '__DATA', '__DATA_CONST', '__LINKEDIT'])+ inside = {'__TEXT': '__PRELINK_TEXT', '__TEXT_EXEC': '__TEXT_EXEC', '__DATA': '__DATA',+ '__DATA_CONST': '__DATA_CONST'}+ _, kernel = kc.entry('com.apple.kernel')+ for name, where in inside.items():+ s, r = segs[name], kc.segments[where]+ self.assertEqual(s['fileoff'], s['vmaddr'] - BASE, name)+ self.assertTrue(r['vmaddr'] <= s['vmaddr'] and s['vmaddr'] + s['vmsize'] <= r['vmaddr'] + r['vmsize'], name)+ for k in kernel.values(): # and in none of the kernel's+ self.assertTrue(s['vmaddr'] + s['vmsize'] <= k['vmaddr'] or k['vmaddr'] + k['vmsize'] <= s['vmaddr'],+ f'{name} and the kernel\'s {k["name"]}')+ self.assertEqual(segs['__TEXT']['vmaddr'], kc.entries['org.example.kext.one'][0])+ self.assertEqual(segs['__LINKEDIT']['fileoff'] + segs['__LINKEDIT']['filesize'], len(kc.buf))+ # its code, resolved against itself and the kernel+ start = n['_one_start']+ self.assertEqual(start, segs['__TEXT_EXEC']['vmaddr'])+ self.assertEqual(branch_target(kc.u32(start), start), n['_helper'])+ self.assertEqual(kc.u32(n['_helper']), movz(0, 9))+ self.assertEqual(branch_target(kc.u32(start + 4), start + 4), self.ksyms['_kernel_func'])+ slot = adrp_page(kc.u32(start + 8), start + 8) + (imm12(kc.u32(start + 12)) << 3)+ self.assertEqual(kc.pointer(slot), (self.ksyms['_kernel_data'], None))+ message = adrp_page(kc.u32(start + 16), start + 16) + imm12(kc.u32(start + 20))+ self.assertEqual(message, n['_message'])+ self.assertEqual(kc.buf[message - BASE:message - BASE + 18], b'hello from a kext\0')+ self.assertEqual(sorted(n), ['_helper', '_message', '_one_start', '_one_stop', '_pointers', '_table'])++ def test_every_pointer_is_a_chained_fixup(self):+ kc, n, k = self.kc, self.kc.natives, self.ksyms+ _, segs = kc.entry('org.example.kext.one')+ data = segs['__DATA']['vmaddr']+ got = next(s for s in segs['__DATA_CONST']['sections'] if s['sectname'] == '__got')['addr']+ expected = {va: (target, sign) for va, target, sign in self.kpointers}+ expected.update({+ n['_pointers']: (k['_kernel_data'], None), n['_pointers'] + 8: (n['_one_start'], (KEY_IA, 0x1111, 1)),+ n['_pointers'] + 16: (n['_message'], None),+ n['_table']: (n['_helper'], (KEY_IA, 0, 0)), n['_table'] + 8: (k['_kernel_private'], None),+ got: (k['_kernel_data'], None),+ data + 180: (n['_one_start'], (KEY_IA, 0xe4fe, 0)), data + 188: (n['_one_stop'], (KEY_IA, 0xe4fe, 0))})+ self.assertEqual({BASE + off: (BASE + p.target, p.signing()) for off, p in kc.pointers.items()}, expected)+ self.assertTrue(all(p.cache_level == 0 for p in kc.pointers.values()))+ self.assertEqual(len(expected), 12)++ def test_the_chains(self):+ kc = self.kc+ self.assertEqual((kc.header[0], kc.header[4]), (0, 0)) # version 0, no imports+ self.assertEqual(len(kc.starts), len(kc.segments)) # one entry per segment of the collection, in order+ for s, starts in zip(kc.segments.values(), kc.starts):+ mine = sorted(off for off in kc.pointers if s['fileoff'] <= off < s['fileoff'] + s['filesize'])+ if not mine:+ self.assertIsNone(starts, s['name'])+ continue+ self.assertEqual((starts['pointer_format'], starts['page_size'], starts['segment_offset']),+ (8, PAGE, s['fileoff']), s['name']) # DYLD_CHAINED_PTR_64_KERNEL_CACHE+ self.assertEqual(len(starts['page_start']), s['filesize'] // PAGE)+ for page, first in enumerate(starts['page_start']):+ on_page = [off for off in mine if (off - s['fileoff']) // PAGE == page]+ self.assertEqual(first, (on_page[0] - s['fileoff']) % PAGE if on_page else 0xffff,+ f'{s["name"]}, page {page}')+ for off, following in zip(on_page, on_page[1:] + [None]):+ self.assertEqual(kc.pointers[off].next, (following - off) // 4 if following else 0, hex(off))+ # the kernel's pointer over the end of a page is the last of its page; the next page starts after it+ dc = kc.segments['__DATA_CONST']+ self.assertIn(dc['fileoff'] + 0x3ffc, kc.pointers)+ self.assertEqual(kc.starts[2]['page_start'][:2], [0, 8])+ self.assertEqual(kc.pointers[dc['fileoff'] + 0x3ffc].next, 0)+ # what macho.py reads back is what was walked here+ back = macho.kc_read_fixups(kc.buf, BASE, None)+ self.assertEqual({off: (f.target, None if f.key is None else (f.key, f.div, f.addr_div))+ for off, f in back.items()},+ {off: (BASE + p.target, p.signing()) for off, p in kc.pointers.items()})++ def test_the_kexts_kmod_info(self):+ kc = self.kc+ _, segs = kc.entry('org.example.kext.one')+ at = kc.kexts['org.example.kext.one']['_PrelinkKmodInfo'] + (1 << 64)+ self.assertEqual(at, segs['__DATA']['vmaddr'])+ nxt, version, ident, name, vers, refs, reflist, address, size = \+ struct.unpack_from('<QIi64s64siQQQ', kc.buf, at - BASE)+ self.assertEqual((nxt, version, ident, refs, reflist), (0, 1, -1, -1, 0))+ self.assertEqual((name.rstrip(b'\0'), vers.rstrip(b'\0')), (b'org.example.kext.one', b'1.0.0'))+ self.assertEqual((address, size), (segs['__TEXT']['vmaddr'], segs['__TEXT']['vmsize']))++ def test_the_prelink_info(self):+ kc = self.kc+ seg = kc.segments['__PRELINK_INFO']+ self.assertTrue(kc.plist.startswith(b'<?xml'))+ self.assertLessEqual(len(kc.plist), seg['filesize'])+ self.assertEqual(seg['filesize'], -(-len(kc.plist) // PAGE) * PAGE) # as many pages as it takes+ self.assertEqual(kc.buf[seg['fileoff'] + len(kc.plist):seg['fileoff'] + seg['filesize']],+ bytes(seg['filesize'] - len(kc.plist)))+ # nothing between the elements: a kernel's prelink info has no room for indentation+ body = kc.plist[kc.plist.index(b'<plist'):]+ self.assertNotIn(b'\t', body)+ self.assertEqual(body.count(b'\n'), 1)+ # the template's entries and keys, and the kext's+ before = plistlib.loads(self.w.read('template.kc')[0x40000:0x48000].rstrip(b'\0'))+ self.assertEqual({k: v for k, v in kc.info.items() if k != '_PrelinkInfoDictionary'},+ {k: v for k, v in before.items() if k != '_PrelinkInfoDictionary'})+ self.assertEqual(kc.info['_PrelinkInfoDictionary'][:7], before['_PrelinkInfoDictionary'])+ self.assertEqual(list(kc.kexts), list(KPI.values()) + ['org.example.kext.one'])+ d = kc.kexts['org.example.kext.one']+ _, segs = kc.entry('org.example.kext.one')+ text = segs['__TEXT']+ self.assertEqual(d['_PrelinkExecutableLoadAddr'], text['vmaddr'] - (1 << 64))+ self.assertEqual(d['_PrelinkExecutableSourceAddr'], text['vmaddr'] - (1 << 64))+ self.assertEqual(d['_PrelinkExecutableSize'], text['vmsize'])+ self.assertEqual((d['CFBundleIdentifier'], d['CFBundleExecutable'], d['CFBundleVersion']),+ ('org.example.kext.one', 'One', '1.0.0'))+ self.assertEqual(d['CFBundlePackageType'], 'KEXT')+ self.assertEqual((d['OSBundleLibraries'], d['IOKitPersonalities']),+ (SPEC_ONE['libraries'], SPEC_ONE['personalities']))+ self.assertEqual(d['OSBundleUUID'], uuid.uuid5(uuid.NAMESPACE_URL, 'org.example.kext.one').bytes)+ cmds = mkmacho.commands(kc.buf, kc.entries['org.example.kext.one'][1])+ self.assertEqual(next(raw for cmd, raw in cmds if cmd == LC_UUID)[8:], d['OSBundleUUID'])++ def test_what_it_says(self):+ self.assertIn('kernel: 4 threaded pointers (2 signed)', self.log)+ header = self.kc.entries['org.example.kext.one'][0]+ self.assertIn(f'org.example.kext.one: linked, header at {header:#x}, 8 pointers', self.log)+ self.assertIn(f'wrote out.kc: {len(self.kc.buf):#x} bytes, base {BASE:#x}, 12 chained pointers', self.log)+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_kclink_prelink_info.py b/tests/kclink/test_kclink_prelink_info.pynew file mode 100755index 0000000..4b7a255--- /dev/null+++ b/tests/kclink/test_kclink_prelink_info.py@@ -0,0 +1,103 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Two pieces of scripts/kclink/kclink.py on their own: the prelink info as it is written (prelink_xml: a property list+with nothing between its elements, which must read back as what plistlib itself writes), and the room handed out to+native kexts (Holes: first fit, aligned).++ python3 tests/kclink/test_kclink_prelink_info.py+"""+import os+import plistlib+import sys+import unittest++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'scripts', 'kclink'))+import kclink # noqa: E402++INFO = {+ '_PrelinkInfoDictionary': [+ {'CFBundleIdentifier': 'org.example.kext', '_PrelinkExecutableLoadAddr': -0xffffff8f8fc000,+ '_PrelinkExecutableSize': 0x1020, 'OSBundleUUID': bytes(range(16)), 'OSBundleLibraries': {},+ 'IOKitPersonalities': {'P': {'IOClass': 'A<B> & C', 'IOProbeScore': 0, 'Flag': True, 'Off': False,+ 'List': [1, 'two', b'\x03', [], {}]}}},+ {'CFBundleIdentifier': 'com.apple.kpi.bsd', '_PrelinkExecutableLoadAddr': 0x7fffffffffffffff}],+ '_PrelinkKCID': b'\xff' * 16, 'ManagerVersion': 1, 'Text': 'two\r\nlines\rand one\nmore', 'Unicode': 'kéxt',+ 'Largest': (1 << 64) - 1, 'Smallest': -1 << 63,+}+++class PrelinkInfo(unittest.TestCase):+ def test_it_reads_back_as_what_plistlib_writes(self):+ out = kclink.prelink_xml(INFO)+ self.assertEqual(plistlib.loads(out), plistlib.loads(plistlib.dumps(INFO)))+ self.assertEqual(plistlib.loads(out)['Text'], 'two\nlines\nand one\nmore') # (as plistlib has them)++ def test_nothing_between_the_elements(self):+ out = kclink.prelink_xml(INFO)+ head, _, body = out.partition(b'<plist version="1.0">')+ self.assertEqual(head, plistlib.dumps(INFO).partition(b'<plist version="1.0">')[0])+ self.assertTrue(head.startswith(b'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist '))+ self.assertTrue(body.endswith(b'</dict></plist>\n'))+ text = body.decode().replace('two\nlines\nand one\nmore', '')+ self.assertNotIn('\t', text)+ self.assertEqual(text.count('\n'), 1)+ self.assertNotIn('> <', text)+ self.assertLess(len(out), len(plistlib.dumps(INFO)))++ def test_one_of_each(self):+ out = kclink.prelink_xml({'b': [True, False, -5, 'a&b<c>', b'\x00\x01\x02', {}, []], 'a': {'k': 1}})+ self.assertEqual(out.partition(b'<plist version="1.0">')[2].decode(),+ '<dict><key>a</key><dict><key>k</key><integer>1</integer></dict><key>b</key><array><true/>'+ '<false/><integer>-5</integer><string>a&b<c></string><data>AAEC</data><dict/>'+ '<array/></array></dict></plist>\n')++ def test_the_keys_in_one_order_whatever_order_they_came_in(self):+ there = {'b': 1, 'a': {'y': 1, 'x': 2}, 'c': 3}+ back = {'c': 3, 'a': {'x': 2, 'y': 1}, 'b': 1}+ self.assertEqual(kclink.prelink_xml(there), kclink.prelink_xml(back))+ out = kclink.prelink_xml(there)+ self.assertLess(out.index(b'<key>a</key>'), out.index(b'<key>b</key>'))++ def test_what_a_property_list_cannot_hold(self):+ for bad in ({'a': None}, {'a': {1, 2}}, {'a': object()}, {1: 'a'}, {'a': 1 << 64}):+ with self.assertRaises((SystemExit, TypeError, OverflowError), msg=repr(bad)):+ kclink.prelink_xml(bad)+++class Holes(unittest.TestCase):+ def test_first_fit(self):+ h = kclink.Holes(0x1000, 0x9000)+ self.assertEqual(h.fit(0x800, 16), 0x1000)+ self.assertEqual(h.fit(0x800, 16), 0x1800)+ self.assertEqual(h.free, [(0x2000, 0x9000)])++ def test_aligned(self):+ h = kclink.Holes(0x1010, 0x9000)+ self.assertEqual(h.fit(0x10, 0x1000), 0x2000)+ self.assertEqual(h.free, [(0x1010, 0x2000), (0x2010, 0x9000)])+ self.assertEqual(h.fit(0x20, 16), 0x1010) # the room before it is still there+ self.assertEqual(h.fit(0x1000, 0x4000), 0x4000)++ def test_taken_ranges(self):+ h = kclink.Holes(0, 0x10000)+ h.take(0x4000, 0x8000) # the middle: two holes+ self.assertEqual(h.free, [(0, 0x4000), (0x8000, 0x10000)])+ h.take(0x3000, 0x9000) # over the end of one and the start of the other+ self.assertEqual(h.free, [(0, 0x3000), (0x9000, 0x10000)])+ h.take(0x20000, 0x30000) # outside: nothing changes+ self.assertEqual(h.free, [(0, 0x3000), (0x9000, 0x10000)])+ self.assertEqual(h.fit(0x4000, 16), 0x9000) # too large for the first+ self.assertEqual(h.fit(0x3000, 16), 0) # exactly the first+ self.assertEqual(h.free, [(0xd000, 0x10000)])++ def test_no_room(self):+ h = kclink.Holes(0x10, 0x1000)+ self.assertIsNone(h.fit(0xff1, 1)) # a byte too many+ self.assertIsNone(h.fit(0x800, 0x1000)) # small enough, but not from the next page boundary+ self.assertEqual(h.free, [(0x10, 0x1000)])+ self.assertEqual(h.fit(0xff0, 1), 0x10)+ self.assertEqual(h.free, [])+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_kclink_relink.py b/tests/kclink/test_kclink_relink.pynew file mode 100755index 0000000..99e50bb--- /dev/null+++ b/tests/kclink/test_kclink_relink.py@@ -0,0 +1,304 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""More of scripts/kclink/kclink.py, on the stand-in collection of mkcollection.py: several kexts that use each other,+where kexts may not go (--reserve, the kernel's __PRELINK_DATA), a collection linked again with its kexts kept (--keep:+for a kernel somewhere else whose symbols moved, --rebind, patch_personalities), that the same input gives the same+bytes, and what it refuses.++ python3 tests/kclink/test_kclink_relink.py+"""+import json+import os+import struct+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import mkmacho # noqa: E402+from mkmacho import KEY_IA, LC_SEGMENT_64, Object, RET, branch_target # noqa: E402+from mkcollection import (BASE, KPI, PAGE, SPEC_ONE, SPEC_THREE, SPEC_TWO, Workdir, kext_one, kext_three, # noqa: E402+ kext_two)++SLIDE = 0x8000000+ONE, TWO, THREE = 'org.example.kext.one', 'org.example.kext.two', 'org.example.kext.three'+++def spans(kc, name):+ """[(start, end)] of an entry's segments in the file, its share of __LINKEDIT left out."""+ return [(s['fileoff'], s['fileoff'] + s['filesize']) for s in kc.entry(name)[1].values()+ if s['name'] != '__LINKEDIT']+++class Natives(unittest.TestCase):+ def setUp(self):+ self.w = Workdir(self.addCleanup)+ self.w.template()+ self.ksyms, self.kpointers = self.w.kernel()+ self.one = self.w.native(SPEC_ONE, kext_one())++ def linked(self, *args, **how):+ status, out, err = self.w.link(*args, **how)+ self.assertEqual((status, err), (0, ''))+ return self.w.collection(how.get('output', 'out.kc'))++ def refused(self, *args, **how):+ """What kclink says when it gives up: one line, and no collection."""+ status, out, err = self.w.link(*args, output='refused.kc', **how)+ self.assertNotEqual(status, 0)+ self.assertFalse(os.path.exists(self.w.path('refused.kc')))+ self.assertEqual(err.count('\n'), 1, err)+ self.assertTrue(err.startswith('kclink: '), err)+ return err++ def test_a_kext_that_calls_another(self):+ kc = self.linked('--native', self.one, self.w.native(SPEC_TWO, kext_two()))+ self.assertEqual(list(kc.entries), ['com.apple.kernel', ONE, TWO])+ at = kc.natives['_two_start']+ self.assertEqual(branch_target(kc.u32(at), at), kc.natives['_helper'])+ taken = sorted(span + (name,) for name in kc.entries for span in spans(kc, name))+ for (a1, b1, n1), (a2, b2, n2) in zip(taken, taken[1:]):+ self.assertLessEqual(b1, a2, f'{n1} and {n2} overlap')+ self.assertEqual(len(kc.pointers), 14)+ self.assertEqual(list(kc.kexts)[7:], [ONE, TWO])+ self.assertEqual(kc.kexts[TWO]['OSBundleLibraries'], {ONE: '1.0'})+ # the other order: the first one's call binds to a kext linked after it+ kc = self.linked('--native', self.w.native(SPEC_TWO, kext_two()), self.one)+ self.assertEqual(list(kc.entries), ['com.apple.kernel', TWO, ONE])+ at = kc.natives['_two_start']+ self.assertEqual(branch_target(kc.u32(at), at), kc.natives['_helper'])++ def test_reserved_room_stays_free(self):+ plain = self.linked('--native', self.one)+ data = plain.entry(ONE)[1]['__DATA']+ self.assertEqual(data['fileoff'], 0x4c000) # behind the kernel's page of data+ kc = self.linked('--native', self.one, '--reserve', '__DATA:0x4c000-0x50000', '__TEXT_EXEC:0x34000-0x34100')+ self.assertEqual(kc.entry(ONE)[1]['__DATA']['fileoff'], 0x50000)+ self.assertEqual(kc.entry(ONE)[1]['__TEXT_EXEC']['fileoff'], 0x34100)+ self.assertEqual(kc.entry(ONE)[1]['__TEXT']['fileoff'], plain.entry(ONE)[1]['__TEXT']['fileoff'])++ def test_kexts_data_from_the_kernels_prelink_data_on(self):+ self.w.kernel('kernel.pd', prelink_data=0x54000)+ kc = self.linked('--native', self.one, kernel='kernel.pd')+ self.assertEqual(kc.entry(ONE)[1]['__DATA']['fileoff'], 0x54000)++ def test_a_kernel_laid_out_for_somewhere_else(self):+ """The collection is where the kernel is: its header as far below the kernel's __TEXT as in the template."""+ ksyms, kpointers = self.w.kernel('kernel.high', base=BASE + SLIDE)+ low, high = self.linked('--native', self.one), self.linked('--native', self.one, kernel='kernel.high',+ output='high.kc')+ self.assertEqual(high.base, BASE + SLIDE)+ self.assertEqual({n: (va - SLIDE, off) for n, (va, off) in high.entries.items()}, low.entries)+ self.assertEqual({off: (p.target, p.signing()) for off, p in high.pointers.items()},+ {off: (p.target, p.signing()) for off, p in low.pointers.items()})+ self.assertEqual({n: a - SLIDE for n, a in high.natives.items()}, low.natives)+ self.assertEqual(high.kexts[ONE]['_PrelinkKmodInfo'], low.kexts[ONE]['_PrelinkKmodInfo'] + SLIDE)++ def test_what_is_refused(self):+ w = self.w+ self.assertIn('kernel: not a kernel collection', self.refused(base='kernel'))+ self.assertIn('org.example.nowhere: not in template.kc', self.refused('--keep', 'org.example.nowhere'))+ self.assertIn(f'{ONE} is in the collection already', self.refused('--native', self.one, self.one))+ o = Object()+ o.define('_three_start', o.text(RET))+ self.assertIn(f'{THREE}: unresolved symbols: _three_stop',+ self.refused('--native', w.native(SPEC_THREE, [o])))+ self.assertIn(f'{THREE}: unresolved symbols: _nowhere',+ self.refused('--native', w.native(SPEC_THREE, kext_three('_nowhere'))))+ big = kext_three('_kernel_data')+ big[0].section('__DATA', '__bss', zerofill=0x10000)+ self.assertIn(f'{THREE}: no room for its __DATA (0x100d0 bytes) in __DATA',+ self.refused('--native', w.native(SPEC_THREE, big)))+ # what kextld finds before it links, too: in one line, with the kext+ odd = kext_three('_kernel_data')+ odd[0].section('__DATA', '__objc_const', bytes(8), 3)+ self.assertIn(f'{THREE}: three0.o: section __DATA,__objc_const has no place in a kext',+ self.refused('--native', w.native(SPEC_THREE, odd)))+ self.assertIn(f'{THREE}: _three_start defined twice (in three1.o and at __TEXT_EXEC,__text)',+ self.refused('--native', w.native(SPEC_THREE, kext_three('_kernel_data') * 2)))+ spec = w.native(SPEC_THREE, kext_three('_kernel_data'))+ other = bytearray(w.read('three0.o'))+ other[4:8] = struct.pack('<I', 0x01000007) # CPU_TYPE_X86_64+ w.write('three0.o', bytes(other))+ self.assertIn(f'{THREE}: three0.o: not an arm64', self.refused('--native', spec))+ packed = kext_three('_kernel_data')+ packed[0].pointer(packed[0].section('__DATA', '__const', bytes(16), 0), 1, 0)+ self.assertIn('three0.o: pointer at __const+0x1 not at a multiple of 4',+ self.refused('--native', w.native(SPEC_THREE, packed)))+ w.kernel('kernel.odd', more=[('__ODD', 0x38000)])+ self.assertIn('kernel segment __ODD has no place in the collection', self.refused(kernel='kernel.odd'))+ w.kernel('kernel.over', more=[('__KLD', 0x40000)]) # code where the prelink info is+ self.assertIn('overlap', self.refused(kernel='kernel.over'))+++class Kept(unittest.TestCase):+ """A collection with three kexts, linked again for a kernel that is SLIDE higher and has _kernel_data elsewhere in+ its data: two kexts kept (one named, one because the named one's OSBundleLibraries has it), the third not."""++ @classmethod+ def setUpClass(cls):+ cls.w = w = Workdir(cls.addClassCleanup)+ w.template()+ cls.ksyms, _ = w.kernel()+ status, out, err = w.link('--native', w.native(SPEC_ONE, kext_one()), w.native(SPEC_TWO, kext_two()),+ w.native(SPEC_THREE, kext_three('_kernel_data')), output='first.kc')+ assert status == 0, err+ cls.ksyms2, cls.kpointers2 = w.kernel('kernel2', base=BASE + SLIDE, data_at=0x40)+ status, cls.log, err = w.link('--keep', TWO, base='first.kc', kernel='kernel2', output='second.kc')+ assert status == 0, err+ cls.first, cls.second = w.collection('first.kc'), w.collection('second.kc')++ def test_what_is_kept(self):+ self.assertIn(f"keeping 2 kexts: ['{ONE}', '{TWO}']", self.log)+ self.assertIn('kept kexts: 10 chained pointers (3 into the kernel, by symbol)', self.log)+ self.assertEqual(list(self.second.entries), ['com.apple.kernel', ONE, TWO])+ self.assertEqual(list(self.second.kexts), list(KPI.values()) + [ONE, TWO]) # the pseudo-extensions stay+ self.assertEqual(self.second.natives, {})++ def test_the_kexts_moved_with_the_kernel(self):+ first, second = self.first, self.second+ self.assertEqual(second.base, BASE + SLIDE)+ for name in (ONE, TWO):+ self.assertEqual(second.entries[name], (first.entries[name][0] + SLIDE, first.entries[name][1]))+ (off, was), (_, now) = first.entry(name), second.entry(name)+ self.assertEqual(list(now), list(was))+ for seg, s in was.items():+ if seg == '__LINKEDIT':+ continue+ moved = dict(s, vmaddr=s['vmaddr'] + SLIDE, sections=[dict(x, addr=x['addr'] + SLIDE)+ for x in s['sections']])+ self.assertEqual(now[seg], moved, f'{name} {seg}')+ le = now['__LINKEDIT']+ self.assertEqual((le['vmaddr'] - second.base, le['fileoff'] + le['filesize']),+ (le['fileoff'], len(second.buf)), name)+ # the rest of its header is as it was+ cmds = zip(mkmacho.commands(first.buf, off), mkmacho.commands(second.buf, off))+ self.assertTrue(all(a == b for a, b in cmds if a[0] != LC_SEGMENT_64), name)++ def test_their_bytes_are_as_they_were(self):+ """But for the pointers, the load commands and the address in the kmod_info."""+ first, second = self.first, self.second+ for name in (ONE, TWO):+ kmod = first.kexts[name]['_PrelinkKmodInfo'] + (1 << 64) - BASE+ for a, b in spans(first, name):+ was, now = bytearray(first.buf[a:b]), bytearray(second.buf[a:b])+ for buf, kc in ((was, first), (now, second)):+ for off in kc.pointers:+ if a <= off < b:+ buf[off - a:off - a + 8] = bytes(8)+ if a == kc.entries[name][1]:+ buf[0:0x1000] = bytes(0x1000)+ if a <= kmod < b:+ buf[kmod - a + 156:kmod - a + 164] = bytes(8)+ self.assertEqual(now, was, f'{name} at {a:#x}')+ self.assertEqual(struct.unpack_from('<Q', second.buf, kmod + 156)[0],+ struct.unpack_from('<Q', first.buf, kmod + 156)[0] + SLIDE)++ def test_their_pointers(self):+ """Into a kept kext: moved with it. Into the kernel: to the symbol of that name in the new one."""+ first, second = self.first, self.second+ old_kernel = {a: n for n, a in self.ksyms.items()}+ kept = [span for name in (ONE, TWO) for span in spans(first, name)]+ expected = {va - second.base: (target, sign) for va, target, sign in self.kpointers2}+ for off, p in first.pointers.items():+ if not any(a <= off < b for a, b in kept):+ continue # the old kernel's, the kext's that is not kept+ target = BASE + p.target+ expected[off] = (self.ksyms2[old_kernel[target]] if target in old_kernel else target + SLIDE, p.signing())+ self.assertEqual({off: (second.base + p.target, p.signing()) for off, p in second.pointers.items()}, expected)+ self.assertEqual(len(expected), 14)+ # by symbol, not by the distance the kernel moved: _kernel_data is somewhere else in the new kernel's data+ self.assertEqual(second.pointer(first.natives['_pointers'] + SLIDE), (self.ksyms2['_kernel_data'], None))+ self.assertNotEqual(self.ksyms2['_kernel_data'], self.ksyms['_kernel_data'] + SLIDE)+ # one that is not exported, too+ self.assertEqual(second.pointer(first.natives['_table'] + SLIDE + 8), (self.ksyms2['_kernel_private'], None))++ def test_their_entries_in_the_prelink_info(self):+ for name in (ONE, TWO):+ was, now = self.first.kexts[name], self.second.kexts[name]+ addresses = ('_PrelinkExecutableLoadAddr', '_PrelinkExecutableSourceAddr', '_PrelinkKmodInfo')+ moved = dict(was, **{k: was[k] + SLIDE for k in addresses})+ self.assertEqual(now, moved, name)+ for ident in KPI.values():+ self.assertEqual(self.second.kexts[ident], self.first.kexts[ident])++ def relink(self, *args):+ return self.w.link('--keep', TWO, *args, base='first.kc', kernel='kernel2', output='again.kc')++ def test_rebind(self):+ """--rebind ADDRESS=SYMBOL: the pointer at that address of the old collection, to another symbol, signed as+ it was."""+ plain, signed = self.first.natives['_table'] + 8, self.first.natives['_pointers'] + 8+ self.assertEqual(self.first.pointer(signed)[1], (KEY_IA, 0x1111, 1))+ status, out, err = self.relink('--rebind', f'{plain:#x}=_kernel_func', f'{signed:#x}=_kernel_start')+ self.assertEqual((status, err), (0, ''))+ again = self.w.collection('again.kc')+ self.assertEqual(again.pointer(plain + SLIDE), (self.ksyms2['_kernel_func'], None))+ self.assertEqual(again.pointer(signed + SLIDE), (self.ksyms2['_kernel_start'], (KEY_IA, 0x1111, 1)))+ rest = {off for off in again.pointers if off not in (plain - BASE, signed - BASE)}+ self.assertEqual({off: (again.pointers[off].target, again.pointers[off].signing()) for off in rest},+ {off: (p.target, p.signing()) for off, p in self.second.pointers.items() if off in rest})+ self.assertEqual(len(rest), 12)+ status, out, err = self.relink('--rebind', f'{plain:#x}=_nowhere')+ self.assertEqual((status, err), (1, f'kclink: --rebind {plain:#x}=_nowhere: no _nowhere in the kernel\n'))+ status, out, err = self.relink('--rebind', f'{plain + 4:#x}=_kernel_func')+ self.assertEqual((status, err), (1, f'kclink: --rebind: no pointer of a kept kext at {plain + 4:#x}\n'))++ def test_a_native_kext_beside_the_kept_ones(self):+ """In room no kept kext has, and with a key for a kept kext's personality (patch_personalities)."""+ spec = dict(SPEC_THREE, patch_personalities={ONE: {'One': {'IOProbeScore': 5000}}})+ status, out, err = self.relink('--native', self.w.native(spec, kext_three('_kernel_data')))+ self.assertEqual((status, err), (0, ''))+ again = self.w.collection('again.kc')+ self.assertEqual(list(again.entries), ['com.apple.kernel', ONE, TWO, THREE])+ taken = sorted(span + (name,) for name in again.entries for span in spans(again, name))+ for (a1, b1, n1), (a2, b2, n2) in zip(taken, taken[1:]):+ self.assertLessEqual(b1, a2, f'{n1} and {n2} overlap')+ self.assertEqual(again.pointer(again.natives['_three_pointer']), (self.ksyms2['_kernel_data'], None))+ self.assertEqual(again.kexts[ONE]['IOKitPersonalities'],+ {'One': dict(SPEC_ONE['personalities']['One'], IOProbeScore=5000)})+ self.assertEqual(again.kexts[TWO], self.second.kexts[TWO])+ for patch, why in (({ONE: {'Other': {'x': 1}}}, f'patch_personalities: {ONE} has no personality Other'),+ ({THREE + '.not': {'One': {}}}, f'patch_personalities: {THREE}.not not kept')):+ spec = dict(SPEC_THREE, patch_personalities=patch)+ status, out, err = self.relink('--native', self.w.native(spec, kext_three('_kernel_data')))+ self.assertEqual((status, err), (1, f'kclink: {why}\n'))++ def test_a_kept_kext_that_points_into_one_that_is_not(self):+ w = self.w+ status, out, err = w.link('--native', w.native(SPEC_ONE, kext_one()), w.native(SPEC_THREE, kext_three()),+ output='pointing.kc')+ self.assertEqual((status, err), (0, ''))+ status, out, err = w.link('--keep', THREE, base='pointing.kc', kernel='kernel2', output='again.kc')+ self.assertEqual(status, 1)+ self.assertIn(f'{THREE}: pointers to nothing in the output', err)+ self.assertTrue(err.endswith('kclink: kept kexts point at what is not kept\n'), err)+++class TheSameTwice(unittest.TestCase):+ def build(self, seed):+ """A template, a collection with two kexts, and that linked again for another kernel; with python's hashes+ (the order of its sets) seeded as said."""+ w = Workdir(self.addCleanup, env={'PYTHONHASHSEED': seed})+ template = w.template()+ w.kernel()+ status, out, err = w.link('--native', w.native(SPEC_ONE, kext_one()), w.native(SPEC_TWO, kext_two()))+ self.assertEqual((status, err), (0, ''))+ w.kernel('kernel2', base=BASE + SLIDE, data_at=0x40)+ status, out, err = w.link('--keep', TWO, '--native', w.native(SPEC_THREE, kext_three('_kernel_data')),+ base='out.kc', kernel='kernel2', output='again.kc')+ self.assertEqual((status, err), (0, ''))+ return template, w.read('out.kc'), w.read('out.natives.json'), w.read('again.kc'), w.read('again.natives.json')++ def test_byte_for_byte(self):+ first = self.build('1')+ for seed in ('1', '2', '4711'):+ again = self.build(seed)+ for what, a, b in zip(('the template', 'the collection', 'its symbols', 'the collection linked again',+ 'its symbols'), first, again):+ self.assertEqual(a, b, f'{what}, hash seed {seed}')+ self.assertEqual(len(first[1]) % PAGE, 0)+ self.assertEqual(sorted(json.loads(first[4])), ['_three_pointer', '_three_start', '_three_stop'])+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_kextld_definitions.py b/tests/kclink/test_kextld_definitions.pynew file mode 100755index 0000000..fe7c27a--- /dev/null+++ b/tests/kclink/test_kextld_definitions.py@@ -0,0 +1,146 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Which definition a kext gets of a symbol that several of its objects define, and which objects it takes at all+(scripts/kclink/kextld.py: Kext.layout(), Obj). The objects here are symbol tables only, so nothing is compiled:++ python3 tests/kclink/test_kextld_definitions.py+"""+import itertools+import os+import sys+import tempfile+import unittest++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'scripts', 'kclink'))+import kextld # noqa: E402+from macho import HEADER, MH_MAGIC_64, MH_OBJECT, CPU_TYPE_ARM64, N_EXT, N_SECT, N_UNDF # noqa: E402++WEAK = 0x80 # N_WEAK_DEF, in n_desc+++class SymbolsOnly:+ """What layout() reads of an object when it has no sections: its path and its symbol table."""+ sects = ()++ def __init__(self, index, syms):+ self.path, self.syms, self.where = f'obj{index}.o', syms, {}+++def layout(*tables):+ """Lays out a kext of objects with these symbol tables. A defined symbol's place is its value in one section."""+ kx = kextld.Kext({}, [])+ kx.objs = [SymbolsOnly(i, t) for i, t in enumerate(tables)]+ const = kx.section('__TEXT', '__const')+ kx.place_of = lambda o, sect, value: (const, value)+ kx.layout()+ return kx+++def defined(name, value, weak=False):+ return (name, N_SECT | N_EXT, 1, WEAK if weak else 0, value)+++def common(name, size, log2align=2):+ return (name, N_UNDF | N_EXT, 0, log2align << 8, size)+++def where(kx, name):+ out, off = kx.globals[name]+ return out.name, off+++class Definitions(unittest.TestCase):+ def place(self, *entries):+ """entries: ('W' or 'S', place), an object each. The place '_s' ends up at."""+ return where(layout(*[[defined('_s', p, weak=k == 'W')] for k, p in entries]), '_s')[1]++ def test_strong_over_weak_in_either_order(self):+ self.assertEqual(self.place(('W', 0), ('S', 8)), 8)+ self.assertEqual(self.place(('S', 8), ('W', 0)), 8)++ def test_first_of_several_weak_ones(self):+ self.assertEqual(self.place(('W', 8), ('W', 0), ('W', 16)), 8)++ def test_two_strong_ones_are_refused(self):+ with self.assertRaises(kextld.LinkError):+ self.place(('S', 0), ('S', 8))++ def test_weak_and_strong_at_one_place_then_strong_elsewhere(self):+ # one object's symbol at the end of its part of a section and the next object's at the start of its part+ # have the same place: the strong one of the two makes the symbol strong, in either order+ for first, second in (('W', 'S'), ('S', 'W')):+ with self.assertRaises(kextld.LinkError, msg=f'{first}@0 {second}@0 S@8'):+ self.place((first, 0), (second, 0), ('S', 8))++ def test_weak_and_strong_at_one_place_then_weak_elsewhere(self):+ for first, second in (('W', 'S'), ('S', 'W')):+ self.assertEqual(self.place((first, 0), (second, 0), ('W', 8)), 0)++ def test_every_short_sequence_against_the_rule(self):+ """Entries at one place are one definition, strong if any of them is; strong ones at two places are an error;+ otherwise the strong one's place; otherwise the first weak one's."""+ def rule(seq):+ strong = {p for k, p in seq if k == 'S'}+ return 'error' if len(strong) > 1 else strong.pop() if strong else seq[0][1]++ def linked(seq):+ try:+ return self.place(*seq)+ except kextld.LinkError:+ return 'error'++ entries = [(k, p) for k in 'WS' for p in (0, 8, 16)]+ wrong = [seq for n in range(1, 6) for seq in itertools.product(entries, repeat=n) if linked(seq) != rule(seq)]+ self.assertEqual(wrong[:3], [], f'{len(wrong)} sequences differ from the rule')+++class Commons(unittest.TestCase):+ def test_a_common_symbol_alone_gets_common_storage(self):+ kx = layout([common('_c', 4)])+ self.assertEqual(where(kx, '_c')[0], '__common')+ self.assertEqual(kx.out[('__DATA', '__common')].size, 4)++ def test_the_largest_of_several_commons(self):+ kx = layout([common('_c', 8, 0)], [common('_c', 32, 3)])+ self.assertEqual(kx.out[('__DATA', '__common')].size, 32)++ def test_a_definition_is_the_symbol_in_either_order(self):+ for weak in (False, True):+ for tables in ([[common('_c', 4)], [defined('_c', 8, weak)]], [[defined('_c', 8, weak)], [common('_c', 4)]]):+ kx = layout(*tables)+ self.assertEqual(where(kx, '_c'), ('__const', 8), f'weak={weak}')+ self.assertNotIn(('__DATA', '__common'), kx.out) # and no storage is set aside for it++ def test_other_commons_keep_their_storage_beside_a_defined_one(self):+ kx = layout([common('_c', 4), common('_d', 16, 3)], [defined('_c', 8)])+ self.assertEqual(where(kx, '_d'), ('__common', 0))+ self.assertEqual(kx.out[('__DATA', '__common')].size, 16)+++class Objects(unittest.TestCase):+ def obj(self, cputype, cpusubtype, filetype=MH_OBJECT):+ f = tempfile.NamedTemporaryFile(suffix='.o', delete=False)+ self.addCleanup(os.unlink, f.name)+ f.write(HEADER.pack(MH_MAGIC_64, cputype, cpusubtype, filetype, 0, 0, 0, 0))+ f.close()+ return f.name++ def test_arm64e_objects_are_taken(self):+ for subtype in (2, 0x80000002, 0xc0000002): # plain, a user ABI version, the kernel's (clang -mkernel)+ kextld.Obj(self.obj(CPU_TYPE_ARM64, subtype))++ def test_arm64_objects_are_refused(self):+ # the kext is written as arm64e whatever went in: an arm64 object's pointers would be in it unsigned+ for subtype in (0, 1): # CPU_SUBTYPE_ARM64_ALL, _V8+ with self.assertRaises(kextld.LinkError, msg=hex(subtype)):+ kextld.Obj(self.obj(CPU_TYPE_ARM64, subtype))++ def test_other_files_are_refused(self):+ with self.assertRaises(kextld.LinkError):+ kextld.Obj(self.obj(0x01000007, 3)) # x86_64+ with self.assertRaises(kextld.LinkError):+ kextld.Obj(self.obj(CPU_TYPE_ARM64, 0xc0000002, filetype=2)) # an executable, not an object+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_kextld_layout.py b/tests/kclink/test_kextld_layout.pynew file mode 100755index 0000000..96359aa--- /dev/null+++ b/tests/kclink/test_kextld_layout.py@@ -0,0 +1,266 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Where scripts/kclink/kextld.py puts what the objects of a kext bring: each section into the kext's segments, aligned,+in the objects' order, nothing over anything else, zero-fill last; the kmod_info in front of the data; the room for the+Mach-O header; and what the kext's header and its entry in the prelink info then say. Objects built here (mkmacho.py):++ python3 tests/kclink/test_kextld_layout.py+"""+import os+import random+import shutil+import struct+import sys+import tempfile+import unittest+import uuid++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import mkmacho # noqa: E402+from mkmacho import (HEADER_VA, KEXT_VA, KEY_IA, LC_SEGMENT_64, LC_SYMTAB, LC_UUID, MH_KEXT_BUNDLE, OUTSIDE, # noqa: E402+ RET, S_ATTR_DEBUG, S_CSTRING_LITERALS, S_ZEROFILL, TEXT_FLAGS, Object, movz)+import kextld # noqa: E402++# where a section of an object goes in the kext (kextld's PLACEMENT, said again: a change there is meant to show here)+GOES_TO = {+ ('__TEXT', '__text'): ('__TEXT_EXEC', '__text'), ('__TEXT', '__cstring'): ('__TEXT', '__cstring'),+ ('__TEXT', '__const'): ('__TEXT', '__const'), ('__TEXT', '__literal8'): ('__TEXT', '__literal8'),+ ('__TEXT', '__literal16'): ('__TEXT', '__literal16'), ('__DATA', '__const'): ('__DATA_CONST', '__const'),+ ('__DATA', '__mod_init_func'): ('__DATA_CONST', '__mod_init_func'), ('__DATA', '__data'): ('__DATA', '__data'),+ ('__DATA', '__bss'): ('__DATA', '__bss'), ('__DATA', '__common'): ('__DATA', '__common'),+}+ZEROFILL = {'__bss', '__common'}+KMOD_INFO = 196 # sizeof(kmod_info_t), <mach/kmod.h> (packed to 4 bytes)+++class Case(unittest.TestCase):+ def setUp(self):+ self.dir = tempfile.mkdtemp()+ self.addCleanup(shutil.rmtree, self.dir)++ def link(self, *objects, **how):+ return mkmacho.link([o.write(self.dir, f'o{i}.o') for i, o in enumerate(objects)], **how)++ def refused(self, *objects):+ with self.assertRaises(kextld.LinkError) as e:+ self.link(*objects)+ return str(e.exception)+++def mixed(seed, objects=3):+ """Objects with sections of every size and alignment (1 byte to a 16K page), each piece its own byte pattern and a+ symbol. Returns (objects, {symbol: (section it goes to, log2 alignment, its bytes or its zero-filled size)})."""+ rnd, out, pieces = random.Random(seed), [], {}+ for i in range(objects):+ o = Object()+ for key in rnd.sample(sorted(GOES_TO), rnd.randint(4, len(GOES_TO))):+ al, size = rnd.choice((0, 0, 1, 2, 3, 4, 4, 6, 12, 14)), rnd.choice((1, 3, 8, 16, 100, 333, 4096))+ name = f'_piece{len(pieces)}'+ if key[1] in ZEROFILL:+ sect, content = o.section(*key, align_=al, zerofill=size), size+ else:+ content = bytes((len(pieces) * 7 + j) % 251 + 1 for j in range(size))+ flags = {'__text': TEXT_FLAGS, '__cstring': S_CSTRING_LITERALS}.get(key[1], 0)+ sect = o.section(*key, content, al, flags)+ o.define(name, sect)+ pieces[name] = (GOES_TO[key], al, content)+ out.append(o)+ return out, pieces+++class Sections(Case):+ def test_every_piece_aligned_whole_and_apart(self):+ for seed in range(12):+ objects, pieces = mixed(seed)+ k = self.link(*objects)+ spans = []+ for name, (where, al, content) in pieces.items():+ at, size = k.symbols[name], content if isinstance(content, int) else len(content)+ self.assertEqual(at % (1 << al), 0, f'seed {seed}: {name} at {at:#x}, alignment 2^{al}')+ self.assertEqual(k.bytes(at, size), bytes(size) if isinstance(content, int) else content, name)+ start, length = k.section(*where)+ self.assertTrue(start <= at and at + size <= start + length, f'seed {seed}: {name} in {where}')+ spans.append((at, at + size, name))+ spans.sort()+ for (a1, b1, n1), (a2, b2, n2) in zip(spans, spans[1:]):+ self.assertLessEqual(b1, a2, f'seed {seed}: {n1} and {n2} overlap')+ # in one section: in the order of the objects (the pieces are numbered in it)+ for where in set(w for w, al, content in pieces.values()):+ inside = [k.symbols[n] for n, (w, al, content) in pieces.items() if w == where]+ self.assertEqual(inside, sorted(inside), f'seed {seed}: {where}')++ def test_segments_are_as_aligned_as_what_is_in_them(self):+ for seed in range(12):+ objects, pieces = mixed(seed)+ sizes = mkmacho.kext([o.write(self.dir, f'o{i}.o') for i, o in enumerate(objects)]).layout()+ for seg, (size, al) in sizes.items():+ most = max([1 << a for (s, n), a, c in pieces.values() if s == seg] + [16])+ self.assertEqual(al, most, f'seed {seed}: {seg}')+ self.assertEqual(size % 16, 0, seg)++ def test_sections_of_a_segment_follow_each_other_zero_fill_last(self):+ for seed in range(12):+ objects, pieces = mixed(seed)+ k = self.link(*objects)+ for seg in k.segments:+ sects = sorted((s.addr, s.addr + s.size, s.name) for s in k.kx.out.values() if s.seg == seg)+ for (a1, b1, n1), (a2, b2, n2) in zip(sects, sects[1:]):+ self.assertLessEqual(b1, a2, f'seed {seed}: {seg},{n1} and {n2} overlap')+ self.assertLessEqual(sects[-1][1], k.addrs[seg] + len(k.segments[seg]))+ names = [n for a, b, n in sects]+ first = min([i for i, n in enumerate(names) if n in ZEROFILL] + [len(names)])+ self.assertTrue(all(n in ZEROFILL for n in names[first:]), f'seed {seed}: {seg}: {names}')++ def test_the_kmod_info_is_first_in_the_data(self):+ o = Object()+ o.define('_mine', o.section('__DATA', '__data', b'\xaa' * 24, 5))+ k = self.link(o)+ data, size = k.section('__DATA', '__data')+ self.assertEqual(data, KEXT_VA['__DATA'])+ self.assertEqual(k.symbols['_mine'], data + 224) # after 196 bytes, at the next multiple of 32+ self.assertEqual(size, 224 + 24)+ info = k.bytes(data, KMOD_INFO)+ nxt, version, ident, name, vers, refs, reflist, address, length, hdr_size, start, stop = \+ struct.unpack('<QIi64s64siQQQQQQ', info)+ self.assertEqual((nxt, version, ident, refs, reflist, hdr_size), (0, 1, -1, -1, 0, 0))+ self.assertEqual((name.rstrip(b'\0'), vers.rstrip(b'\0')), (b'org.example.kext.test', b'1.2.3'))+ self.assertEqual((address, length), (KEXT_VA['__TEXT'], len(k.segments['__TEXT'])))+ # start and stop: signed as XNU calls them, the IA key and kmod_start_func_t's type discriminator+ self.assertEqual((start, stop), (0, 0))+ for off, name in ((180, '_test_start'), (188, '_test_stop')):+ f = k.fixups[data + off]+ self.assertEqual((f.target, f.key, f.div, f.addr_div), (OUTSIDE[name], KEY_IA, 0xe4fe, 0))++ def test_start_and_stop_of_the_kext_itself(self):+ o = Object()+ t = o.text(movz(0, 0), RET, movz(0, 0), RET)+ o.define('_my_start', t)+ o.define('_my_stop', t, 8, private=True)+ k = self.link(o, spec={'start': '_my_start', 'stop': '_my_stop'})+ data = k.section('__DATA', '__data')[0]+ self.assertEqual(k.fixups[data + 180].target, KEXT_VA['__TEXT_EXEC'])+ self.assertEqual(k.fixups[data + 188].target, KEXT_VA['__TEXT_EXEC'] + 8)+ with self.assertRaises(kextld.LinkError) as e:+ self.link(o, spec={'start': '_my_start', 'stop': '_no_such_stop'})+ self.assertIn('unresolved symbols: _no_such_stop', str(e.exception))++ def test_room_for_the_header_in_front_of_text(self):+ o = Object()+ o.define('_s', o.section('__TEXT', '__cstring', b'first\0', 0, S_CSTRING_LITERALS))+ k = self.link(o)+ self.assertEqual(k.symbols['_s'], KEXT_VA['__TEXT'] + 0x1000)+ self.assertEqual(k.bytes(KEXT_VA['__TEXT'], 0x1000), bytes(0x1000)) # (the header is written by kclink)+ self.assertEqual(len(k.segments['__TEXT']), 0x1010)++ def test_a_kext_of_nothing(self):+ k = self.link()+ self.assertEqual({seg: len(b) for seg, b in k.segments.items()}, {'__TEXT': 0x1000, '__DATA': 208})+ self.assertEqual(k.section('__DATA', '__data'), (KEXT_VA['__DATA'], KMOD_INFO))+ self.assertEqual(sorted(k.fixups), [KEXT_VA['__DATA'] + 180, KEXT_VA['__DATA'] + 188])++ def test_a_section_with_no_place_is_refused(self):+ for key in (('__DATA', '__objc_const'), ('__TEXT', '__gcc_except_tab'), ('__DATA', '__thread_vars')):+ o = Object()+ o.section(*key, bytes(8), 3)+ self.assertIn(f'section {key[0]},{key[1]} has no place in a kext', self.refused(o))++ def test_what_a_kext_does_not_get(self):+ """Unwind tables, debug information and bitcode take no room, and their relocations are not looked at."""+ plain, with_more = Object(), Object()+ for o in (plain, with_more):+ o.define('_f', o.text(movz(0, 5), RET))+ for seg, name, flags in (('__LD', '__compact_unwind', S_ATTR_DEBUG), ('__TEXT', '__eh_frame', 0),+ ('__DWARF', '__debug_info', S_ATTR_DEBUG), ('__DWARF', '__apple_names', S_ATTR_DEBUG),+ ('__LLVM', '__bitcode', 0), ('__LLVM', '__cmdline', 0)):+ s = with_more.section(seg, name, bytes(64), 3, flags)+ with_more.reloc(s, 0, mkmacho.UNSIGNED, 1, length=3, extern=0)+ with_more.reloc(s, 8, mkmacho.SUBTRACTOR, 0, length=3)+ a, b = self.link(plain), self.link(with_more)+ self.assertEqual(a.segments, b.segments)+ self.assertEqual(sorted(a.fixups), sorted(b.fixups))+ self.assertEqual(sorted(s.name for s in b.kx.out.values()), ['__data', '__text'])+++class Header(Case):+ LINKEDIT = (HEADER_VA + 0x3e00000, 0x3e00000, 0x8000)++ def setUp(self):+ super().setUp()+ o = Object()+ o.define('_f', o.text(movz(0, 5), RET))+ o.define('_s', o.section('__TEXT', '__cstring', b'text\0', 0, S_CSTRING_LITERALS))+ o.define('_c', o.section('__DATA', '__const', bytes(24), 3))+ o.define('_d', o.section('__DATA', '__data', bytes(8), 3))+ o.define('_z', o.section('__DATA', '__bss', align_=6, zerofill=100))+ o.define('_k', o.section('__DATA', '__kalloc_type', bytes(16), 3))+ self.k = self.link(o)+ self.header = self.k.kx.header(self.LINKEDIT)++ def test_it_is_a_kext_of_a_collection(self):+ magic, cpu, sub, filetype, ncmds, size, flags, _ = struct.unpack_from('<8I', self.header)+ self.assertEqual((magic, cpu, sub & 0xffffff, filetype), (0xfeedfacf, 0x0100000c, 2, MH_KEXT_BUNDLE))+ self.assertTrue(flags & 0x80000000) # MH_DYLIB_IN_CACHE+ cmds = mkmacho.commands(self.header)+ self.assertEqual(len(self.header), 32 + size)+ self.assertEqual(sum(len(raw) for cmd, raw in cmds), size)+ self.assertLessEqual(len(self.header), 0x1000)+ self.assertEqual([cmd for cmd, raw in cmds], [LC_SEGMENT_64] * 5 + [LC_SYMTAB, LC_UUID])+ self.assertEqual(cmds[-1][1][8:], uuid.uuid5(uuid.NAMESPACE_URL, 'org.example.kext.test').bytes)+ self.assertEqual(struct.unpack_from('<4I', cmds[-2][1], 8), (self.LINKEDIT[1], 0, self.LINKEDIT[1], 0))++ def test_its_segments_are_where_they_were_placed(self):+ segs = mkmacho.segments(self.header)+ self.assertEqual([s['name'] for s in segs], ['__TEXT', '__TEXT_EXEC', '__DATA', '__DATA_CONST', '__LINKEDIT'])+ for s in segs[:4]:+ self.assertEqual(s['vmaddr'], KEXT_VA[s['name']])+ self.assertEqual(s['vmsize'], len(self.k.segments[s['name']]))+ self.assertEqual((s['fileoff'], s['filesize']), (s['vmaddr'] - HEADER_VA, s['vmsize']))+ self.assertEqual(s['initprot'], {'__TEXT': 1, '__TEXT_EXEC': 5, '__DATA': 3, '__DATA_CONST': 3}[s['name']])+ le = segs[4]+ self.assertEqual((le['vmaddr'], le['fileoff'], le['vmsize'], le['filesize'], le['sections']),+ (self.LINKEDIT[0], self.LINKEDIT[1], self.LINKEDIT[2], self.LINKEDIT[2], []))++ def test_its_sections(self):+ sects = {(s['segname'], s['sectname']): s for seg in mkmacho.segments(self.header) for s in seg['sections']}+ self.assertEqual(sorted(sects), [('__DATA', '__bss'), ('__DATA', '__data'), ('__DATA_CONST', '__const'),+ ('__DATA_CONST', '__kalloc_type'), ('__TEXT', '__cstring'),+ ('__TEXT_EXEC', '__text')])+ for (seg, name), s in sects.items():+ self.assertEqual((s['addr'], s['size']), self.k.section(seg, name), name)+ self.assertEqual(s['offset'], 0 if name == '__bss' else s['addr'] - HEADER_VA, name)+ for name, sym in (('__text', '_f'), ('__cstring', '_s'), ('__const', '_c'), ('__bss', '_z'),+ ('__kalloc_type', '_k')):+ s = next(s for (seg, n), s in sects.items() if n == name)+ self.assertEqual(s['addr'], self.k.symbols[sym], name)+ self.assertEqual(sects[('__TEXT_EXEC', '__text')]['flags'], TEXT_FLAGS)+ self.assertEqual(sects[('__TEXT', '__cstring')]['flags'], S_CSTRING_LITERALS)+ self.assertEqual(sects[('__DATA', '__bss')]['flags'], S_ZEROFILL)+ self.assertEqual((sects[('__DATA', '__bss')]['align'], sects[('__DATA', '__bss')]['size']), (6, 100))+ self.assertEqual(sects[('__DATA', '__data')]['size'], 208)++ def test_its_entry_in_the_prelink_info(self):+ kx = self.k.kx+ d = kx.plist(self.k.section('__DATA', '__data')[0])+ signed = KEXT_VA['__TEXT'] - (1 << 64) # as a kernel's prelink info has addresses+ self.assertEqual((d['_PrelinkExecutableLoadAddr'], d['_PrelinkExecutableSourceAddr']), (signed, signed))+ self.assertEqual(d['_PrelinkKmodInfo'], KEXT_VA['__DATA'] - (1 << 64))+ self.assertEqual(d['_PrelinkExecutableSize'], len(self.k.segments['__TEXT']))+ self.assertEqual((d['CFBundleIdentifier'], d['CFBundleExecutable'], d['CFBundleVersion']),+ ('org.example.kext.test', 'Test', '1.2.3'))+ self.assertEqual(d['OSBundleUUID'], uuid.uuid5(uuid.NAMESPACE_URL, 'org.example.kext.test').bytes)+ self.assertEqual((d['OSBundleLibraries'], d['IOKitPersonalities'], d['OSBundleCompatibleVersion']),+ ({}, {}, '1.0.0'))+ self.assertEqual(d['_PrelinkBundlePath'], '/System/Library/Extensions/Test.kext')++ def test_what_the_spec_says_goes_into_the_entry(self):+ kx = self.k.kx+ kx.spec.update(libraries={'com.apple.kpi.iokit': '8.0'}, personalities={'P': {'IOClass': 'Test'}},+ compatible_version='1.1', plist={'OSBundleRequired': 'Safe Boot', 'Extra': 1})+ d = kx.plist(0)+ self.assertEqual((d['OSBundleLibraries'], d['IOKitPersonalities'], d['OSBundleCompatibleVersion']),+ ({'com.apple.kpi.iokit': '8.0'}, {'P': {'IOClass': 'Test'}}, '1.1'))+ self.assertEqual((d['OSBundleRequired'], d['Extra']), ('Safe Boot', 1))+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_kextld_relocations.py b/tests/kclink/test_kextld_relocations.pynew file mode 100755index 0000000..06d5ee3--- /dev/null+++ b/tests/kclink/test_kextld_relocations.py@@ -0,0 +1,521 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Every relocation scripts/kclink/kextld.py resolves, checked in what it linked: the instruction's operand decoded,+or the pointer it hands to the collection's chained fixups (its target, key, diversity, address diversity).++The objects are built here, relocation by relocation (mkmacho.py), so the tests need python3 only. Where there is a+clang that makes arm64e objects, the same code is assembled too: the assembler must write what was built by hand, byte+for byte, and its object must link to the same result.++ python3 tests/kclink/test_kextld_relocations.py+"""+import os+import shutil+import struct+import sys+import tempfile+import unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import mkmacho # noqa: E402+from mkmacho import (AUTHENTICATED_POINTER, B, BL, BRANCH26, GOT_LOAD_PAGE21, GOT_LOAD_PAGEOFF12, # noqa: E402+ HEADER_VA, KEXT_VA, KEY_DA, KEY_DB, KEY_IA, KEY_IB, LOADS, NOP, PAGE21, PAGEOFF12, POINTER_TO_GOT,+ RET, TLVP_PAGE21, UNSIGNED, Object, add, adrp, adrp_page, branch_target, imm12, movz)+import kextld # noqa: E402++LDR_X1_X1 = 0xf9400021 # ldr x1, [x1]+OPERAND = {name: name.split()[0] + ' ' + (name.split()[1] + '2' if ' ' in name else 'pldl2keep') for name in LOADS}+# the same object as assembly: code() below builds it by hand. (With .subsections_via_symbols after it, as a compiler+# ends its output: without, the assembler resolves a branch within the section itself and writes no relocation.)+SOURCE = ''' .section __TEXT,__text,regular,pure_instructions+ .globl _code+ .p2align 2+_code:+ bl _near+ b _far+ bl _outside+ bl _near+4+ adrp x1, _datum@PAGE+ add x1, x1, _datum@PAGEOFF+ adrp x1, _datum+0x12340@PAGE+ add x1, x1, _datum+0x12340@PAGEOFF+ adrp x1, _outside_data@GOTPAGE+ ldr x1, [x1, _outside_data@GOTPAGEOFF]+ adrp x1, _datum@GOTPAGE+ ldr x1, [x1, _datum@GOTPAGEOFF]+''' + ''.join(f' {OPERAND[name]}, [x1, _datum@PAGEOFF]\n' for name in LOADS) + ''' .globl _near+_near:+ mov w0, #1+ ret+ .section __DATA,__data+ .globl _datum+ .p2align 4+_datum:+ .quad 0x1111111111111111+ .quad 0x2222222222222222+ .globl _table+_table:+ .quad _code+ .quad _code+20+ .quad _table-8+ .quad _outside+'''+SIGNED = ''' .quad _code@AUTH(ia,0x1234)+ .quad _code+8@AUTH(ib,0xffff,addr)+ .quad _table@AUTH(da,0)+ .quad _outside-4@AUTH(db,0xbeef,addr)+'''+LOADS_AT, NEAR_AT = 48, 48 + 4 * len(LOADS) # offsets in _code+++def code(signed=True):+ """The object SOURCE (+ SIGNED) describes, built by hand."""+ o = Object()+ insns = [BL, B, BL, BL, adrp(1), add(1, 1), adrp(1), add(1, 1), adrp(1), LDR_X1_X1, adrp(1), LDR_X1_X1]+ insns += [insn for insn, scale in LOADS.values()] + [movz(0, 1), RET]+ t = o.text(*insns)+ d = o.section('__DATA', '__data', struct.pack('<2Q', 0x1111111111111111, 0x2222222222222222) ++ bytes(64 if signed else 32), 4)+ s = {'_code': o.define('_code', t), '_near': o.define('_near', t, NEAR_AT), '_datum': o.define('_datum', d),+ '_table': o.define('_table', d, 16)}+ for name in ('_far', '_outside', '_outside_data'):+ s[name] = o.undefined(name)+ o.reloc(t, 0, BRANCH26, s['_near'], pcrel=1)+ o.reloc(t, 4, BRANCH26, s['_far'], pcrel=1)+ o.reloc(t, 8, BRANCH26, s['_outside'], pcrel=1)+ o.reloc(t, 12, BRANCH26, s['_near'], pcrel=1, addend=4)+ o.reloc(t, 16, PAGE21, s['_datum'], pcrel=1)+ o.reloc(t, 20, PAGEOFF12, s['_datum'])+ o.reloc(t, 24, PAGE21, s['_datum'], pcrel=1, addend=0x12340)+ o.reloc(t, 28, PAGEOFF12, s['_datum'], addend=0x12340)+ o.reloc(t, 32, GOT_LOAD_PAGE21, s['_outside_data'], pcrel=1)+ o.reloc(t, 36, GOT_LOAD_PAGEOFF12, s['_outside_data'])+ o.reloc(t, 40, GOT_LOAD_PAGE21, s['_datum'], pcrel=1)+ o.reloc(t, 44, GOT_LOAD_PAGEOFF12, s['_datum'])+ for i in range(len(LOADS)):+ o.reloc(t, LOADS_AT + 4 * i, PAGEOFF12, s['_datum'])+ o.pointer(d, 16, s['_code'])+ o.pointer(d, 24, s['_code'], 20)+ o.pointer(d, 32, s['_table'], -8)+ o.pointer(d, 40, s['_outside'])+ if signed:+ o.auth_pointer(d, 48, s['_code'], KEY_IA, 0x1234)+ o.auth_pointer(d, 56, s['_code'], KEY_IB, 0xffff, 1, addend=8)+ o.auth_pointer(d, 64, s['_table'], KEY_DA)+ o.auth_pointer(d, 72, s['_outside'], KEY_DB, 0xbeef, 1, addend=-4)+ return o+++def far():+ """A second object: _far, the function _code branches to."""+ o = Object()+ o.define('_far', o.text(movz(0, 2), RET))+ return o+++class Case(unittest.TestCase):+ def setUp(self):+ self.dir = tempfile.mkdtemp()+ self.addCleanup(shutil.rmtree, self.dir)++ def link(self, *objects, **how):+ """Links objects (an Object, or the path of a compiled one) into a kext."""+ paths = [o if isinstance(o, str) else o.write(self.dir, f'o{i}.o') for i, o in enumerate(objects)]+ return mkmacho.link(paths, **how)++ def refused(self, *objects, **how):+ """The message kextld refuses the link with."""+ with self.assertRaises(kextld.LinkError) as e:+ self.link(*objects, **how)+ return str(e.exception)++ def pointer(self, k, va):+ """(target, signing) of the pointer kextld hands back for the 8 bytes at va, which it leaves zero."""+ self.assertEqual(k.u64(va), 0, f'the bytes of the pointer at {va:#x}')+ f = k.fixups[va]+ return f.target, None if f.key is None else (f.key, f.div, f.addr_div)+++OUTSIDE = {'_outside': KEXT_VA['__TEXT_EXEC'] - 0x400000, '_outside_data': HEADER_VA + 0x3800000}+++class Built(Case):+ """The object of SOURCE as code() builds it, linked with far(): every relocation of it."""+ signed = True++ def object(self):+ return code(self.signed)++ def setUp(self):+ super().setUp()+ self.k = self.link(self.object(), far(), outside=OUTSIDE)+ self.code, self.datum = self.k.symbols['_code'], self.k.symbols['_datum']+ self.table = self.k.symbols['_table']++ def insn(self, off):+ return self.k.u32(self.code + off)++ def test_the_symbols_are_where_their_content_is(self):+ k = self.k+ self.assertEqual(k.u32(k.symbols['_near']), movz(0, 1))+ self.assertEqual(k.u32(k.symbols['_far']), movz(0, 2))+ self.assertEqual(k.u64(self.datum), 0x1111111111111111)+ self.assertEqual(self.table, self.datum + 16)+ self.assertEqual(self.code, k.section('__TEXT_EXEC', '__text')[0])+ self.assertEqual(self.datum % 16, 0)++ def test_branch26(self):+ k = self.k+ for off, op, target in ((0, BL, k.symbols['_near']), (4, B, k.symbols['_far']), (8, BL, OUTSIDE['_outside']),+ (12, BL, k.symbols['_near'] + 4)):+ self.assertEqual(self.insn(off) & 0xfc000000, op, f'the instruction at {off}')+ self.assertEqual(branch_target(self.insn(off), self.code + off), target, f'the branch at {off}')+ self.assertLess(OUTSIDE['_outside'], self.code) # (one of them goes backward)++ def test_page21_and_pageoff12_of_an_add(self):+ for off, target in ((16, self.datum), (24, self.datum + 0x12340)):+ self.assertEqual(self.insn(off) & 0x9f00001f, adrp(1))+ self.assertEqual(adrp_page(self.insn(off), self.code + off), target & ~0xfff)+ self.assertEqual(self.insn(off + 4) & ~(0xfff << 10), add(1, 1))+ self.assertEqual(imm12(self.insn(off + 4)), target & 0xfff)+ self.assertNotEqual(self.datum >> 12, (self.datum + 0x12340) >> 12) # (the addend changes the page)+ self.assertNotEqual(self.datum & 0xfff, 0)++ def test_pageoff12_of_every_load_and_store(self):+ """The 12 bits count in units of what the instruction moves: 1, 2, 4, 8 or 16 bytes."""+ for i, (name, (insn, scale)) in enumerate(LOADS.items()):+ linked = self.insn(LOADS_AT + 4 * i)+ self.assertEqual(linked & ~(0xfff << 10), insn, name)+ self.assertEqual(imm12(linked) << scale, self.datum & 0xfff, name)++ def test_got_load(self):+ k = self.k+ got, size = k.section('__DATA_CONST', '__got')+ self.assertEqual((size, got % 8), (16, 0))+ slots = {}+ for off, name in ((32, '_outside_data'), (40, '_datum')):+ self.assertEqual(self.insn(off + 4) & ~(0xfff << 10), LDR_X1_X1)+ slot = adrp_page(self.insn(off), self.code + off) + (imm12(self.insn(off + 4)) << 3)+ self.assertTrue(got <= slot < got + size and slot % 8 == 0, name)+ slots[name] = slot+ self.assertNotEqual(slots['_outside_data'], slots['_datum'])+ self.assertEqual(self.pointer(k, slots['_outside_data']), (OUTSIDE['_outside_data'], None))+ self.assertEqual(self.pointer(k, slots['_datum']), (self.datum, None))++ def test_unsigned(self):+ k = self.k+ self.assertEqual(self.pointer(k, self.table), (self.code, None))+ self.assertEqual(self.pointer(k, self.table + 8), (self.code + 20, None))+ self.assertEqual(self.pointer(k, self.table + 16), (self.table - 8, None))+ self.assertEqual(self.pointer(k, self.table + 24), (OUTSIDE['_outside'], None))++ def test_authenticated_pointer(self):+ if not self.signed:+ self.skipTest('this compiler does not assemble @AUTH')+ k = self.k+ self.assertEqual(self.pointer(k, self.table + 32), (self.code, (KEY_IA, 0x1234, 0)))+ self.assertEqual(self.pointer(k, self.table + 40), (self.code + 8, (KEY_IB, 0xffff, 1)))+ self.assertEqual(self.pointer(k, self.table + 48), (self.table, (KEY_DA, 0, 0)))+ self.assertEqual(self.pointer(k, self.table + 56), (OUTSIDE['_outside'] - 4, (KEY_DB, 0xbeef, 1)))++ def test_no_other_pointers(self):+ k = self.k+ data = k.section('__DATA', '__data')[0]+ mine = {self.table + 8 * i for i in range(8 if self.signed else 4)}+ mine |= {k.section('__DATA_CONST', '__got')[0] + 8 * i for i in range(2)}+ mine |= {data + kextld.KMOD_START, data + kextld.KMOD_STOP}+ self.assertEqual(set(k.fixups), mine)+++class Assembled(Built):+ """The same, of what clang assembles from SOURCE: its object is what code() builds, and links the same."""++ def object(self):+ cc, why = mkmacho.compiler('auth')+ type(self).signed = cc is not None+ return mkmacho.compile(self, SOURCE + (SIGNED if self.signed else '') + '.subsections_via_symbols\n',+ 'auth' if self.signed else 'asm')++ def test_the_assembler_writes_what_was_built_by_hand(self):+ with open(self.object(), 'rb') as f:+ assembled = mkmacho.describe(f.read())+ built = mkmacho.describe(code(self.signed).build())+ self.assertEqual(sorted(assembled, key=str), sorted(built, key=str))+ for what in built:+ self.assertEqual(assembled[what], built[what], what)+++class Branches(Case):+ def caller(self, addend=None):+ o = Object()+ t = o.text(BL, RET)+ o.define('_caller', t)+ o.reloc(t, 0, BRANCH26, o.undefined('_callee'), pcrel=1, addend=addend)+ return o++ def test_the_addend_is_a_signed_24_bit_number(self):+ callee = KEXT_VA['__TEXT_EXEC'] + 0x10000+ for addend in (-4, -0x800000, 0x7ffffc):+ k = self.link(self.caller(addend), outside={'_callee': callee})+ at = k.symbols['_caller']+ self.assertEqual(branch_target(k.u32(at), at), callee + addend, hex(addend))++ def test_an_addend_applies_to_the_relocation_after_it_only(self):+ o = Object()+ t = o.text(BL, BL, RET, RET)+ o.define('_caller', t)+ callee = o.define('_callee', t, 8)+ o.reloc(t, 0, BRANCH26, callee, pcrel=1, addend=4)+ o.reloc(t, 4, BRANCH26, callee, pcrel=1)+ k = self.link(o)+ at = k.symbols['_caller']+ self.assertEqual(branch_target(k.u32(at), at), k.symbols['_callee'] + 4)+ self.assertEqual(branch_target(k.u32(at + 4), at + 4), k.symbols['_callee'])++ def test_as_far_as_a_branch_reaches_and_no_farther(self):+ at = KEXT_VA['__TEXT_EXEC'] # where _caller's bl is+ for delta in (0x7fffffc, -0x8000000):+ k = self.link(self.caller(), outside={'_callee': at + delta})+ self.assertEqual(branch_target(k.u32(at), at), at + delta)+ for delta in (0x8000000, -0x8000004):+ self.assertIn('_callee', self.refused(self.caller(), outside={'_callee': at + delta}))++ def test_a_symbol_nothing_defines(self):+ self.assertIn('unresolved symbols: _callee', self.refused(self.caller()))++ def test_a_static_function_is_its_own_objects(self):+ """Two objects with a local symbol of one name each call their own; a third's external one is another."""+ objects = []+ for i in range(3):+ o = Object()+ t = o.text(BL, RET, movz(0, 10 + i), RET)+ o.define(f'_caller{i}', t)+ o.reloc(t, 0, BRANCH26, o.define('_helper', t, 8, ext=i == 2), pcrel=1)+ objects.append(o)+ k = self.link(*objects)+ for i in range(3):+ at = k.symbols[f'_caller{i}']+ self.assertEqual(k.u32(branch_target(k.u32(at), at)), movz(0, 10 + i), f'object {i}')++ def test_the_strong_definition_also_for_the_object_with_the_weak_one(self):+ weak, strong = Object(), Object()+ t = weak.text(BL, RET, movz(0, 1), RET)+ weak.define('_caller', t)+ weak.reloc(t, 0, BRANCH26, weak.define('_f', t, 8, weak=True), pcrel=1)+ strong.define('_f', strong.text(movz(0, 2), RET))+ for objects in ((weak, strong), (strong, weak)):+ k = self.link(*objects)+ at = k.symbols['_caller']+ self.assertEqual(k.u32(branch_target(k.u32(at), at)), movz(0, 2))+++class Pages(Case):+ def reader(self, insn, sym_off=0, addend=None, align_=4):+ """adrp x1, _d@PAGE; <insn> [x1, _d@PAGEOFF], with _d at sym_off of a section of this alignment."""+ o = Object()+ t = o.text(adrp(1), insn, RET)+ d = o.section('__DATA', '__data', bytes(sym_off + 16), align_)+ o.define('_reader', t)+ sym = o.define('_d', d, sym_off)+ o.reloc(t, 0, PAGE21, sym, pcrel=1, addend=addend)+ o.reloc(t, 4, PAGEOFF12, sym, addend=addend)+ return o++ def operand(self, k, scale=0):+ at = k.symbols['_reader']+ return adrp_page(k.u32(at), at) + (imm12(k.u32(at + 4)) << scale)++ def test_a_negative_addend_into_the_page_before(self):+ k = self.link(self.reader(add(1, 1), addend=-8, align_=12))+ self.assertEqual(k.symbols['_d'] & 0xfff, 0)+ self.assertEqual(self.operand(k), k.symbols['_d'] - 8)++ def test_pages_below_and_above_as_far_as_adrp_reaches(self):+ text = KEXT_VA['__TEXT_EXEC']+ for data in (text - 0x40000000, text + 0xfffe0000, text - 0x100000000):+ k = self.link(self.reader(add(1, 1)), addrs={'__DATA': data})+ self.assertEqual(k.symbols['_d'] & ~0x3fff, data)+ self.assertEqual(self.operand(k), k.symbols['_d'], hex(data))+ for data in (text + 0x100000000, text - 0x100004000):+ self.assertIn('out of range', self.refused(self.reader(add(1, 1)), addrs={'__DATA': data}))++ def test_an_offset_the_instruction_cannot_count(self):+ """A load of 2, 4, 8 or 16 bytes at an address that is not a multiple of that is refused, not rounded."""+ for name, (insn, scale) in LOADS.items():+ for off in (1 << scale >> 1, 1 << scale):+ if off & ((1 << scale) - 1):+ self.assertIn('not aligned', self.refused(self.reader(insn, off)), f'{name} at +{off}')+ else:+ k = self.link(self.reader(insn, off))+ self.assertEqual(self.operand(k, scale), k.symbols['_d'], f'{name} at +{off}')++ def test_a_page_offset_into_another_instruction(self):+ for insn in (NOP, 0xb1000021, 0xd1000021): # adds and sub take no @PAGEOFF from an assembler either+ self.assertIn('page offset into instruction', self.refused(self.reader(insn)))+++class Got(Case):+ def setUp(self):+ super().setUp()+ self.objects = []++ def loader(self, name, define=False):+ """adrp x1, name@GOTPAGE; ldr x1, [x1, name@GOTPAGEOFF]"""+ o = Object()+ t = o.text(adrp(1), LDR_X1_X1, RET)+ o.define(f'_loader_{len(self.objects)}', t)+ sym = o.define(name, o.section('__DATA', '__data', bytes(8), 3)) if define else o.undefined(name)+ o.reloc(t, 0, GOT_LOAD_PAGE21, sym, pcrel=1)+ o.reloc(t, 4, GOT_LOAD_PAGEOFF12, sym)+ self.objects.append(o)++ def slot(self, k, i):+ at = k.symbols[f'_loader_{i}']+ return adrp_page(k.u32(at), at) + (imm12(k.u32(at + 4)) << 3)++ def test_one_slot_for_a_symbol_whoever_loads_it(self):+ self.loader('_a')+ self.loader('_b', define=True)+ self.loader('_a')+ self.loader('_b')+ k = self.link(*self.objects, outside={'_a': HEADER_VA + 0x3900000})+ got, size = k.section('__DATA_CONST', '__got')+ self.assertEqual(size, 16)+ self.assertEqual(self.slot(k, 0), self.slot(k, 2))+ self.assertEqual(self.slot(k, 1), self.slot(k, 3))+ self.assertEqual({self.slot(k, 0), self.slot(k, 1)}, {got, got + 8})+ self.assertEqual(self.pointer(k, self.slot(k, 0)), (HEADER_VA + 0x3900000, None))+ self.assertEqual(self.pointer(k, self.slot(k, 1)), (k.symbols['_b'], None))++ def test_a_symbol_nothing_defines(self):+ self.loader('_nowhere')+ self.assertIn('unresolved symbols: _nowhere', self.refused(*self.objects))++ def test_no_got_without_a_load_through_it(self):+ k = self.link(far())+ self.assertNotIn(('__DATA_CONST', '__got'), k.kx.out)+ self.assertNotIn('__DATA_CONST', k.segments)+++class Pointers(Case):+ def holder(self):+ o = Object()+ t = o.text(movz(0, 3), RET)+ d = o.section('__DATA', '__data', bytes(64), 3)+ return o, t, d, o.define('_f', t), o.define('_p', d)++ def test_every_key_with_and_without_address_diversity(self):+ o, t, d, f, p = self.holder()+ cases = [(key, div, addr) for key in (KEY_IA, KEY_IB, KEY_DA, KEY_DB) for div, addr in ((0, 0), (0xa5a5, 1))]+ for i, (key, div, addr) in enumerate(cases):+ o.auth_pointer(d, 8 * i, f, key, div, addr)+ k = self.link(o)+ for i, case in enumerate(cases):+ self.assertEqual(self.pointer(k, k.symbols['_p'] + 8 * i), (k.symbols['_f'], case))++ def test_a_signed_pointers_addend_is_a_signed_32_bit_number(self):+ o, t, d, f, p = self.holder()+ addends = (0x7fffffff, -0x80000000, -1, 0x10)+ for i, addend in enumerate(addends):+ o.auth_pointer(d, 8 * i, f, KEY_DA, 0xffff, 1, addend=addend)+ k = self.link(o)+ for i, addend in enumerate(addends):+ self.assertEqual(self.pointer(k, k.symbols['_p'] + 8 * i),+ ((k.symbols['_f'] + addend) & mkmacho.MASK64, (KEY_DA, 0xffff, 1)), hex(addend))++ def test_a_pointer_into_a_section_by_its_number(self):+ """r_extern 0: the 8 bytes hold the target's address in the object, r_symbolnum its section."""+ o, t, d, f, p = self.holder()+ c = o.section('__DATA', '__const', struct.pack('<2Q', 0x33, 0x44), 3)+ struct.pack_into('<Q', o.data(d), 0, o.addr(c, 8))+ o.reloc(d, 0, UNSIGNED, c, length=3, extern=0)+ struct.pack_into('<Q', o.data(d), 8, o.addr(t, 4) | 2 << 49 | 0x77 << 32 | 1 << 63)+ o.reloc(d, 8, AUTHENTICATED_POINTER, t, length=3, extern=0)+ k = self.link(o)+ const = k.section('__DATA_CONST', '__const')[0]+ self.assertEqual(k.u64(const + 8), 0x44)+ self.assertEqual(self.pointer(k, k.symbols['_p']), (const + 8, None))+ self.assertEqual(self.pointer(k, k.symbols['_p'] + 8), (k.symbols['_f'] + 4, (KEY_DA, 0x77, 0)))++ def test_a_32_bit_pointer_is_refused(self):+ o, t, d, f, p = self.holder()+ o.reloc(d, 0, UNSIGNED, f, length=2)+ self.assertIn('32-bit pointer at __data+0x0', self.refused(o))++ def test_a_pointer_not_at_a_multiple_of_4(self):+ """A collection's chained fixups are at multiples of 4 (a pointer in a packed structure may not be): refused+ with the object and the place, not left for the collection's writer to find."""+ for off in (1, 2, 7):+ o, t, d, f, p = self.holder()+ c = o.section('__DATA', '__const', bytes(16), 0)+ o.pointer(c, off, f)+ self.assertIn(f'o0.o: pointer at __const+{off:#x} not at a multiple of 4', self.refused(o))+ o, t, d, f, p = self.holder()+ c = o.section('__DATA', '__const', bytes(16), 0)+ o.pointer(c, 4, f) # 4 is fine, 8 is not needed+ k = self.link(o)+ self.assertEqual(self.pointer(k, k.section('__DATA_CONST', '__const')[0] + 4), (k.symbols['_f'], None))++ def test_a_symbol_nothing_defines(self):+ o, t, d, f, p = self.holder()+ o.pointer(d, 0, o.undefined('_nowhere'))+ o.auth_pointer(d, 8, o.undefined('_nowhere_else'), KEY_IA)+ self.assertIn('unresolved symbols: _nowhere _nowhere_else', self.refused(o))++ def test_a_vtable_slot_for_a_method_no_kext_exports(self):+ """The spec's `vtable` class: a slot naming what nothing exports takes the superclass's, by its index."""+ o, t, d, f, p = self.holder()+ vt = o.section('__DATA', '__const', bytes(48), 3)+ o.define('__ZTV3Sub', vt)+ o.auth_pointer(vt, 16, f, KEY_IA, 0x1111, 1)+ o.auth_pointer(vt, 24, o.undefined('__ZN4Base7privateEv'), KEY_IA, 0x2222, 1)+ o.auth_pointer(vt, 32, o.undefined('__ZN4Base5otherEv'), KEY_IA, 0x3333, 1, addend=4)+ spec = {'vtable': {'class': 'Sub', 'base': 'Base'}}+ base = {1: HEADER_VA + 0x2a00000, 2: HEADER_VA + 0x2a00100}+ k = self.link(o, spec=spec, inherited=base.get)+ at = k.symbols['__ZTV3Sub']+ self.assertEqual(self.pointer(k, at + 16), (k.symbols['_f'], (KEY_IA, 0x1111, 1)))+ self.assertEqual(self.pointer(k, at + 24), (base[1], (KEY_IA, 0x2222, 1)))+ self.assertEqual(self.pointer(k, at + 32), (base[2] + 4, (KEY_IA, 0x3333, 1)))+ self.assertIn('__ZN4Base5otherEv', self.refused(o, spec=spec, inherited={1: base[1]}.get))+ self.assertIn('__ZN4Base7privateEv', self.refused(o)) # and not without the spec saying so+++class NotLinked(Case):+ """What kextld does not resolve it must refuse: left as the assembler wrote it, a kext would load and run wrong."""++ def test_a_difference_of_two_symbols(self):+ o = Object()+ t = o.text(RET, RET)+ d = o.section('__DATA', '__data', bytes(8), 3)+ o.reloc(d, 0, UNSIGNED, o.define('_b', t, 4), length=3, minus=o.define('_a', t))+ self.assertIn('relocation type 1 at __data+0x0', self.refused(o))++ def test_a_pointer_to_a_got_slot(self):+ for pcrel, length in ((1, 2), (0, 3)):+ o = Object()+ d = o.section('__DATA', '__data', bytes(8), 3)+ o.reloc(d, 0, POINTER_TO_GOT, o.undefined('_outside'), pcrel=pcrel, length=length)+ self.assertIn('relocation type 7 at __data+0x0', self.refused(o, outside=OUTSIDE))++ def test_a_thread_local(self):+ o = Object()+ t = o.text(adrp(0), RET)+ o.reloc(t, 0, TLVP_PAGE21, o.undefined('_outside'), pcrel=1)+ self.assertIn('relocation type 8 at __text+0x0', self.refused(o, outside=OUTSIDE))++ def test_a_got_load_of_a_section(self):+ o = Object()+ t = o.text(adrp(1), RET)+ o.reloc(t, 0, GOT_LOAD_PAGE21, t, pcrel=1, extern=0)+ self.assertIn('GOT load of a section', self.refused(o))++ def test_a_symbol_in_a_section_the_kext_does_not_get(self):+ o = Object()+ d = o.section('__DATA', '__data', bytes(8), 3)+ o.pointer(d, 0, o.define('_unwind', o.section('__LD', '__compact_unwind', bytes(32), 3), ext=False))+ self.assertIn('dropped section __LD,__compact_unwind', self.refused(o))+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/kclink/test_macho.py b/tests/kclink/test_macho.pynew file mode 100755index 0000000..4bd79ba--- /dev/null+++ b/tests/kclink/test_macho.py@@ -0,0 +1,371 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""scripts/kclink/macho.py against the formats: what it reads of an image (load commands, segments, sections, symbols),+that what it writes of a segment is what it read, a collection's chained fixups written and walked back bit by bit+(DYLD_CHAINED_PTR_64_KERNEL_CACHE: page starts, the stride of 4, the last pointer of a page), and a kernel's threaded+rebases. The images are made here (mkmacho.py), the chains walked by a reader of its own:++ python3 tests/kclink/test_macho.py+"""+import os+import struct+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import mkmacho # noqa: E402+from mkmacho import (KEY_DA, KEY_DB, KEY_IA, KEY_IB, LC_DYLD_CHAINED_FIXUPS, LC_FILESET_ENTRY, # noqa: E402+ LC_SEGMENT_64, LC_SYMTAB, LC_UNIXTHREAD, N_EXT, N_PEXT, N_SECT, N_WEAK_DEF, RET, S_ZEROFILL,+ TEXT_FLAGS, Object)+import macho # noqa: E402++PAGE = 0x4000+VA = 0xfffffff007004000+++def an_object():+ o = Object()+ t = o.text(RET, RET)+ d = o.section('__DATA', '__data', b'\x11' * 24, 3)+ z = o.section('__DATA', '__bss', align_=4, zerofill=48)+ u = o.section('__LD', '__compact_unwind', bytes(32), 3, mkmacho.S_ATTR_DEBUG) # a name of all 16 bytes+ o.define('_f', t)+ o.define('_local', t, 4, ext=False)+ o.define('_weak', d, 8, weak=True)+ o.define('_hidden', d, 16, private=True)+ o.define('_zero', z, 8)+ o.undefined('_elsewhere')+ o.absolute('_abs', 0x1234)+ o.syms.append(('stab', 0x24, 1, 0, 0)) # N_FUN: a debugger's entry, not a symbol+ o.pointer(d, 0, 0)+ return o, (t, d, z, u)+++class Reading(unittest.TestCase):+ def test_an_object(self):+ o, (t, d, z, u) = an_object()+ buf = o.build()+ img = macho.Image(buf)+ self.assertEqual((img.filetype, img.cputype, img.cpusubtype & 0xffffff), (macho.MH_OBJECT, 0x0100000c, 2))+ self.assertEqual([c for c, raw in img.cmds], [LC_SEGMENT_64, LC_SYMTAB])+ self.assertEqual(sum(len(raw) for c, raw in img.cmds), img.sizeofcmds)+ self.assertEqual(len(img.segments), 1)+ sects = img.sections()+ self.assertEqual([(s.segname, s.sectname) for s in sects], [('__TEXT', '__text'), ('__DATA', '__data'),+ ('__DATA', '__bss'), ('__LD', '__compact_unwind')])+ self.assertEqual([(s.addr, s.size, s.align) for s in sects], [(0, 8, 2), (8, 24, 3), (32, 48, 4), (80, 32, 3)])+ self.assertEqual([s.zerofill for s in sects], [False, False, True, False])+ self.assertEqual((sects[0].flags, sects[2].flags), (TEXT_FLAGS, S_ZEROFILL))+ self.assertEqual(buf[sects[1].offset:sects[1].offset + 24], bytes(8) + b'\x11' * 16)+ self.assertEqual((sects[1].nreloc, sects[0].nreloc), (1, 0))+ self.assertEqual(struct.unpack_from('<iI', buf, sects[1].reloff), (0, 0 | 3 << 25 | 1 << 27))+ self.assertIs(img.section('__DATA', '__bss').zerofill, True)+ self.assertIsNone(img.section('__DATA', '__const'))+ self.assertIsNone(img.segment('__TEXT')) # (an object's one segment has no name)++ def test_its_symbols(self):+ o, sects = an_object()+ img = macho.Image(o.build())+ self.assertEqual(img.symbols(), [+ ('_f', N_SECT | N_EXT, 1, 0, 0), ('_local', N_SECT, 1, 0, 4), ('_weak', N_SECT | N_EXT, 2, N_WEAK_DEF, 16),+ ('_hidden', N_SECT | N_EXT | N_PEXT, 2, 0, 24), ('_zero', N_SECT | N_EXT, 3, 0, 40),+ ('_elsewhere', N_EXT, 0, 0, 0), ('_abs', 2 | N_EXT, 0, 0, 0x1234), ('stab', 0x24, 1, 0, 0)])+ self.assertEqual(img.exports(), {'_f': 0, '_weak': 16, '_hidden': 24, '_zero': 40, '_abs': 0x1234})++ def test_zero_fill_is_a_type_not_a_flag(self):+ for flags, zerofill in ((0x1, True), (0xc, True), (0x12, True), (0x80000401, True), (0x0, False),+ (0x2, False), (0x11, False), (0x100, False)):+ o = Object()+ o.section('__DATA', '__x', b'', 0, flags)+ self.assertIs(macho.Image(o.build()).sections()[0].zerofill, zerofill, hex(flags))++ def test_no_mach_o(self):+ for buf in (bytes(64), struct.pack('<I', 0xfeedface) + bytes(60), struct.pack('>I', 0xfeedfacf) + bytes(60)):+ with self.assertRaises(ValueError):+ macho.Image(buf)++ def kernel(self):+ segs = [('__TEXT', VA + PAGE, bytes(2 * PAGE), [('__const', 0x2000, 0x100, 0)]),+ ('__DATA_CONST', VA + 0x100000, bytes(PAGE), [('__const', 0, PAGE, 0)]),+ ('__TEXT_EXEC', VA + 0x200000, mkmacho.words(RET, RET) + bytes(PAGE - 8),+ [('__text', 0, 8, TEXT_FLAGS)]),+ ('__DATA', VA + 0x300000, bytes(PAGE), [('__data', 0, 0x100, 0), ('__bss', 0x100, 0x200, S_ZEROFILL)])]+ symbols = [('_start', VA + 0x200000, True), ('_second', VA + 0x200004, False), ('_datum', VA + 0x300010, True)]+ return mkmacho.kernel(segs, symbols, extra=[struct.pack('<4I', 0x26, 16, 0, 0)])++ def test_an_executable(self):+ buf = self.kernel()+ img = macho.Image(buf)+ self.assertEqual(img.filetype, macho.MH_EXECUTE)+ self.assertEqual([s.name for s in img.segments], ['__TEXT', '__DATA_CONST', '__TEXT_EXEC', '__DATA',+ '__LINKEDIT'])+ self.assertEqual([(s.vmaddr - VA, s.vmsize, s.fileoff) for s in img.segments[:4]],+ [(PAGE, 2 * PAGE, 0), (0x100000, PAGE, 2 * PAGE), (0x200000, PAGE, 3 * PAGE),+ (0x300000, PAGE, 4 * PAGE)])+ self.assertEqual(img.segment('__DATA').sections[1].sectname, '__bss')+ self.assertEqual(img.section('__TEXT', '__thread_starts').addr, VA + PAGE + 0x1000)+ self.assertEqual([c for c, raw in img.cmds][-3:], [LC_SYMTAB, LC_UNIXTHREAD, 0x26])+ self.assertEqual(img.cmd(0x26), struct.pack('<4I', 0x26, 16, 0, 0))+ self.assertIsNone(img.cmd(LC_FILESET_ENTRY))+ self.assertEqual([(s.segname, s.sectname) for s in img.sections()][:4], [+ ('__TEXT', '__thread_starts'), ('__TEXT', '__const'), ('__DATA_CONST', '__const'),+ ('__TEXT_EXEC', '__text')])+ self.assertEqual(img.symbols(), [('_start', 0xf, 4, 0, VA + 0x200000), ('_second', 0xe, 4, 0, VA + 0x200004),+ ('_datum', 0xf, 5, 0, VA + 0x300010)])+ self.assertEqual(img.exports(), {'_start': VA + 0x200000, '_datum': VA + 0x300010})++ def test_addresses_to_file_offsets(self):+ img = macho.Image(self.kernel())+ self.assertEqual(img.va_to_off(VA + PAGE), 0)+ self.assertEqual(img.va_to_off(VA + 0x200004), 3 * PAGE + 4)+ self.assertEqual(img.va_to_off(VA + 0x300000 + PAGE - 1), 5 * PAGE - 1)+ for va in (VA, VA + 3 * PAGE, VA + 0x100000 + PAGE, VA + 0x400000, 0):+ self.assertIsNone(img.va_to_off(va), hex(va))+ seg = img.segment('__TEXT_EXEC')+ self.assertTrue(seg.contains(seg.vmaddr) and seg.contains(seg.vmaddr + PAGE - 1))+ self.assertFalse(seg.contains(seg.vmaddr - 1) or seg.contains(seg.vmaddr + PAGE))++ def test_an_image_inside_a_collection(self):+ """A fileset entry: its header somewhere in the file, its file offsets the collection's."""+ inner = bytearray(self.kernel())+ at = 3 * PAGE+ buf = bytearray(at) + inner+ p = at + 32+ for cmd, raw in mkmacho.commands(buf, at): # move its offsets, as a collection has them+ if cmd == LC_SEGMENT_64:+ struct.pack_into('<Q', buf, p + 40, struct.unpack_from('<Q', buf, p + 40)[0] + at)+ elif cmd == LC_SYMTAB:+ symoff, nsyms, stroff, strsize = struct.unpack_from('<4I', buf, p + 8)+ struct.pack_into('<4I', buf, p + 8, symoff + at, nsyms, stroff + at, strsize)+ p += len(raw)+ entry = struct.pack('<IIQQII', LC_FILESET_ENTRY, 48, VA + PAGE, at, 32, 0) + b'org.example.one\0'+ header = struct.pack('<8I', 0xfeedfacf, 0x0100000c, 2, macho.MH_FILESET, 1, len(entry), 0, 0)+ buf[0:32 + len(entry)] = header + entry+ top = macho.Image(buf)+ self.assertEqual((top.filetype, top.entries), (macho.MH_FILESET, [('org.example.one', VA + PAGE, at)]))+ img = macho.Image(buf, at)+ self.assertEqual(img.va_to_off(VA + 0x200004), at + 3 * PAGE + 4)+ self.assertEqual(img.exports(), {'_start': VA + 0x200000, '_datum': VA + 0x300010})+ # and one whose offsets are its own: counted from `base`+ own = macho.Image(bytearray(at) + inner, at, at)+ self.assertEqual(own.va_to_off(VA + 0x200004), at + 3 * PAGE + 4)+ self.assertEqual(own.exports(), img.exports())+++class Writing(unittest.TestCase):+ def test_a_segment_packs_to_what_was_read(self):+ o, sects = an_object()+ for buf in (o.build(), Reading().kernel()):+ for cmd, raw in mkmacho.commands(buf):+ if cmd == LC_SEGMENT_64:+ seg = macho.Segment(raw)+ self.assertEqual(seg.pack(), raw)+ for i, s in enumerate(seg.sections):+ self.assertEqual(s.pack(), raw[72 + 80 * i:152 + 80 * i])++ def test_a_segment_made_from_numbers(self):+ seg = macho.Segment(name='__DATA_CONST', vmaddr=VA + 0x8000, vmsize=0x4000, fileoff=0x8000, filesize=0x3000,+ prot=3, flags=0x10)+ s = macho.Section(bytes(80))+ s.sectname, s.segname, s.addr, s.size, s.offset, s.align, s.flags = '__const', '__DATA_CONST', VA + 0x8010, \+ 0x20, 0x8010, 4, 0x8000000+ seg.sections.append(s)+ raw = seg.pack()+ self.assertEqual(struct.unpack_from('<II', raw), (LC_SEGMENT_64, 152))+ back, = mkmacho.segments(struct.pack('<8I', 0xfeedfacf, 0x0100000c, 2, 2, 1, len(raw), 0, 0) + raw)+ self.assertEqual(back, dict(name='__DATA_CONST', vmaddr=VA + 0x8000, vmsize=0x4000, fileoff=0x8000,+ filesize=0x3000, maxprot=3, initprot=3, flags=0x10, sections=[dict(+ sectname='__const', segname='__DATA_CONST', addr=VA + 0x8010, size=0x20,+ offset=0x8010, align=4, reloff=0, nreloc=0, flags=0x8000000)]))++ def test_names_and_rounding(self):+ self.assertEqual(macho.name16('__TEXT'), b'__TEXT' + bytes(10))+ self.assertEqual(macho.name16('__compact_unwind'), b'__compact_unwind')+ self.assertEqual((macho.cstr(b'__compact_unwind'), macho.cstr(b'ab\0cd\0')), ('__compact_unwind', 'ab'))+ self.assertEqual([macho.align(v, 16) for v in (0, 1, 16, 17)], [0, 16, 16, 32])+++def collection(size, segments, fixups, header_va=VA):+ """A file of `size` bytes with macho.kc_write_fixups()'s chains for `fixups` and, at its end, the payload, the+ LC_DYLD_CHAINED_FIXUPS of its header pointing there. Returns (bytes, (payload offset, size))."""+ out = bytearray(size)+ blob = macho.kc_write_fixups(out, header_va, segments, fixups)+ out[0:48] = struct.pack('<8I', 0xfeedfacf, 0x0100000c, 2, macho.MH_FILESET, 1, 16, 0, 0) + \+ struct.pack('<4I', LC_DYLD_CHAINED_FIXUPS, 16, size, len(blob))+ return bytes(out) + blob, (size, len(blob))+++SEGMENTS = [('__TEXT', 0, PAGE), ('__DATA_CONST', PAGE, 2 * PAGE), ('__TEXT_EXEC', 3 * PAGE, PAGE),+ ('__DATA', 4 * PAGE, 3 * PAGE)]+++class ChainedFixups(unittest.TestCase):+ def test_one_pointer_bit_by_bit(self):+ # dyld_chained_ptr_64_kernel_cache_rebase: target:30 cacheLevel:2 diversity:16 addrDiv:1 key:2 next:12 isAuth:1+ self.assertEqual(macho.kc_encode(0x1234567, None, 0, 0, 0), 0x1234567)+ self.assertEqual(macho.kc_encode(0x3fffffff, None, 0, 0, 0xfff), 0x3fffffff | 0xfff << 51)+ self.assertEqual(macho.kc_encode(0x10, KEY_DB, 0xbeef, 1, 5),+ 0x10 | 0xbeef << 32 | 1 << 48 | 3 << 49 | 5 << 51 | 1 << 63)+ self.assertEqual(macho.kc_encode(0, KEY_IA, 0, 0, 0), 1 << 63)+ for target in (-1, 1 << 30):+ with self.assertRaises(ValueError):+ macho.kc_encode(target, None, 0, 0, 0)++ def test_decoding_is_the_inverse(self):+ for key in (None, KEY_IA, KEY_IB, KEY_DA, KEY_DB):+ for div, addr, nxt in ((0, 0, 0), (0xffff, 1, 0xfff), (0x8001, 0, 1)):+ raw = macho.kc_encode(0x2aaaaaaa, key, div, addr, nxt)+ p = mkmacho.Pointer(raw)+ self.assertEqual((p.target, p.cache_level, p.next), (0x2aaaaaaa, 0, nxt))+ self.assertEqual(p.signing(), None if key is None else (key, div, addr))+ self.assertEqual(macho.kc_decode(raw), (0x2aaaaaaa, 0, key, div if key is not None else 0,+ addr if key is not None else 0, nxt))+ self.assertEqual(macho.kc_decode(0x10 | 2 << 30)[:2], (0x10, 2))++ def fixups(self):+ """Pointers in two of four segments: the first and the last word of a page, one over a page's end, one+ alone on its page, pages with none."""+ f = {}+ for off in (PAGE, PAGE + 8, PAGE + 0x3ffc, 2 * PAGE + 4, 2 * PAGE + 0x3ff8): # __DATA_CONST+ f[off] = macho.Fixup(VA + 0x100 + off)+ f[PAGE + 8] = macho.Fixup(VA + 0x3fffffff, KEY_IA, 0xe4fe, 0)+ f[5 * PAGE + 0x10] = macho.Fixup(VA, KEY_DA, 0xffff, 1) # __DATA, its second page+ f[6 * PAGE + 0x3ff8] = macho.Fixup(VA + 4 * PAGE) # its third+ return f++ def test_the_chains_written(self):+ fixups = self.fixups()+ buf, payload = collection(8 * PAGE, SEGMENTS, dict(reversed(list(fixups.items()))))+ header, starts, pointers = mkmacho.chained_fixups(buf)+ # dyld_chained_fixups_header: version 0, no imports (their offsets past the starts), symbols uncompressed+ self.assertEqual((header[0], header[4], header[6]), (0, 0, 0))+ self.assertEqual(header[2], header[3])+ self.assertEqual(header[2], payload[1])+ self.assertEqual([s is not None for s in starts], [False, True, False, True])+ dc, data = starts[1], starts[3]+ for s, off, pages in ((dc, PAGE, [0, 4]), (data, 4 * PAGE, [0xffff, 0x10, 0x3ff8])):+ self.assertEqual((s['page_size'], s['pointer_format'], s['segment_offset'], s['max_valid_pointer']),+ (PAGE, 8, off, 0))+ self.assertEqual(s['page_start'], pages)+ self.assertEqual(s['size'], 22 + 2 * len(pages)) # as far as the last page_start+ self.assertEqual(s['offset'] % 8, 0)+ self.assertLessEqual(dc['offset'] + dc['size'], data['offset'])+ self.assertLessEqual(data['offset'] + data['size'], payload[1])+ # every pointer is on a chain, and says what it was given+ self.assertEqual(sorted(pointers), sorted(fixups))+ for off, p in pointers.items():+ f = fixups[off]+ self.assertEqual((p.target, p.cache_level), (f.target - VA, 0), hex(off))+ self.assertEqual(p.signing(), None if f.key is None else (f.key, f.div, f.addr_div), hex(off))+ # next: in units of 4 bytes to the next pointer of the page, 0 at the last one+ self.assertEqual([pointers[off].next for off in sorted(pointers)],+ [2, (0x3ffc - 8) // 4, 0, (0x3ff8 - 4) // 4, 0, 0, 0])+ # nothing else of the file is touched+ blank = bytearray(buf[:8 * PAGE])+ for off in fixups:+ self.assertNotEqual(blank[off:off + 8], bytes(8))+ blank[off:off + 8] = bytes(8)+ self.assertEqual(blank[48:], bytes(8 * PAGE - 48))++ def test_read_back(self):+ fixups = self.fixups()+ buf, payload = collection(8 * PAGE, SEGMENTS, fixups)+ back = macho.kc_read_fixups(buf, VA, None)+ self.assertEqual({off: (f.target, f.key, f.div, f.addr_div) for off, f in back.items()},+ {off: (f.target, f.key, f.div, f.addr_div) for off, f in fixups.items()})+ no_command = struct.pack('<8I', 0xfeedfacf, 0x0100000c, 2, 12, 0, 0, 0, 0)+ self.assertEqual(macho.kc_read_fixups(no_command, VA, None), {})++ def test_the_farthest_two_pointers_of_a_page(self):+ """next has 12 bits and counts 4 bytes: from a page's first word its last (4095 words on) is in reach."""+ fixups = {PAGE: macho.Fixup(VA), PAGE + 0x3ffc: macho.Fixup(VA + 8)}+ buf, payload = collection(8 * PAGE, SEGMENTS, fixups)+ header, starts, pointers = mkmacho.chained_fixups(buf)+ self.assertEqual([p.next for p in pointers.values()], [0xfff, 0])+ self.assertEqual(sorted(macho.kc_read_fixups(buf, VA, None)), sorted(fixups))++ def test_no_pointers(self):+ buf, payload = collection(8 * PAGE, SEGMENTS, {})+ header, starts, pointers = mkmacho.chained_fixups(buf)+ self.assertEqual((starts, pointers), ([None] * 4, {}))+ self.assertEqual(macho.kc_read_fixups(buf, VA, None), {})++ def test_pointers_that_cannot_be_written(self):+ for off, why in ((PAGE + 2, 'misaligned'), (8 * PAGE, 'outside'), (-8, 'outside')):+ with self.assertRaises(ValueError, msg=hex(off)) as e:+ collection(8 * PAGE, SEGMENTS, {off: macho.Fixup(VA)})+ self.assertIn(why, str(e.exception))+ gap = [('__TEXT', 0, PAGE), ('__DATA', 2 * PAGE, PAGE)]+ with self.assertRaises(ValueError):+ collection(8 * PAGE, gap, {PAGE + 8: macho.Fixup(VA)})+ for target in (VA - 8, VA + (1 << 30)): # 30 bits of offset from the collection's header+ with self.assertRaises(ValueError):+ collection(8 * PAGE, SEGMENTS, {PAGE: macho.Fixup(target)})++ def test_chains_that_are_not_a_collections(self):+ fixups = self.fixups()+ buf, (at, size) = collection(8 * PAGE, SEGMENTS, fixups)+ header, starts, pointers = mkmacho.chained_fixups(buf)+ info = at + starts[1]['offset']++ def changed(off, fmt, value):+ b = bytearray(buf)+ struct.pack_into(fmt, b, off, value)+ return bytes(b)++ first = struct.unpack_from('<Q', buf, PAGE)[0]+ for what, bad in (('imports', changed(at + 16, '<I', 1)),+ ('the pointer format', changed(info + 6, '<H', 2)), # DYLD_CHAINED_PTR_64+ ('several chains in a page', changed(info + 22, '<H', 0x8000)), # ..._START_MULTI+ ('another cache level', changed(PAGE, '<Q', first | 1 << 30))):+ with self.assertRaises(ValueError, msg=what):+ macho.kc_read_fixups(bad, VA, None)+++class ThreadedRebases(unittest.TestCase):+ TEXT, DATA = VA + PAGE, VA + 0x100000++ def kernel(self, chains, stride=4):+ return macho.Image(mkmacho.kernel([('__TEXT', self.TEXT, bytes(2 * PAGE), []),+ ('__DATA', self.DATA, bytes(2 * PAGE), [('__data', 0, 2 * PAGE, 0)])],+ chains=chains, stride=stride))++ def rebases(self, chains, stride=4):+ return {va: (f.target, None if f.key is None else (f.key, f.div, f.addr_div))+ for va, f in macho.threaded_rebases(self.kernel(chains, stride)).items()}++ def test_plain_and_signed_pointers(self):+ d = self.DATA+ chains = [[(d, self.TEXT + 0x10, None), (d + 8, 0x0000000100004000, None), (d + 0x14, 0x8000000100004008, None),+ (d + 0x20, self.TEXT + 0x1ff0, (KEY_IA, 0x1234, 0)), (d + 0x28, d + 0x7ff8, (KEY_DB, 0xffff, 1))],+ [(d + 0x3ffc, d + 0x4000, (KEY_IB, 0, 0)), (d + 0x4004, 0xffffffffffffffff, None)]]+ self.assertEqual((d + 0x3ffc) % PAGE, PAGE - 4) # (that one lies over the end of a page)+ self.assertEqual(self.rebases(chains), {va: (target, sign) for chain in chains for va, target, sign in chain})++ def test_every_chain_of_the_starts(self):+ d = self.DATA+ chains = [[(d + 0x100, d, None)], [(d + 0x200, d + 8, None), (d + 0x200 + 4 * 0x7ff, d + 16, None)],+ [(d + 0x4000, d + 24, (KEY_DA, 7, 1))]]+ self.assertEqual(self.rebases(chains), {va: (target, sign) for chain in chains for va, target, sign in chain})++ def test_a_stride_of_eight(self):+ d = self.DATA+ chain = [(d, d + 0x40, None), (d + 8, d + 0x48, (KEY_IA, 1, 0)), (d + 8 + 8 * 0x7ff, d + 0x50, None)]+ self.assertEqual(self.rebases([chain], stride=8), {va: (target, sign) for va, target, sign in chain})++ def test_none(self):+ self.assertEqual(self.rebases([]), {})+ o, sects = an_object()+ self.assertEqual(macho.threaded_rebases(macho.Image(o.build())), {})++ def test_a_bind_is_refused(self):+ img = self.kernel([[(self.DATA, self.DATA + 8, None)]])+ buf = bytearray(img.buf)+ off = img.va_to_off(self.DATA)+ struct.pack_into('<Q', buf, off, struct.unpack_from('<Q', buf, off)[0] | 1 << 62)+ with self.assertRaises(ValueError):+ macho.threaded_rebases(macho.Image(buf))+++if __name__ == '__main__':+ unittest.main()