Skip to content

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

C

tools: xnu-input sends what was asked; kcdis, kcstrs and kcblraa give the collection's addresses; tests/tools and CI

Fred Nix4e92f99da1f6
diff --git a/.github/workflows/tools.yml b/.github/workflows/tools.yml
new file mode 100644
index 0000000..a37aa61
--- /dev/null
+++ b/.github/workflows/tools.yml
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0-only
+# The tests of the tools (tests/tools). python3 alone, but for kcdis's: those also need an llvm-objdump (the runner has
+# llvm-objdump-NN, which the test finds) and are skipped without one.
+name: tools
+on:
+ push:
+ pull_request:
+jobs:
+ tests:
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ - name: The tools' tests
+ run: python3 -m unittest discover -s tests/tools -v
diff --git a/tests/tools/test_kc_dev_tools.py b/tests/tools/test_kc_dev_tools.py
new file mode 100755
index 0000000..6bbf1bb
--- /dev/null
+++ b/tests/tools/test_kc_dev_tools.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only
+"""tools/dev/kc*.py (kcdis, kcstrs, kcxref, kcblraa) on a stand-in collection made here: a Mach-O header, two segments,
+a few dozen instructions written as numbers and three strings, at a kernel's addresses. What each tool prints is
+checked against what the instructions say, worked out here from their encodings.
+
+kcdis needs llvm-objdump (on the path, as llvm-objdump or llvm-objdump-NN, or Xcode's): its tests are skipped where
+there is none. The others need python3 only.
+
+ python3 tests/tools/test_kc_dev_tools.py
+"""
+import glob
+import os
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+
+DEV = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'tools', 'dev')
+TEXT, EXEC = 0xfffffff007004000, 0xfffffff007f9c000 # the two segments' addresses (their file offsets: 0, 0x4000)
+START = EXEC + 0xc24 # where the code is: not at a page's start
+STRINGS = TEXT + 0x48c
+NOP, RET = 0xd503201f, 0xd65f03c0
+
+
+def at(i):
+ return START + 4 * i
+
+
+def rel(target, pc, bits, shift=2):
+ """A pc-relative immediate of this many bits."""
+ delta = target - pc
+ assert delta % (1 << shift) == 0 and -(1 << (bits + shift - 1)) <= delta < 1 << (bits + shift - 1), hex(delta)
+ return delta >> shift & (1 << bits) - 1
+
+
+def bl(i, target):
+ return 0x94000000 | rel(target, at(i), 26)
+
+
+def b(i, target):
+ return 0x14000000 | rel(target, at(i), 26)
+
+
+def adrp(i, rd, target):
+ pages = rel(target & ~0xfff, at(i) & ~0xfff, 21, 12)
+ return 0x90000000 | (pages & 3) << 29 | (pages >> 2) << 5 | rd
+
+
+def adr(i, rd, target):
+ delta = rel(target, at(i), 21, 0)
+ return 0x10000000 | (delta & 3) << 29 | (delta >> 2) << 5 | rd
+
+
+def add(rd, rn, imm):
+ return 0x91000000 | imm << 10 | rn << 5 | rd
+
+
+def ldr(rt, rn, off): # ldr xt, [xn, #off]
+ return 0xf9400000 | off // 8 << 10 | rn << 5 | rt
+
+
+def mov_x17(imm):
+ return 0xd2800011 | imm << 5
+
+
+def blraa(rn, rm=17):
+ return 0xd73f0800 | rn << 5 | rm
+
+
+def code():
+ """The instructions, and for kcdis what each is: (mnemonic, the address its operand must name or None); (None,
+ None) for those it is not asked about."""
+ words, listing = [], []
+
+ def put(mnemonic, target, word):
+ words.append(word(len(words)))
+ listing.append((mnemonic, target))
+
+ def more(*insns):
+ for insn in insns:
+ put(None, None, insn if callable(insn) else lambda i, insn=insn: insn)
+
+ far, data = EXEC + 0x2b00000, TEXT + 0x2bd9234 # 43 MB on (in no segment), and off the code's own page
+ # 0: every kind of pc-relative operand
+ put('bl', far, lambda i: bl(i, far))
+ put('bl', START - 0x800, lambda i: bl(i, START - 0x800))
+ put('b', at(40), lambda i: b(i, at(40)))
+ put('b.ne', START, lambda i: 0x54000001 | rel(START, at(i), 19) << 5)
+ put('cbz', at(40), lambda i: 0xb4000000 | rel(at(40), at(i), 19) << 5)
+ put('tbnz', START, lambda i: 0x37180001 | rel(START, at(i), 14) << 5)
+ put('adr', at(41), lambda i: adr(i, 9, at(41)))
+ put('adrp', data & ~0xfff, lambda i: adrp(i, 8, data))
+ put('add', None, lambda i: add(8, 8, data & 0xfff))
+ put('ldr', at(42), lambda i: 0x5800000a | rel(at(42), at(i), 19) << 5)
+ # 10: a run of zero words, then more (their addresses count on)
+ more(0, 0, 0, 0)
+ put('bl', START, lambda i: bl(i, START))
+ more(NOP)
+ # 16: strings (kcstrs): an address, two more made from it by adding, one from a page of its own, one more
+ more(lambda i: adrp(i, 19, STRINGS), add(19, 19, STRINGS & 0xfff), add(1, 19, 0x10), add(2, 19, 0x20),
+ lambda i: adrp(i, 0, STRINGS + 0x40), add(0, 0, (STRINGS + 0x40) & 0xfff), add(1, 19, 0x10), RET)
+ # 24: calls through function pointers (kcblraa): one reached through another pointer, x8 loaded twice; one
+ # straight from a field; one whose discriminator is set too far from the load
+ more(ldr(8, 0, 8), ldr(8, 8, 0x10), 0xaa0103e0, mov_x17(0x50c7), blraa(8))
+ more(ldr(9, 19, 0x28), mov_x17(0x1111), blraa(9))
+ more(ldr(10, 0, 0x30), *[NOP] * 14, mov_x17(0x2222), blraa(10))
+ # 49: callers (kcxref): two calls of the nop at 15 and, between them, a jump to it and a call of another
+ more(lambda i: bl(i, at(15)), lambda i: b(i, at(15)), lambda i: bl(i, at(16)), lambda i: bl(i, at(15)), RET)
+ return words, listing
+
+
+def collection(path):
+ """Writes the stand-in collection: __TEXT (the header, the strings) and __TEXT_EXEC (the code)."""
+ words, listing = code()
+ text = bytearray(0x4000)
+ strings = b''.join(s.ljust(n, b'\0') for s, n in ((b'first name', 16), (b'second name', 16),
+ (b'the third of the names', 32), (b'\x01\x02\x03', 4)))
+ text[0x48c:0x48c + len(strings)] = strings
+ segs = [(b'__TEXT', TEXT, 0x4000, 0, 0x4000), (b'__TEXT_EXEC', EXEC, 0x4000, 0x4000, 0x4000)]
+ cmds = b''.join(struct.pack('<II16s4Q4I', 0x19, 72, name, va, vmsize, off, size, 5, 5, 0, 0)
+ for name, va, vmsize, off, size in segs)
+ text[0:32 + len(cmds)] = struct.pack('<8I', 0xfeedfacf, 0x100000c, 2, 12, len(segs), len(cmds), 0, 0) + cmds
+ exec_ = bytearray(0x4000)
+ exec_[0xc24:0xc24 + 4 * len(words)] = struct.pack(f'<{len(words)}I', *words)
+ with open(path, 'wb') as f:
+ f.write(text + exec_)
+ return listing
+
+
+class Tools(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.dir = tempfile.mkdtemp()
+ cls.addClassCleanup(shutil.rmtree, cls.dir)
+ cls.kc = os.path.join(cls.dir, 'kc')
+ cls.listing = collection(cls.kc)
+ cls.env = dict(os.environ)
+
+ def run_tool(self, tool, *args):
+ """(exit status, the lines it printed, what it wrote to stderr)."""
+ args = [a if isinstance(a, str) else f'{a:x}' for a in args] # (addresses are given in hex)
+ r = subprocess.run([sys.executable, os.path.join(DEV, tool), self.kc] + args, capture_output=True, text=True,
+ env=self.env)
+ return r.returncode, r.stdout.splitlines(), r.stderr
+
+
+class Kcdis(Tools):
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ if not shutil.which('llvm-objdump'): # llvm-objdump-18 and the like: under its plain name
+ versioned = sorted((p for d in os.get_exec_path() for p in glob.glob(os.path.join(d, 'llvm-objdump-*'))),
+ key=lambda p: -int(p.rsplit('-', 1)[1]) if p.rsplit('-', 1)[1].isdigit() else 0)
+ if versioned:
+ os.symlink(versioned[0], os.path.join(cls.dir, 'llvm-objdump'))
+ cls.env['PATH'] = cls.dir + os.pathsep + cls.env.get('PATH', '')
+ r = subprocess.run([sys.executable, os.path.join(DEV, 'kcdis.py'), cls.kc, f'{at(23):x}', '4'],
+ capture_output=True, text=True, env=cls.env)
+ if r.stdout.split() != [f'{at(23):x}', 'ret']:
+ raise unittest.SkipTest('kcdis has no llvm-objdump that disassembles arm64 here: ' +
+ (r.stderr.strip().splitlines() or ['no listing'])[-1])
+
+ def listed(self, start, length):
+ """kcdis's listing from instruction `start` on: [(address, mnemonic, the address its operand names or None)]."""
+ status, lines, err = self.run_tool('kcdis.py', at(start), length)
+ self.assertEqual((status, err), (0, ''))
+ out = []
+ for line in lines:
+ address, mnemonic, *operands = line.split()
+ named = [int(o, 16) for o in operands if o.startswith('0x')] # (an immediate is written #0x...)
+ out.append((int(address, 16), mnemonic, named[-1] if named else None))
+ return out
+
+ def test_pc_relative_operands_are_addresses_of_the_collection(self):
+ lines = self.listed(0, '0x40')
+ self.assertEqual([address for address, mnemonic, named in lines], [at(i) for i in range(16)])
+ for (address, mnemonic, named), (expected, target) in zip(lines, self.listing):
+ if expected:
+ self.assertEqual((mnemonic, named), (expected, target), f'the instruction at {address:x}')
+ self.assertEqual(sum(target is not None for expected, target in self.listing[:16]), 10)
+
+ def test_the_addresses_after_a_run_of_zero_words(self):
+ lines = self.listed(9, '24')
+ self.assertEqual([address for address, mnemonic, named in lines], [at(i) for i in range(9, 15)])
+ self.assertEqual(lines[5][1:], ('bl', START))
+
+ def test_from_the_middle_of_a_page_the_page_is_the_instructions_own(self):
+ self.assertEqual(self.listed(7, '4'), [(at(7), 'adrp', (TEXT + 0x2bd9234) & ~0xfff)])
+ self.assertNotEqual(at(7) & 0xfff, 0)
+
+ def test_a_length_that_is_not_whole_instructions(self):
+ for length, count in (('8', 2), ('10', 2), ('0x2a', 10), ('7', 1), ('3', 0)):
+ self.assertEqual([address for address, mnemonic, named in self.listed(0, length)],
+ [at(i) for i in range(count)], f'a length of {length}')
+
+ def test_an_address_outside_the_collection(self):
+ self.assertEqual(self.run_tool('kcdis.py', TEXT - 0x4000, '8'), (0, ['va not found'], ''))
+
+
+class Kcstrs(Tools):
+ def test_addresses_made_by_adrp_and_add(self):
+ status, lines, err = self.run_tool('kcstrs.py', at(16), '0x20')
+ self.assertEqual((status, err), (0, ''))
+ self.assertEqual(lines, [
+ f"{at(17):x}: x19 = {STRINGS:x} 'first name'",
+ f"{at(18):x}: x1 = {STRINGS + 0x10:x} 'second name'", # x19 + 0x10: the address, not its page
+ f"{at(19):x}: x2 = {STRINGS + 0x20:x} 'the third of the names'",
+ f"{at(21):x}: x0 = {STRINGS + 0x40:x} ", # no string there
+ f"{at(22):x}: x1 = {STRINGS + 0x10:x} 'second name'"])
+
+ def test_an_address_outside_the_collection(self):
+ status, lines, err = self.run_tool('kcstrs.py', TEXT - 0x4000, '8')
+ self.assertEqual((status, lines, err), (0, [f'{TEXT - 0x4000:x}: va not found'], ''))
+ # and a range that runs out of it: what is inside, then that
+ status, lines, err = self.run_tool('kcstrs.py', EXEC + 0x3ff8, '0x10')
+ self.assertEqual((status, lines, err), (0, [f'{EXEC + 0x4000:x}: va not found'], ''))
+
+
+class Kcxref(Tools):
+ def test_the_callers_of_a_function(self):
+ def callers(lo, hi, target):
+ status, lines, err = self.run_tool('kcxref.py', lo, hi, target)
+ self.assertEqual((status, err), (0, ''))
+ return [int(line, 16) for line in lines]
+
+ self.assertEqual(callers(EXEC, EXEC + 0x4000, at(15)), [at(49), at(52)])
+ self.assertEqual(callers(EXEC, EXEC + 0x4000, START), [at(14)]) # a call backward
+ self.assertEqual(callers(at(50), at(53), at(15)), [at(52)]) # only the range asked for
+ self.assertEqual(callers(TEXT, EXEC + 0x4000, at(17)), [])
+
+
+class Kcblraa(Tools):
+ def test_calls_through_a_function_pointer_field(self):
+ status, lines, err = self.run_tool('kcblraa.py', EXEC, EXEC + 0x4000)
+ self.assertEqual((status, err), (0, ''))
+ self.assertEqual(lines, [
+ f'{at(25):x} off 0x10 disc 0x50c7 base x8', # not the load before it, of the pointer it goes through
+ f'{at(29):x} off 0x28 disc 0x1111 base x19',
+ '---',
+ '0x10 0x50c7',
+ '0x28 0x1111'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/tools/test_xnu_input.py b/tests/tools/test_xnu_input.py
new file mode 100755
index 0000000..9133847
--- /dev/null
+++ b/tests/tools/test_xnu_input.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only
+"""What tools/hosted/xnu-input.py writes for a command line: the evdev records XnuInput reads (kexts/XnuInput), decoded.
+
+ python3 tests/tools/test_xnu_input.py
+"""
+import contextlib
+import importlib.util
+import io
+import os
+import struct
+import sys
+import tempfile
+import time
+import unittest
+
+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'tools', 'hosted', 'xnu-input.py')
+spec = importlib.util.spec_from_file_location('xnu_input', TOOL)
+xnu_input = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(xnu_input)
+
+EV_SYN, EV_KEY, EV_REL, EV_ABS = 0, 1, 2, 3
+REL_WHEEL, SHIFT, CMD, COMMA = 8, 42, 125, 51
+
+
+class Records(unittest.TestCase):
+ def setUp(self):
+ self.sleep, time.sleep = time.sleep, lambda seconds: None # the tool paces its frames; the test need not wait
+ self.addCleanup(setattr, time, 'sleep', self.sleep)
+
+ def run_tool(self, *argv):
+ """(records, exit status or message): records are (type, code, value) of what the tool appended to its file."""
+ f = tempfile.NamedTemporaryFile(delete=False)
+ f.close()
+ self.addCleanup(os.unlink, f.name)
+ status = 0
+ with contextlib.redirect_stderr(io.StringIO()):
+ try:
+ xnu_input.main(['--file', f.name, *argv])
+ except SystemExit as e:
+ status = e.code
+ b = open(f.name, 'rb').read()
+ self.assertEqual(len(b) % 8, 0)
+ return [struct.unpack_from('<HHi', b, i) for i in range(0, len(b), 8)], status
+
+ def frames(self, records):
+ """The records of each frame (what a SYN_REPORT ends), without the SYN."""
+ out, cur = [], []
+ for r in records:
+ if r[0] == EV_SYN:
+ out.append(cur)
+ cur = []
+ else:
+ cur.append(r)
+ self.assertEqual(cur, [], 'records after the last SYN_REPORT')
+ return out
+
+ def test_scroll_is_whole_and_fits_a_report(self):
+ # XnuInput's tablet report carries the wheel as one signed byte and clamps a frame's total at -127..127
+ for notches in (1, -1, 5, 127, 128, 300, -300, -1000):
+ records, status = self.run_tool('scroll', str(notches))
+ self.assertEqual(status, 0)
+ wheel = [sum(v for t, c, v in f if (t, c) == (EV_REL, REL_WHEEL)) for f in self.frames(records)]
+ self.assertTrue(all(-127 <= w <= 127 for w in wheel), f'scroll {notches}: a frame of {wheel}')
+ self.assertEqual(sum(wheel), notches, f'scroll {notches}: frames {wheel}')
+
+ def test_key_takes_punctuation_by_its_character(self):
+ records, status = self.run_tool('key', 'cmd', ',') # Settings...
+ self.assertEqual(status, 0)
+ self.assertEqual(self.frames(records), [[(EV_KEY, CMD, 1), (EV_KEY, COMMA, 1)], [(EV_KEY, COMMA, 0), (EV_KEY, CMD, 0)]])
+
+ def test_key_with_no_key_writes_nothing(self):
+ for argv in (('key',), ('key', 'nosuchkey')):
+ records, status = self.run_tool(*argv)
+ self.assertEqual(records, [])
+ self.assertTrue(status, argv)
+
+ def test_key_then_another_command(self):
+ records, status = self.run_tool('key', 'cmd', 'space', 'type', 'a')
+ self.assertEqual(status, 0)
+ self.assertEqual([c for f in self.frames(records) for t, c, v in f if v == 1], [CMD, 57, 30])
+
+ def test_type_presses_shift_for_capitals_and_symbols(self):
+ records, status = self.run_tool('type', 'aA1!,<')
+ self.assertEqual(status, 0)
+ downs = [[c for t, c, v in f if t == EV_KEY and v == 1] for f in self.frames(records)][::2]
+ self.assertEqual(downs, [[30], [SHIFT, 30], [2], [SHIFT, 2], [COMMA], [SHIFT, COMMA]])
+
+ def test_type_types_all_of_it_or_nothing(self):
+ # a character with no key on the US layout: the text would arrive with a hole in it
+ for text in ('café', 'Été', 'ok € ok'):
+ records, status = self.run_tool('type', text)
+ self.assertEqual(records, [], text)
+ self.assertIn('type:', str(status))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/dev/kcblraa.py b/tools/dev/kcblraa.py
index 0b92c74..87f4ca8 100644
--- a/tools/dev/kcblraa.py
+++ b/tools/dev/kcblraa.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
-# In [lo, hi) of a fileset KC: "ldr xA, [xB, #off]" followed within 4 instructions by "mov x17, #imm" and
-# "blraa xA, x17" (a call through a type-discriminated function pointer field). Prints off, imm, base reg, address.
+# In [lo, hi) of a fileset KC: "ldr xA, [xB, #off]" followed within 13 instructions by "mov x17, #imm" and
+# "blraa xA, x17" (a call through a type-discriminated function pointer field), xA not loaded again in between.
+# Prints off, imm, base reg, address.
import struct, sys, collections
path, lo, hi = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 16)
d = open(path, 'rb').read()
@@ -20,6 +21,8 @@ for _ in range(ncmds):
imm = None
for j in range(i + 1, min(i + 14, len(words))):
x = words[j]
+ if (x & 0xffc0001f) == 0xf9400000 | rt: # xA loaded again: the call is through that load, not this one
+ break
if (x & 0xffe0001f) == 0xd2800011: # movz x17, #imm16
imm = (x >> 5) & 0xffff
if (x & 0xfffffc1f) == (0xd73f0800 | 0) and ((x >> 5) & 31) == rt and imm is not None:
diff --git a/tools/dev/kcdis.py b/tools/dev/kcdis.py
index 0985f75..00e4abe 100644
--- a/tools/dev/kcdis.py
+++ b/tools/dev/kcdis.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
-# Disassemble [va, va+len) of a fileset kernel collection (top-level LC_SEGMENT_64s) with llvm-mc. Debugging aid.
-import struct, subprocess, sys
+# Disassemble [va, va+len) of a fileset kernel collection (top-level LC_SEGMENT_64s) with llvm-objdump. Debugging aid.
+import re, shutil, struct, subprocess, sys, tempfile
path, va, n = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 0)
d = open(path, 'rb').read()
ncmds = struct.unpack_from('<I', d, 16)[0]; off = 32
@@ -11,19 +11,27 @@ for _ in range(ncmds):
vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off + 24)
if vmaddr <= va < vmaddr + filesize:
fo = fileoff + (va - vmaddr); code = d[fo:fo + n]
- words = struct.unpack('<%dI' % (len(code) // 4), code)
- import tempfile, os
- t = tempfile.mkdtemp()
- open(t + '/c.s', 'w').write('.text\n.globl _x\n_x:\n' + ''.join('.inst 0x%08x\n' % w for w in words))
- subprocess.run(['xcrun', 'clang', '-arch', 'arm64e', '-c', t + '/c.s', '-o', t + '/c.o'], check=True)
- # -z: a run of zero words is one '...' line otherwise, and the lines are counted for the addresses below
- out = subprocess.run(['xcrun', 'llvm-objdump', '-d', '-z', '--no-show-raw-insn', '--mattr=+v8.5a,+pauth', t + '/c.o'],
- capture_output=True, text=True).stdout.splitlines()
- k = 0
- for l in out:
- l = l.strip()
- if ':' in l and l.split(':')[0].strip().isalnum() and '\t' in l:
- print('%x %s' % (va + 4 * k, l.split(':', 1)[1].strip())); k += 1
+ code = code[:len(code) & ~3] # whole instructions (a length that is not a multiple of 4)
+ # an arm64e object whose __text is this code AT va: the disassembler then gives every pc-relative operand (bl, b.cond,
+ # cbz, tbz, adr, adrp, ldr of a literal) as the address in the collection it is, not as an offset into a scratch file
+ obj = struct.pack('<8I', 0xfeedfacf, 0x100000c, 2, 1, 1, 152, 0, 0) + \
+ struct.pack('<II16s4Q4I', 0x19, 152, b'', va, len(code), 184, len(code), 7, 7, 1, 0) + \
+ struct.pack('<16s16s2Q8I', b'__text', b'__TEXT', va, len(code), 184, 2, 0, 0, 0x80000400, 0, 0, 0) + code
+ objdump = shutil.which('llvm-objdump') or shutil.which('xcrun') and subprocess.run(
+ ['xcrun', '-f', 'llvm-objdump'], capture_output=True, text=True).stdout.strip()
+ if not objdump:
+ sys.exit('kcdis: no llvm-objdump (on the path, or Xcode\'s)')
+ with tempfile.TemporaryDirectory() as t:
+ open(t + '/c.o', 'wb').write(obj)
+ # -z: a run of zero words is one '...' line otherwise
+ r = subprocess.run([objdump, '-d', '-z', '--no-show-raw-insn', '--mattr=+v8.5a,+pauth', t + '/c.o'],
+ capture_output=True, text=True)
+ if r.returncode:
+ sys.exit('kcdis: ' + r.stderr.strip())
+ for l in r.stdout.splitlines():
+ a, _, insn = l.strip().partition(':')
+ if '\t' in insn and re.fullmatch('[0-9a-f]+', a):
+ print('%x %s' % (int(a, 16), re.sub(r' <[^>]*>$', '', insn.strip()))) # (<__text+0x..>: its place in c.o)
sys.exit(0)
off += sz
print('va not found')
diff --git a/tools/dev/kcstrs.py b/tools/dev/kcstrs.py
index 1bdc51f..4dfa2ae 100644
--- a/tools/dev/kcstrs.py
+++ b/tools/dev/kcstrs.py
@@ -19,7 +19,10 @@ def rd(va, k):
regs = {}
for i in range(0, n, 4):
va = va0 + i
- w = struct.unpack('<I', rd(va, 4))[0]
+ w = rd(va, 4)
+ if w is None or len(w) < 4:
+ print('%x: va not found' % va); break
+ w = struct.unpack('<I', w)[0]
if (w & 0x9f000000) == 0x90000000: # adrp
rd_ = w & 31; immlo = (w >> 29) & 3; immhi = (w >> 5) & 0x7ffff
imm = (immhi << 2) | immlo
@@ -28,7 +31,7 @@ for i in range(0, n, 4):
elif (w & 0xffc00000) == 0x91000000: # add xd, xn, #imm12
rd_, rn = w & 31, (w >> 5) & 31; imm = (w >> 10) & 0xfff
if rn in regs:
- t = regs[rn] + imm
+ t = regs[rd_] = regs[rn] + imm # (xd holds that address now: an add from it is from there, not from the page)
s = rd(t, 96) or b''
s = s.split(b'\0')[0]
pr = s.decode('latin1') if s and all(32 <= c < 127 for c in s) else ''
diff --git a/tools/hosted/xnu-input.py b/tools/hosted/xnu-input.py
index d7a4b66..70ad664 100644
--- a/tools/hosted/xnu-input.py
+++ b/tools/hosted/xnu-input.py
@@ -9,7 +9,7 @@
drag X1 Y1 X2 Y2 left-button drag
scroll N wheel N notches (negative: down)
type TEXT type TEXT (US layout)
- key NAME... press and release keys together (e.g. key cmd space, key return)
+ key NAME... press and release keys together (e.g. key cmd space, key return, key cmd ,)
sleep SECONDS
Several commands can follow one another: xnu-input.py click 640 400 type hello key return
"""
@@ -35,6 +35,17 @@ SHIFTED = {'!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7',
'+': '=', '{': '[', '}': ']', ':': ';', '"': "'", '~': '`', '|': '\\', '<': ',', '>': '.', '?': '/'}
+def chord(ch):
+ """The keys that type ch on a US layout (shift first), or None when no key does."""
+ if ch in SHIFTED:
+ return [KEYS['shift'], KEYS.get(SHIFTED[ch]) or PLAIN[SHIFTED[ch]]]
+ if ch in PLAIN:
+ return [PLAIN[ch]]
+ if len(ch) == 1 and ch.isascii() and ch.isalnum():
+ return [KEYS['shift'], KEYS[ch.lower()]] if ch.isupper() else [KEYS[ch]]
+ return None
+
+
class Input:
def __init__(self, path, width, height):
self.out, self.w, self.h = open(path, 'ab', buffering=0), width, height
@@ -65,14 +76,7 @@ class Input:
def type(self, text):
for ch in text:
- if ch in SHIFTED:
- self.keys([KEYS['shift'], KEYS.get(SHIFTED[ch]) or PLAIN[SHIFTED[ch]]])
- elif ch.isupper():
- self.keys([KEYS['shift'], KEYS[ch.lower()]])
- elif ch in KEYS:
- self.keys([KEYS[ch]])
- elif ch in PLAIN:
- self.keys([PLAIN[ch]])
+ self.keys(chord(ch))
def main(argv):
@@ -102,14 +106,22 @@ def main(argv):
for s in range(1, 11):
d.move(x1 + (x2 - x1) * s / 10, y1 + (y2 - y1) * s / 10)
d.button('left', False)
- elif cmd == 'scroll':
- d.ev(EV_REL, 8, int(argv[i])); d.syn(); i += 1
- elif cmd == 'type':
+ elif cmd == 'scroll': # XnuInput's wheel is one signed byte a report (-127..127): a longer turn goes in steps
+ n = int(argv[i]); i += 1
+ while n:
+ step = max(-127, min(127, n))
+ d.ev(EV_REL, 8, step); d.syn(); n -= step
+ elif cmd == 'type': # all of it or none: text with a character missing is not what was asked for
+ missing = sorted({ch for ch in argv[i] if chord(ch) is None})
+ if missing:
+ sys.exit(f"type: no key on the US layout for {' '.join(map(repr, missing))}")
d.type(argv[i]); i += 1
- elif cmd == 'key':
+ elif cmd == 'key': # names of KEYS, and the keys `type` knows by their character (key cmd ,)
names = []
- while i < len(argv) and argv[i] in KEYS:
- names.append(KEYS[argv[i]]); i += 1
+ while i < len(argv) and (argv[i] in KEYS or argv[i] in PLAIN):
+ names.append(KEYS.get(argv[i]) or PLAIN[argv[i]]); i += 1
+ if not names:
+ sys.exit(f"key: no key named {argv[i]!r}" if i < len(argv) else 'key: which key?')
d.keys(names)
elif cmd == 'sleep':
time.sleep(float(argv[i])); i += 1