XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
free-kc: the collection without Apple's kexts builds on a host that never had Apple's kernelcache (the kernel was linked 0x80000 over its own segments, and kclink refused it); a test (#101)
Fred Nix405f67368381
diff --git a/.github/workflows/free-kc.yml b/.github/workflows/free-kc.ymlnew file mode 100644index 0000000..e2e2384--- /dev/null+++ b/.github/workflows/free-kc.yml@@ -0,0 +1,22 @@+# SPDX-License-Identifier: GPL-2.0-only+# scripts/free-kc/kernel-slots.py (the kernel's slots in the collection without Apple's kernelcache), on Mach-O headers+# the test makes itself: tests/free-kc/test_kernel_slots.py. python3 only, a second or two.+name: free-kc+on:+ push:+ paths:+ - .github/workflows/free-kc.yml+ - scripts/free-kc/**+ - tests/free-kc/**+ pull_request:+ paths:+ - .github/workflows/free-kc.yml+ - scripts/free-kc/**+ - tests/free-kc/**+jobs:+ test:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - name: The kernel's slots from layout.json+ run: python3 tests/free-kc/test_kernel_slots.py -vdiff --git a/scripts/free-kc/kernel-slots.py b/scripts/free-kc/kernel-slots.pynew file mode 100755index 0000000..c23d136--- /dev/null+++ b/scripts/free-kc/kernel-slots.py@@ -0,0 +1,87 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""The kernel's segment slots inside the kernel collection, from numbers alone (layout.json): macOS-DroidVM's+k27/segaddrs.sh, the -segaddr list the kernel is linked with, for a host that has no Apple kernelcache.++ kernel-slots.py LAYOUT.json KERNEL.macho [--write k27/segaddrs.sh]++The slots follow the kernel's size. With macOS 27.2's kernelcache scripts/vm-xnu-rebuild.sh has k27/kc27-layout.py work+them out again after every kernel build. Without it nothing did: the kernel was linked with the segaddrs.sh+macOS-DroidVM commits, which is for its own kernel, and with xnu-patches __TEXT_EXEC is larger than its slot there. The+linker lays it over __KLD and __LAST without a word, and scripts/free-kc/build.sh ends in kclink's "segments __TEXT_EXEC+and __PRELINK_INFO overlap".++The placement is kc27-layout.py's: __TEXT_EXEC ends where __KLD starts, __KLDDATA, __DATA and __BOOTDATA end where the+kernelcache's __BOOTDATA ends, and a segment that grows has MARGIN of room. What it reads from the kernelcache is four+offsets (layout.json's kernel_slots) and the top-level segments mk-template.py builds its collection from. The file written+is the one kc27-layout.py writes, byte for byte, so the kernel is the same with the kernelcache and without. Nothing is+written, and the exit status is 1, for a kernel that does not fit.+"""+import json, struct, sys+from pathlib import Path++KB = 0xfffffff007004000 # the collection's first byte, where the kernel is linked (mk-template.py's BASE)+PAGE, MARGIN = 0x4000, 0x10000+GROWS = ('__TEXT', '__DATA_CONST', '__TEXT_EXEC', '__DATA', '__BOOTDATA') # segments given MARGIN of room to grow+MOVE = '-Wl,-rename_section,__TEXT,__cstring,__TEXT_EXEC,__cstring' # the kernel's strings are linked into __TEXT_EXEC+EMPTY = ['__PRELINK_DATA', '__PRELINK_INFO', '__PLK_TEXT_EXEC', '__PLK_DATA_CONST', '__PLK_LLVM_COV', '__PLK_LINKEDIT']+ORDER = ('__TEXT', '__DATA_CONST', '__LASTDATA_CONST', '__TEXT_EXEC', '__KLD', '__LAST', '__KLDDATA', '__DATA', '__BOOTDATA')++args = [a for a in sys.argv[1:] if a != '--write']+write = Path(args.pop(sys.argv.index('--write') - 1)) if '--write' in sys.argv else None+layout, kernel = json.loads(Path(args[0]).read_text()), Path(args[1]).read_bytes()+num = lambda s: int(s, 16) # noqa: E731+up = lambda v: -(-v // PAGE) * PAGE # noqa: E731+top = {name: (num(off), num(off) + num(size)) for name, off, size, _, _ in layout['segments']}+slot = {name: num(off) for name, off in layout['kernel_slots'].items()}++# the kernel's segment sizes, with __TEXT,__cstring counted where MOVE puts it (a kernel linked without it has it in __TEXT)+ours, off, cstring = {}, 32, 0+for _ in range(struct.unpack_from('<I', kernel, 16)[0]):+ cmd, size = struct.unpack_from('<II', kernel, off)+ if cmd == 0x19: # LC_SEGMENT_64+ name = kernel[off + 8:off + 24].rstrip(b'\0').decode()+ ours[name] = struct.unpack_from('<Q', kernel, off + 32)[0]+ for s in range(struct.unpack_from('<I', kernel, off + 64)[0]):+ if name == '__TEXT' and kernel[off + 72 + 80 * s:off + 88 + 80 * s].rstrip(b'\0') == b'__cstring':+ cstring = struct.unpack_from('<Q', kernel, off + 72 + 80 * s + 40)[0]+ off += size+if cstring:+ ours['__TEXT'], ours['__TEXT_EXEC'] = up(ours['__TEXT'] - cstring), up(ours['__TEXT_EXEC'] + cstring)+need = {name: up(size + (MARGIN if name in GROWS else 0)) for name, size in ours.items()}++place = {'__TEXT': num(layout['kernel_header']), '__DATA_CONST': top['__DATA_CONST'][0], '__LASTDATA_CONST': slot['__LASTDATA_CONST'],+ '__TEXT_EXEC': slot['__KLD'] - need['__TEXT_EXEC'], '__KLD': slot['__KLD'], '__LAST': slot['__LAST']}+place['__KLDDATA'] = slot['__BOOTDATA_END'] - need['__KLDDATA'] - need['__DATA'] - need['__BOOTDATA']+place['__DATA'] = place['__KLDDATA'] + need['__KLDDATA']+place['__BOOTDATA'] = place['__DATA'] + need['__DATA']+place['__PRELINK_TEXT'] = top['__PRELINK_INFO'][0]+linkinfo, linkinfo_size = map(num, layout['kernel_linkinfo'])++# each segment inside the collection's segment it belongs to (the data ones may start in the tail of __PRELINK_INFO, which+# the free collection leaves empty), and none over the next+data = (top['__PRELINK_INFO'][0], top['__DATA'][1])+inside = {'__TEXT': top['__PRELINK_TEXT'], '__DATA_CONST': top['__DATA_CONST'], '__LASTDATA_CONST': top['__DATA_CONST'],+ '__TEXT_EXEC': top['__TEXT_EXEC'], '__KLD': top['__TEXT_EXEC'], '__LAST': top['__TEXT_EXEC'], '__KLDDATA': data,+ '__DATA': data, '__BOOTDATA': top['__DATA']}+bad, end = [], 0+for name in ORDER:+ s, e = place[name], place[name] + need[name]+ ok = inside[name][0] <= s and e <= inside[name][1] and end <= s+ print(f'{name:18} {s:#10x}-{e:#10x} ours {ours[name]:#9x} {"ok" if ok else "DOES NOT FIT"}')+ if not ok: bad.append(name)+ end = e+if ours.get('__LINKINFO', 0) > linkinfo_size: bad.append('__LINKINFO')+if place['__KLDDATA'] < top['__PRELINK_INFO'][0] + 0x100000: bad.append('the prelink info (less than 1 MiB left)')+if bad:+ sys.exit(f'{args[1]}: no room in the collection for {", ".join(bad)}')+if write:+ o = up(place['__BOOTDATA'] + need['__BOOTDATA'])+ write.write_text('\n'.join([+ '# -segaddr list for linking the kernel into the kc27 fileset KC (generated by k27/kc27-layout.py; offsets from the KC header page)',+ f'KB={KB:#x}', f'echo -n "{MOVE} "', 'a() { printf -- "-Wl,-segaddr,%s,0x%x " "$1" $((KB + $2)); }', '{',+ ' '.join(f'a {name} {place[name]:#x};' for name in ORDER + ('__PRELINK_TEXT',)),+ f'o={o:#x}; for n in {" ".join(EMPTY)}; do a $n $o; o=$((o+{PAGE:#x})); done', f'a __LINKINFO {linkinfo:#x}',+ "} | sed 's/ $//'"]) + '\n')+ write.with_suffix('.json').write_text(json.dumps({'DATA_CONST_START': top['__DATA_CONST'][0], 'DATA_START': place['__KLDDATA']}) + '\n')+ print('wrote', write)diff --git a/scripts/free-kc/layout.json b/scripts/free-kc/layout.jsonindex ba5e79b..48a3a94 100644--- a/scripts/free-kc/layout.json+++ b/scripts/free-kc/layout.json@@ -1,5 +1,5 @@{- "comment": "Where kclink places things in a kernel collection, as offsets from its first byte: the top-level segments, the slot of the kernel's __LINKINFO and where the shared __LINKEDIT starts. The numbers are those of the layout k27/segaddrs.sh links the kernel for (macOS 27.2's kernelcache); mk-template.py builds a collection skeleton from them alone.",+ "comment": "Where kclink places things in a kernel collection, as offsets from its first byte: the top-level segments, the slot of the kernel's __LINKINFO and where the shared __LINKEDIT starts. The numbers are those of the layout k27/segaddrs.sh links the kernel for (macOS 27.2's kernelcache); mk-template.py builds a collection skeleton from them alone. kernel_slots: where that kernelcache has its own kernel's __LASTDATA_CONST, __KLD and __LAST and where its __BOOTDATA ends; kernel-slots.py places the kernel's segments by them (k27/segaddrs.sh) on a host without the kernelcache.","segments": [["__TEXT", "0x0", "0x4000", 1, null],["__PRELINK_TEXT", "0x4000", "0x814000", 1, "__text"],@@ -10,6 +10,7 @@["__LINKEDIT", "0x3e20000", "0x9c000", 1, null]],"kernel_header": "0x4000",+ "kernel_slots": {"__LASTDATA_CONST": "0x9f8000", "__KLD": "0x3854000", "__LAST": "0x3860000", "__BOOTDATA_END": "0x3cc4000"},"kernel_linkinfo": ["0x3e20000", "0x51000"],"kernel_linkedit": "0x3ebc000"}diff --git a/tests/free-kc/test_kernel_slots.py b/tests/free-kc/test_kernel_slots.pynew file mode 100755index 0000000..37e1b77--- /dev/null+++ b/tests/free-kc/test_kernel_slots.py@@ -0,0 +1,102 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""scripts/free-kc/kernel-slots.py: the kernel's slots in the collection, from layout.json alone.++ python3 tests/free-kc/test_kernel_slots.py++The "kernels" are Mach-O headers with nothing but segments of the sizes given. The two files expected are real ones:+what macOS-DroidVM's k27/kc27-layout.py wrote from macOS 27.2's kernelcache (26B123) for a kernel of these sizes.+"""+import json, struct, subprocess, sys, tempfile, unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+TOOL, LAYOUT = ROOT / 'scripts/free-kc/kernel-slots.py', ROOT / 'scripts/free-kc/layout.json'+HEAD = '''# -segaddr list for linking the kernel into the kc27 fileset KC (generated by k27/kc27-layout.py; offsets from the KC header page)+KB=0xfffffff007004000+echo -n "-Wl,-rename_section,__TEXT,__cstring,__TEXT_EXEC,__cstring "+a() { printf -- "-Wl,-segaddr,%s,0x%x " "$1" $((KB + $2)); }+{+'''+TAIL = '''o=0x3cc4000; for n in __PRELINK_DATA __PRELINK_INFO __PLK_TEXT_EXEC __PLK_DATA_CONST __PLK_LLVM_COV __PLK_LINKEDIT; do a $n $o; o=$((o+0x4000)); done+a __LINKINFO 0x3e20000+} | sed 's/ $//'+'''+# xnu-12377.121.6 with xnulinux's patches (e083534), built with clang 21.1.8: the kernel that did not fit+XNULINUX = {'__TEXT': 0x8c000, '__DATA_CONST': 0x138000, '__LASTDATA_CONST': 0x4000, '__TEXT_EXEC': 0xae4000, '__KLD': 0x4000,+ '__LAST': 0, '__KLDDATA': 0x8000, '__DATA': 0x15c000, '__BOOTDATA': 0xd4000, '__LINKINFO': 0x48000}+XNULINUX_SLOTS = ('a __TEXT 0x4000; a __DATA_CONST 0x818000; a __LASTDATA_CONST 0x9f8000; a __TEXT_EXEC 0x2d60000; a __KLD 0x3854000; '+ 'a __LAST 0x3860000; a __KLDDATA 0x3a6c000; a __DATA 0x3a74000; a __BOOTDATA 0x3be0000; a __PRELINK_TEXT 0x3864000;\n')+# the kernel macOS-DroidVM's committed k27/segaddrs.sh (524d27b) is for: 0x90000 less code, 0x8000 less data+DROIDVM = dict(XNULINUX, __TEXT_EXEC=0xa54000, __DATA=0x154000)+DROIDVM_SLOTS = ('a __TEXT 0x4000; a __DATA_CONST 0x818000; a __LASTDATA_CONST 0x9f8000; a __TEXT_EXEC 0x2df0000; a __KLD 0x3854000; '+ 'a __LAST 0x3860000; a __KLDDATA 0x3a74000; a __DATA 0x3a7c000; a __BOOTDATA 0x3be0000; a __PRELINK_TEXT 0x3864000;\n')+++def kernel(path, sizes, cstring=0):+ """A Mach-O header whose segments have these sizes; cstring: a __TEXT,__cstring section of that size (not yet moved)."""+ cmds = b''+ for name, size in sizes.items():+ sect = struct.pack('<16s16s2Q8I', b'__cstring', b'__TEXT', 0, cstring, 0, 0, 0, 0, 0, 0, 0, 0) if name == '__TEXT' and cstring else b''+ cmds += struct.pack('<II16s4Q4I', 0x19, 72 + len(sect), name.encode(), 0, size, 0, 0, 1, 1, len(sect) // 80, 0) + sect+ path.write_bytes(struct.pack('<8I', 0xfeedfacf, 0x100000c, 0xc0000002, 2, len(sizes), len(cmds), 0, 0) + cmds)+ return path+++class KernelSlots(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(); self.d = Path(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ def run_tool(self, sizes, cstring=0):+ out = self.d / 'segaddrs.sh'+ r = subprocess.run([sys.executable, str(TOOL), str(LAYOUT), str(kernel(self.d / 'kernel', sizes, cstring)), '--write', str(out)],+ capture_output=True, text=True)+ return r, out++ def test_the_kernel_with_xnu_patches_gets_a_slot_it_fits(self):+ r, out = self.run_tool(XNULINUX)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertEqual(out.read_text(), HEAD + XNULINUX_SLOTS + TAIL) # kc27-layout.py's file for this kernel, byte for byte+ self.assertEqual(json.loads(out.with_suffix('.json').read_text()), {'DATA_CONST_START': 0x818000, 'DATA_START': 0x3a6c000})+ # in the committed file's slot (0x2df0000 up to __KLD) this kernel's __TEXT_EXEC ran 0x80000 past __KLD+ self.assertGreater(0x2df0000 + XNULINUX['__TEXT_EXEC'], 0x3854000)+ self.assertLessEqual(0x2d60000 + XNULINUX['__TEXT_EXEC'], 0x3854000)++ def test_the_committed_file_is_what_it_writes_for_that_kernel(self):+ r, out = self.run_tool(DROIDVM)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertEqual(out.read_text(), HEAD + DROIDVM_SLOTS + TAIL)++ def test_strings_still_in_text_are_counted_where_they_go(self):+ # the same kernel linked without the rename: 0x64000 of __cstring in __TEXT, not yet in __TEXT_EXEC+ r, out = self.run_tool(dict(XNULINUX, __TEXT=0xf0000, __TEXT_EXEC=0xa80000), cstring=0x64000)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertEqual(out.read_text(), HEAD + XNULINUX_SLOTS + TAIL)++ def test_no_segment_over_another_whatever_the_sizes(self):+ for text in range(0x900000, 0x2800000, 0x1f4000):+ for data in range(0x100000, 0x180000, 0x34000):+ r, out = self.run_tool(dict(XNULINUX, __TEXT_EXEC=text, __DATA=data))+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+ at = dict(w.split()[1:3] for w in out.read_text().splitlines()[5].split(';') if w.strip())+ at = {n: int(v, 16) for n, v in at.items()}+ order = ['__TEXT', '__DATA_CONST', '__LASTDATA_CONST', '__TEXT_EXEC', '__KLD', '__LAST', '__KLDDATA', '__DATA', '__BOOTDATA']+ sizes = dict(XNULINUX, __TEXT_EXEC=text, __DATA=data)+ for a, b in zip(order, order[1:]):+ self.assertLessEqual(at[a] + sizes[a], at[b], (a, b, hex(text), hex(data)))++ def test_a_kernel_that_does_not_fit_is_refused_and_nothing_is_written(self):+ for sizes, what in ((dict(XNULINUX, __TEXT_EXEC=0x2900000), '__TEXT_EXEC'), (dict(XNULINUX, __DATA=0x400000), '__KLDDATA'),+ (dict(XNULINUX, __LINKINFO=0x52000), '__LINKINFO')):+ r, out = self.run_tool(sizes)+ self.assertEqual(r.returncode, 1, r.stdout + r.stderr)+ self.assertIn('no room in the collection for', r.stderr)+ self.assertIn(what, r.stderr)+ self.assertFalse(out.exists() or out.with_suffix('.json').exists())+++if __name__ == '__main__':+ unittest.main()