Skip to content

XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)

C
6.1 KB
Raw Blame
#!/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()