Skip to content

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

C

Test init: the child runs Apple's /bin/sh -c (echo, uname, ls, a loop), falling back to /bin/echo; vm-sysdisk-init.sh updates the init in the system disk

Heyang Zhoub32220cb4ac6
diff --git a/scripts/vm-sysdisk-init.sh b/scripts/vm-sysdisk-init.sh
new file mode 100755
index 0000000..2cc1fa7
--- /dev/null
+++ b/scripts/vm-sysdisk-init.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+# In the VM: rebuild tools/init and put /sbin/launchd and /sbin/hello into the existing system disk image.
+set -euo pipefail
+IMG=${IMG:-/var/tmp/sys.img}
+cd ~/w/poc/tools/init; TC=~/w/dvm/toolchains/linux/bin26
+for f in start:init hello:hello; do
+ $TC/target-clang -target arm64-apple-macos14.0 -c ${f%%:*}.s -o ${f%%:*}.o
+ $TC/target-clang -target arm64-apple-macos14.0 -nostdlib -static -e _start -Wl,-adhoc_codesign ${f%%:*}.o -o ${f##*:} 2>&1 | grep -v "directory not found" || true
+done
+sudo mkdir -p /mnt/sys; sudo mount -o loop -t hfsplus $IMG /mnt/sys
+sudo cp init /mnt/sys/sbin/launchd; sudo cp hello /mnt/sys/sbin/hello; sudo chmod 755 /mnt/sys/sbin/launchd /mnt/sys/sbin/hello
+ls -la /mnt/sys/sbin /mnt/sys/private/var/select; sudo umount /mnt/sys
diff --git a/tools/init/start.s b/tools/init/start.s
index 22b1577..43a05ba 100644
--- a/tools/init/start.s
+++ b/tools/init/start.s
@@ -40,7 +40,7 @@ Lopen_again:
lsr w0, w0, #8 // WEXITSTATUS
and w0, w0, #0xff
mov x23, x0
- cmp w0, #7 // /sbin/hello exits 7, /bin/echo 0
+ cmp w0, #7 // /sbin/hello exits 7, /bin/echo and /bin/sh 0
ccmp w0, #0, #4, ne
b.ne Lbad_status
adr x1, Lmsg3
@@ -55,8 +55,21 @@ Lchild:
adr x1, Lmsg2
mov x2, #(Lmsg2_end - Lmsg2)
bl Lwrite
- adr x0, Lecho // execve("/bin/echo", {"echo", "hello from /bin/echo ...", NULL}, {NULL}): Apple's dynamically
- adr x1, Lechoarg // linked echo through dyld and the shared cache, where the root has them
+ adr x0, Lsh // execve("/bin/sh", {"sh", "-c", script, NULL}, {"PATH=/bin:/usr/bin", NULL}): Apple's shell
+ adr x9, Lsharg2 // (dyld + shared cache) where the root has it
+ stp x9, xzr, [sp, #-16]! // argv[2], argv[3] = NULL
+ adr x9, Lsh0
+ adr x10, Lsharg1
+ stp x9, x10, [sp, #-16]! // argv[0], argv[1]
+ adr x9, Lpathenv
+ stp x9, xzr, [sp, #-16]! // envp[0], envp[1] = NULL
+ add x1, sp, #16
+ mov x2, sp
+ mov x16, #59 // SYS_execve
+ svc #0x80
+ add sp, sp, #48
+ adr x0, Lecho // no /bin/sh: execve("/bin/echo", {"echo", "hello from /bin/echo ...", NULL}, {NULL})
+ adr x1, Lechoarg
stp x1, xzr, [sp, #-16]!
adr x1, Lecho0
stp xzr, x1, [sp, #-16]! // sp+0: envp NULL, sp+8: argv[0], sp+16: argv[1], sp+24: NULL
@@ -110,6 +123,16 @@ Lmsg2:
Lmsg2_end:
Lhello:
.asciz "/sbin/hello"
+Lsh:
+ .asciz "/bin/sh"
+Lsh0:
+ .asciz "sh"
+Lsharg1:
+ .asciz "-c"
+Lsharg2:
+ .asciz "echo \"hello from $0 (pid $$) on Linux\"; uname -a; ls /; for i in 1 2 3; do echo \"loop $i\"; done"
+Lpathenv:
+ .asciz "PATH=/bin:/usr/bin"
Lecho:
.asciz "/bin/echo"
Lecho0: