Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Merge PR #45 (unlock VM) and PR #46 (tool compat fallbacks)

Lakrd179b4f6beb3
diff --git a/Makefile b/Makefile
index d694d2e7..81e4ce8e 100644
--- a/Makefile
+++ b/Makefile
@@ -37,6 +37,8 @@ help:
@echo " make build Build + sign vphone-cli"
@echo " make install Build + copy to ./bin/"
@echo " make clean Remove .build/"
+ @echo " make unlock Cross-compile unlock for arm64-ios"
+ @echo " make unlock_deploy Build + deploy unlock to VM via SSH"
@echo ""
@echo "VM management:"
@echo " make vm_new Create VM directory"
@@ -81,7 +83,7 @@ setup_libimobiledevice:
# Build
# ═══════════════════════════════════════════════════════════════════
-.PHONY: build install clean
+.PHONY: build install clean unlock unlock_deploy
build: $(BINARY)
@@ -102,6 +104,24 @@ clean:
swift package clean
rm -rf .build
+unlock:
+ clang -arch arm64 -target arm64-apple-ios15.0 \
+ -o $(VM_DIR)/unlock $(SCRIPTS)/unlock.c
+ $(VM_DIR)/cfw_input/tools/ldid_macosx_arm64 -S$(SCRIPTS)/unlock.entitlements -M -K$(VM_DIR)/cfw_input/signcert.p12 $(VM_DIR)/unlock
+ @echo "Built $(VM_DIR)/unlock (arm64-ios)"
+
+SSHPASS := $(VM_DIR)/cfw_input/tools/sshpass
+SSH_PASS := alpine
+VM_SSH_PORT := 22222
+VM_SSH_HOST := root@localhost
+VM_SSH_OPTS := -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=3 -q
+
+unlock_deploy: unlock
+ @echo "[*] Deploying unlock to localhost:/var/root/unlock..."
+ $(SSHPASS) -p $(SSH_PASS) ssh $(VM_SSH_OPTS) -p $(VM_SSH_PORT) $(VM_SSH_HOST) \
+ '/iosbinpack64/bin/cat > /var/root/unlock && /iosbinpack64/bin/chmod +x /var/root/unlock' < $(VM_DIR)/unlock
+ @echo "[+] Deployed"
+
# ═══════════════════════════════════════════════════════════════════
# VM management
# ═══════════════════════════════════════════════════════════════════
@@ -177,8 +197,8 @@ ramdisk_send:
.PHONY: cfw_install cfw_install_jb
-cfw_install:
+cfw_install: unlock
cd $(VM_DIR) && zsh "$(CURDIR)/$(SCRIPTS)/cfw_install.sh" .
-cfw_install_jb:
+cfw_install_jb: unlock
cd $(VM_DIR) && zsh "$(CURDIR)/$(SCRIPTS)/cfw_install_jb.sh" .
diff --git a/scripts/cfw_install.sh b/scripts/cfw_install.sh
index 7399e647..ad86ae43 100755
--- a/scripts/cfw_install.sh
+++ b/scripts/cfw_install.sh
@@ -33,6 +33,7 @@ SSH_PORT=2222
SSH_PASS="alpine"
SSH_USER="root"
SSH_HOST="localhost"
+SSHPASS_BIN=""
SSH_OPTS=(
-o StrictHostKeyChecking=no
-o UserKnownHostsFile=/dev/null
@@ -44,8 +45,56 @@ SSH_OPTS=(
# ── Helpers ─────────────────────────────────────────────────────
die() { echo "[-] $*" >&2; exit 1; }
+is_exec_compatible() {
+ local bin="$1"
+ local host_arch file_out archs
+
+ [[ -x "$bin" ]] || return 1
+ host_arch="$(uname -m)"
+ file_out="$(file "$bin" 2>/dev/null || true)"
+
+ # Non Mach-O executables (scripts/wrappers) are accepted.
+ if [[ "$file_out" != *"Mach-O"* ]]; then
+ return 0
+ fi
+
+ if command -v lipo >/dev/null 2>&1; then
+ archs="$(lipo -archs "$bin" 2>/dev/null || true)"
+ [[ -n "$archs" && " $archs " == *" $host_arch "* ]] && return 0
+ return 1
+ fi
+
+ [[ "$file_out" == *"$host_arch"* || "$file_out" == *"universal"* ]]
+}
+
+resolve_sshpass() {
+ local bundled="$VM_DIR/$CFW_INPUT/tools/sshpass"
+ local host_sshpass
+ host_sshpass="$(command -v sshpass 2>/dev/null || true)"
+
+ if is_exec_compatible "$bundled"; then
+ SSHPASS_BIN="$bundled"
+ echo "[+] Using bundled sshpass: $SSHPASS_BIN"
+ return
+ fi
+
+ if [[ -x "$bundled" ]]; then
+ echo "[!] Bundled sshpass is not compatible with host arch ($(uname -m)): $bundled"
+ fi
+
+ if [[ -n "$host_sshpass" ]] && is_exec_compatible "$host_sshpass"; then
+ SSHPASS_BIN="$host_sshpass"
+ echo "[+] Using host sshpass: $SSHPASS_BIN"
+ return
+ fi
+
+ [[ -n "$host_sshpass" ]] && \
+ echo "[!] Host sshpass is present but incompatible with host arch: $host_sshpass"
+ die "No compatible sshpass found. Install one with: brew install hudochenkov/sshpass/sshpass"
+}
+
_sshpass() {
- "sshpass" -p "$SSH_PASS" "$@"
+ "$SSHPASS_BIN" -p "$SSH_PASS" "$@"
}
ssh_cmd() {
@@ -137,6 +186,7 @@ echo "[+] Restore directory: $RESTORE_DIR"
setup_cfw_input
INPUT_DIR="$VM_DIR/$CFW_INPUT"
echo "[+] Input resources: $INPUT_DIR"
+resolve_sshpass
mkdir -p "$TEMP_DIR"
@@ -292,6 +342,19 @@ ssh_cmd "/bin/rm -f /mnt1/iosbinpack64.tar"
echo " [+] iosbinpack64 installed"
+# ═══════════ 4.5 INSTALL VPHOME (unlock tool) ════════════════
+UNLOCK_BIN="$VM_DIR/unlock"
+if [[ -f "$UNLOCK_BIN" ]]; then
+ echo ""
+ echo "[*] Installing unlock..."
+ scp_to "$UNLOCK_BIN" "/mnt1/iosbinpack64/bin/unlock"
+ ssh_cmd "/bin/chmod 0755 /mnt1/iosbinpack64/bin/unlock"
+ echo " [+] unlock installed to /iosbinpack64/bin/unlock"
+else
+ echo ""
+ echo "[*] Skipping unlock (not built — run 'make unlock' first)"
+fi
+
# ═══════════ 5/7 PATCH LAUNCHD_CACHE_LOADER ══════════════════
echo ""
echo "[5/7] Patching launchd_cache_loader..."
diff --git a/scripts/cfw_install_jb.sh b/scripts/cfw_install_jb.sh
index 9ab7eb62..fde05c8b 100755
--- a/scripts/cfw_install_jb.sh
+++ b/scripts/cfw_install_jb.sh
@@ -39,6 +39,7 @@ SSH_PORT=2222
SSH_PASS="alpine"
SSH_USER="root"
SSH_HOST="localhost"
+SSHPASS_BIN=""
SSH_OPTS=(
-o StrictHostKeyChecking=no
-o UserKnownHostsFile=/dev/null
@@ -50,8 +51,56 @@ SSH_OPTS=(
# ── Helpers ─────────────────────────────────────────────────────
die() { echo "[-] $*" >&2; exit 1; }
+is_exec_compatible() {
+ local bin="$1"
+ local host_arch file_out archs
+
+ [[ -x "$bin" ]] || return 1
+ host_arch="$(uname -m)"
+ file_out="$(file "$bin" 2>/dev/null || true)"
+
+ # Non Mach-O executables (scripts/wrappers) are accepted.
+ if [[ "$file_out" != *"Mach-O"* ]]; then
+ return 0
+ fi
+
+ if command -v lipo >/dev/null 2>&1; then
+ archs="$(lipo -archs "$bin" 2>/dev/null || true)"
+ [[ -n "$archs" && " $archs " == *" $host_arch "* ]] && return 0
+ return 1
+ fi
+
+ [[ "$file_out" == *"$host_arch"* || "$file_out" == *"universal"* ]]
+}
+
+resolve_sshpass() {
+ local bundled="$VM_DIR/$CFW_INPUT/tools/sshpass"
+ local host_sshpass
+ host_sshpass="$(command -v sshpass 2>/dev/null || true)"
+
+ if is_exec_compatible "$bundled"; then
+ SSHPASS_BIN="$bundled"
+ echo "[+] Using bundled sshpass: $SSHPASS_BIN"
+ return
+ fi
+
+ if [[ -x "$bundled" ]]; then
+ echo "[!] Bundled sshpass is not compatible with host arch ($(uname -m)): $bundled"
+ fi
+
+ if [[ -n "$host_sshpass" ]] && is_exec_compatible "$host_sshpass"; then
+ SSHPASS_BIN="$host_sshpass"
+ echo "[+] Using host sshpass: $SSHPASS_BIN"
+ return
+ fi
+
+ [[ -n "$host_sshpass" ]] && \
+ echo "[!] Host sshpass is present but incompatible with host arch: $host_sshpass"
+ die "No compatible sshpass found. Install one with: brew install hudochenkov/sshpass/sshpass"
+}
+
_sshpass() {
- "sshpass" -p "$SSH_PASS" "$@"
+ "$SSHPASS_BIN" -p "$SSH_PASS" "$@"
}
ssh_cmd() {
@@ -108,6 +157,7 @@ setup_cfw_jb_input
JB_INPUT_DIR="$VM_DIR/$CFW_JB_INPUT"
echo ""
echo "[+] JB input resources: $JB_INPUT_DIR"
+resolve_sshpass
mkdir -p "$TEMP_DIR"
diff --git a/scripts/ramdisk_build.py b/scripts/ramdisk_build.py
index 3e603acc..544811a4 100755
--- a/scripts/ramdisk_build.py
+++ b/scripts/ramdisk_build.py
@@ -22,6 +22,7 @@ Prerequisites:
import gzip
import glob
import os
+import platform
import plistlib
import shutil
import subprocess
@@ -155,6 +156,56 @@ def run(cmd, **kwargs):
return subprocess.run(cmd, check=True, **kwargs)
+def is_exec_compatible(path):
+ """Return True if an executable is usable on this host arch."""
+ if not path or not os.path.isfile(path) or not os.access(path, os.X_OK):
+ return False
+
+ file_out = subprocess.run(
+ ["file", path], capture_output=True, text=True
+ ).stdout
+
+ # Non-Mach-O executables (scripts/wrappers) are accepted.
+ if "Mach-O" not in file_out:
+ return True
+
+ host_arch = platform.machine()
+ try:
+ archs = subprocess.run(
+ ["lipo", "-archs", path], capture_output=True, text=True, check=True
+ ).stdout.split()
+ return host_arch in archs
+ except Exception:
+ return host_arch in file_out or "universal" in file_out
+
+
+def resolve_tar_extractor(input_dir):
+ """Select tar tool with compatibility fallback and clear diagnostics."""
+ bundled_gtar = os.path.join(input_dir, "tools/gtar")
+ host_gtar = shutil.which("gtar")
+ host_tar = shutil.which("tar")
+ host_arch = platform.machine()
+
+ if is_exec_compatible(bundled_gtar):
+ return bundled_gtar, True, "bundled gtar"
+ if os.path.exists(bundled_gtar):
+ print(f" [!] Bundled gtar is not compatible with host arch ({host_arch}): {bundled_gtar}")
+
+ if host_gtar and is_exec_compatible(host_gtar):
+ return host_gtar, True, "host gtar"
+ if host_gtar:
+ print(f" [!] Host gtar is present but incompatible with host arch ({host_arch}): {host_gtar}")
+
+ if host_tar and is_exec_compatible(host_tar):
+ return host_tar, False, "host tar"
+ if host_tar:
+ print(f" [!] Host tar is present but incompatible with host arch ({host_arch}): {host_tar}")
+
+ print("[-] No compatible tar extractor found.")
+ print(" Install GNU tar with: brew install gnu-tar")
+ sys.exit(1)
+
+
# ══════════════════════════════════════════════════════════════════
# Firmware extraction and IM4P creation
# ══════════════════════════════════════════════════════════════════
@@ -223,6 +274,9 @@ def build_ramdisk(restore_dir, im4m_path, vm_dir, input_dir, output_dir, temp_di
mountpoint = os.path.join(vm_dir, "SSHRD")
ramdisk_raw = os.path.join(temp_dir, "ramdisk.raw.dmg")
ramdisk_custom = os.path.join(temp_dir, "ramdisk1.dmg")
+ tar_bin, tar_is_gnu, tar_label = resolve_tar_extractor(input_dir)
+
+ print(f" Using archive extractor: {tar_label} ({tar_bin})")
# Extract base ramdisk
print(" Extracting base ramdisk...")
@@ -252,8 +306,11 @@ def build_ramdisk(restore_dir, im4m_path, vm_dir, input_dir, output_dir, temp_di
print(" Injecting SSH tools...")
ssh_tar = os.path.join(input_dir, "ssh.tar.gz")
- run(["sudo", "gtar", "-x", "--no-overwrite-dir",
- "-f", ssh_tar, "-C", mountpoint])
+ extract_cmd = ["sudo", tar_bin, "-x", "-f", ssh_tar, "-C", mountpoint]
+ if tar_is_gnu:
+ extract_cmd = ["sudo", tar_bin, "-x", "--no-overwrite-dir",
+ "-f", ssh_tar, "-C", mountpoint]
+ run(extract_cmd)
# Remove unnecessary files
for rel_path in RAMDISK_REMOVE:
diff --git a/scripts/unlock.c b/scripts/unlock.c
new file mode 100644
index 00000000..c602a437
--- /dev/null
+++ b/scripts/unlock.c
@@ -0,0 +1,119 @@
+// unlock — dispatch Consumer Menu (Home) IOHIDEvent from inside the VM
+// Replicates TrollVNC STHIDEventGenerator._sendHIDEvent pattern:
+// - dispatch_once client creation
+// - dispatch_async on serial queue with setSenderID inside block
+
+#include <dlfcn.h>
+#include <dispatch/dispatch.h>
+#include <mach/mach_time.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+typedef const void *CFTypeRef;
+typedef const void *CFAllocatorRef;
+
+#define kHIDPage_Consumer 0x0C
+#define kHIDUsage_Csmr_Menu 0x40
+#define kIOHIDEventOptionNone 0
+
+typedef CFTypeRef (*CreateClient_t)(CFAllocatorRef);
+typedef CFTypeRef (*CreateKbEvent_t)(CFAllocatorRef, uint64_t, uint32_t, uint32_t, int, uint32_t);
+typedef void (*SetSenderID_t)(CFTypeRef, uint64_t);
+typedef void (*DispatchEvent_t)(CFTypeRef, CFTypeRef);
+typedef void (*CFRelease_t)(CFTypeRef);
+typedef CFTypeRef (*CFRetain_t)(CFTypeRef);
+
+static CreateClient_t g_createClient;
+static CreateKbEvent_t g_createKbEvent;
+static SetSenderID_t g_setSenderID;
+static DispatchEvent_t g_dispatchEvent;
+static CFRelease_t g_cfRelease;
+static CFRetain_t g_cfRetain;
+static CFAllocatorRef g_alloc;
+
+static CFTypeRef get_client(void) {
+ static CFTypeRef client = NULL;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ client = g_createClient(g_alloc);
+ printf("[unlock] client=%p\n", client);
+ });
+ return client;
+}
+
+static void send_hid_event(CFTypeRef event, dispatch_queue_t queue) {
+ if (!event) return;
+ CFTypeRef retained = g_cfRetain(event);
+ dispatch_async(queue, ^{
+ g_setSenderID(retained, 0x8000000817319372ULL);
+ g_dispatchEvent(get_client(), retained);
+ g_cfRelease(retained);
+ });
+}
+
+int main(void) {
+ void *cf = dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", RTLD_NOW);
+ if (!cf) { fprintf(stderr, "[unlock] dlopen CF: %s\n", dlerror()); return 1; }
+
+ g_cfRelease = (CFRelease_t)dlsym(cf, "CFRelease");
+ g_cfRetain = (CFRetain_t)dlsym(cf, "CFRetain");
+ CFAllocatorRef *pAlloc = (CFAllocatorRef *)dlsym(cf, "kCFAllocatorDefault");
+ if (!g_cfRelease || !g_cfRetain || !pAlloc) { fprintf(stderr, "[unlock] CF syms\n"); return 1; }
+ g_alloc = *pAlloc;
+
+ void *iokit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);
+ if (!iokit) { fprintf(stderr, "[unlock] dlopen IOKit: %s\n", dlerror()); return 1; }
+
+ g_createClient = (CreateClient_t)dlsym(iokit, "IOHIDEventSystemClientCreate");
+ g_createKbEvent = (CreateKbEvent_t)dlsym(iokit, "IOHIDEventCreateKeyboardEvent");
+ g_setSenderID = (SetSenderID_t)dlsym(iokit, "IOHIDEventSetSenderID");
+ g_dispatchEvent = (DispatchEvent_t)dlsym(iokit, "IOHIDEventSystemClientDispatchEvent");
+
+ if (!g_createClient || !g_createKbEvent || !g_setSenderID || !g_dispatchEvent) {
+ fprintf(stderr, "[unlock] IOKit syms\n"); return 1;
+ }
+
+ dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(
+ DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0);
+ dispatch_queue_t queue = dispatch_queue_create("com.unlock.hid-events", attr);
+
+ printf("[unlock] sending Menu (Home) x2 (1.5s gap)...\n");
+
+ // First press — wakes screen
+ CFTypeRef d1 = g_createKbEvent(g_alloc, mach_absolute_time(),
+ kHIDPage_Consumer, kHIDUsage_Csmr_Menu, 1, kIOHIDEventOptionNone);
+ send_hid_event(d1, queue);
+ g_cfRelease(d1);
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC), queue, ^{
+ CFTypeRef u1 = g_createKbEvent(g_alloc, mach_absolute_time(),
+ kHIDPage_Consumer, kHIDUsage_Csmr_Menu, 0, kIOHIDEventOptionNone);
+ send_hid_event(u1, queue);
+ g_cfRelease(u1);
+
+ // Second press — unlocks (1.5s delay avoids App Switcher double-tap)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1500 * NSEC_PER_MSEC), queue, ^{
+ CFTypeRef d2 = g_createKbEvent(g_alloc, mach_absolute_time(),
+ kHIDPage_Consumer, kHIDUsage_Csmr_Menu, 1, kIOHIDEventOptionNone);
+ send_hid_event(d2, queue);
+ g_cfRelease(d2);
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC), queue, ^{
+ CFTypeRef u2 = g_createKbEvent(g_alloc, mach_absolute_time(),
+ kHIDPage_Consumer, kHIDUsage_Csmr_Menu, 0, kIOHIDEventOptionNone);
+ send_hid_event(u2, queue);
+ g_cfRelease(u2);
+
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC), queue, ^{
+ printf("[unlock] done\n");
+ exit(0);
+ });
+ });
+ });
+ });
+
+ dispatch_main();
+ return 0;
+}
diff --git a/scripts/unlock.entitlements b/scripts/unlock.entitlements
new file mode 100644
index 00000000..d48ff8ca
--- /dev/null
+++ b/scripts/unlock.entitlements
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>platform-application</key>
+ <true/>
+ <key>com.apple.private.security.no-container</key>
+ <true/>
+ <key>com.apple.private.hid.client.event-dispatch</key>
+ <true/>
+ <key>com.apple.private.hid.client.event-filter</key>
+ <true/>
+ <key>com.apple.private.hid.client.event-monitor</key>
+ <true/>
+ <key>com.apple.private.hid.client.service-protected</key>
+ <true/>
+ <key>com.apple.private.hid.manager.client</key>
+ <true/>
+ <key>com.apple.backboard.client</key>
+ <true/>
+</dict>
+</plist>
diff --git a/sources/vphone-cli/VPhoneAppDelegate.swift b/sources/vphone-cli/VPhoneAppDelegate.swift
index 0e5cdcd4..f117b549 100644
--- a/sources/vphone-cli/VPhoneAppDelegate.swift
+++ b/sources/vphone-cli/VPhoneAppDelegate.swift
@@ -83,7 +83,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {
try await vm.start(forceDFU: cli.dfu)
if !cli.noGraphics {
- let keyHelper = VPhoneKeyHelper(vm: vm.virtualMachine)
+ let keyHelper = VPhoneKeyHelper(vm: vm.virtualMachine, serialWriteHandle: vm.serialWriteHandle)
let wc = VPhoneWindowController()
wc.showWindow(
for: vm.virtualMachine,
@@ -94,6 +94,10 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {
)
windowController = wc
menuController = VPhoneMenuController(keyHelper: keyHelper)
+
+ if !cli.dfu {
+ keyHelper.autoUnlock(delay: 8)
+ }
}
}
diff --git a/sources/vphone-cli/VPhoneKeyHelper.swift b/sources/vphone-cli/VPhoneKeyHelper.swift
index d631e792..b54acd26 100644
--- a/sources/vphone-cli/VPhoneKeyHelper.swift
+++ b/sources/vphone-cli/VPhoneKeyHelper.swift
@@ -8,6 +8,7 @@ import Virtualization
@MainActor
class VPhoneKeyHelper {
private let vm: VZVirtualMachine
+ private let serialWriteHandle: FileHandle?
/// First _VZKeyboard from the VM's internal keyboard array.
private var firstKeyboard: AnyObject? {
@@ -26,8 +27,9 @@ class VPhoneKeyHelper {
return 1
}
- init(vm: VZVirtualMachine) {
+ init(vm: VZVirtualMachine, serialWriteHandle: FileHandle? = nil) {
self.vm = vm
+ self.serialWriteHandle = serialWriteHandle
}
// MARK: - Send Key via _VZKeyEvent
@@ -101,6 +103,29 @@ class VPhoneKeyHelper {
}
}
+ // MARK: - Unlock via Serial Console
+
+ /// Send unlock command through the serial port to trigger Home button unlock.
+ func sendUnlock() {
+ print("[unlock] Sending unlock via serial console")
+ writeSerial("/var/root/unlock 2>/dev/null || /iosbinpack64/bin/unlock\n")
+ }
+
+ /// Auto-unlock: send unlock once after `delay` seconds via serial.
+ /// The command buffers in the pipe and executes when bash is ready.
+ func autoUnlock(delay: TimeInterval = 8) {
+ print("[unlock] Auto-unlock: sending unlock in \(Int(delay))s")
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
+ self?.writeSerial("/var/root/unlock 2>/dev/null || /iosbinpack64/bin/unlock\n")
+ }
+ }
+
+ private func writeSerial(_ command: String) {
+ guard let data = command.data(using: .utf8) else { return }
+ guard let handle = serialWriteHandle else { return }
+ handle.write(data)
+ }
+
// MARK: - Named Key Actions
/// iOS hardware keyboard shortcuts (Cmd-based, Fn has no table entry in _VZKeyEvent)
diff --git a/sources/vphone-cli/VPhoneMenuController.swift b/sources/vphone-cli/VPhoneMenuController.swift
index 1cd5cae3..436941fd 100644
--- a/sources/vphone-cli/VPhoneMenuController.swift
+++ b/sources/vphone-cli/VPhoneMenuController.swift
@@ -30,6 +30,7 @@ class VPhoneMenuController {
// iOS hardware keyboard shortcuts
keysMenu.addItem(makeItem("Home Screen (Cmd+H)", action: #selector(sendHome)))
+ keysMenu.addItem(makeItem("Unlock", action: #selector(sendUnlock)))
keysMenu.addItem(makeItem("Spotlight (Cmd+Space)", action: #selector(sendSpotlight)))
keysMenu.addItem(NSMenuItem.separator())
keysMenu.addItem(makeItem("Return", action: #selector(sendReturn)))
@@ -75,6 +76,10 @@ class VPhoneMenuController {
keyHelper.sendHome()
}
+ @objc private func sendUnlock() {
+ keyHelper.sendUnlock()
+ }
+
@objc private func sendSpotlight() {
keyHelper.sendSpotlight()
}
diff --git a/sources/vphone-cli/VPhoneVM.swift b/sources/vphone-cli/VPhoneVM.swift
index 26d1c98f..57468209 100644
--- a/sources/vphone-cli/VPhoneVM.swift
+++ b/sources/vphone-cli/VPhoneVM.swift
@@ -6,6 +6,10 @@ import Virtualization
@MainActor
class VPhoneVM: NSObject, VZVirtualMachineDelegate {
let virtualMachine: VZVirtualMachine
+ /// Write handle to inject commands into the VM's serial console.
+ private(set) var serialWriteHandle: FileHandle?
+ /// Read handle for VM serial output.
+ private var serialOutputReadHandle: FileHandle?
struct Options {
var romURL: URL
@@ -102,12 +106,31 @@ class VPhoneVM: NSObject, VZVirtualMachineDelegate {
net.attachment = VZNATNetworkDeviceAttachment()
config.networkDevices = [net]
- // Serial port (PL011 UART — interactive stdin/stdout)
+ // Serial port (PL011 UART — pipes for input/output with boot detection)
if let serialPort = Dynamic._VZPL011SerialPortConfiguration().asObject as? VZSerialPortConfiguration {
+ let inputPipe = Pipe()
+ let outputPipe = Pipe()
+ serialWriteHandle = inputPipe.fileHandleForWriting
+
serialPort.attachment = VZFileHandleSerialPortAttachment(
- fileHandleForReading: FileHandle.standardInput,
- fileHandleForWriting: FileHandle.standardOutput
+ fileHandleForReading: inputPipe.fileHandleForReading,
+ fileHandleForWriting: outputPipe.fileHandleForWriting
)
+
+ // Forward host stdin → VM serial input
+ let writeHandle = inputPipe.fileHandleForWriting
+ let stdinFD = FileHandle.standardInput.fileDescriptor
+ DispatchQueue.global(qos: .userInteractive).async {
+ var buf = [UInt8](repeating: 0, count: 4096)
+ while true {
+ let n = read(stdinFD, &buf, buf.count)
+ if n <= 0 { break }
+ writeHandle.write(Data(buf[..<n]))
+ }
+ }
+
+ serialOutputReadHandle = outputPipe.fileHandleForReading
+
config.serialPorts = [serialPort]
print("[vphone] PL011 serial port attached (interactive)")
}
@@ -139,6 +162,15 @@ class VPhoneVM: NSObject, VZVirtualMachineDelegate {
virtualMachine = VZVirtualMachine(configuration: config)
super.init()
virtualMachine.delegate = self
+
+ // Forward VM serial output → host stdout
+ if let readHandle = serialOutputReadHandle {
+ readHandle.readabilityHandler = { handle in
+ let data = handle.availableData
+ if data.isEmpty { return }
+ FileHandle.standardOutput.write(data)
+ }
+ }
}
// MARK: - Start
diff --git a/sources/vphone-cli/VPhoneVMView.swift b/sources/vphone-cli/VPhoneVMView.swift
index d7a37ee1..7df76bda 100644
--- a/sources/vphone-cli/VPhoneVMView.swift
+++ b/sources/vphone-cli/VPhoneVMView.swift
@@ -5,16 +5,16 @@ import Virtualization
class VPhoneVMView: VZVirtualMachineView {
var keyHelper: VPhoneKeyHelper?
-
+
private var currentTouchSwipeAim: Int = 0
// MARK: - Private API Accessors
- // https://github.com/wh1te4ever/super-tart-vphone-writeup/blob/main/contents/ScreenSharingVNC.swift
+ /// https://github.com/wh1te4ever/super-tart-vphone-writeup/blob/main/contents/ScreenSharingVNC.swift
private var multiTouchDevice: AnyObject? {
- guard let vm = self.virtualMachine else { return nil }
+ guard let vm = virtualMachine else { return nil }
guard let devices = Dynamic(vm)._multiTouchDevices.asObject as? NSArray,
- devices.count > 0
+ devices.count > 0
else {
return nil
}
@@ -24,10 +24,13 @@ class VPhoneVMView: VZVirtualMachineView {
// MARK: - Event Handling
override func mouseDown(with event: NSEvent) {
- let localPoint = self.convert(event.locationInWindow, from: nil)
-
- self.currentTouchSwipeAim = hitTestEdge(at: localPoint)
-
+ // macOS 16+: VZVirtualMachineView handles mouse-to-touch natively
+ if #available(macOS 16.0, *) { super.mouseDown(with: event); return }
+
+ let localPoint = convert(event.locationInWindow, from: nil)
+
+ currentTouchSwipeAim = hitTestEdge(at: localPoint)
+
sendTouchEvent(
phase: 0, // Began
localPoint: localPoint,
@@ -36,7 +39,9 @@ class VPhoneVMView: VZVirtualMachineView {
}
override func mouseDragged(with event: NSEvent) {
- let localPoint = self.convert(event.locationInWindow, from: nil)
+ if #available(macOS 16.0, *) { super.mouseDragged(with: event); return }
+
+ let localPoint = convert(event.locationInWindow, from: nil)
sendTouchEvent(
phase: 1, // Moved
localPoint: localPoint,
@@ -46,13 +51,15 @@ class VPhoneVMView: VZVirtualMachineView {
}
override func mouseUp(with event: NSEvent) {
- let localPoint = self.convert(event.locationInWindow, from: nil)
+ if #available(macOS 16.0, *) { super.mouseUp(with: event); return }
+
+ let localPoint = convert(event.locationInWindow, from: nil)
sendTouchEvent(
phase: 3, // Ended
localPoint: localPoint,
timestamp: event.timestamp
)
- self.currentTouchSwipeAim = 0
+ currentTouchSwipeAim = 0
super.mouseUp(with: event)
}
@@ -64,11 +71,11 @@ class VPhoneVMView: VZVirtualMachineView {
keyHelper.sendHome()
}
- // MARK: - Touch Injection Logic
+ // MARK: - Legacy Touch Injection (macOS 15)
private func sendTouchEvent(phase: Int, localPoint: NSPoint, timestamp: TimeInterval) {
guard let device = multiTouchDevice,
- self.virtualMachine != nil
+ virtualMachine != nil
else { return }
let normalizedPoint = normalizeCoordinate(localPoint)
@@ -96,8 +103,8 @@ class VPhoneVMView: VZVirtualMachineView {
// MARK: - Coordinate Helpers
private func normalizeCoordinate(_ localPoint: NSPoint) -> CGPoint {
- let w = self.bounds.width
- let h = self.bounds.height
+ let w = bounds.width
+ let h = bounds.height
guard w > 0, h > 0 else { return .zero }
@@ -108,7 +115,7 @@ class VPhoneVMView: VZVirtualMachineView {
nx = max(0.0, min(1.0, nx))
ny = max(0.0, min(1.0, ny))
- if !self.isFlipped {
+ if !isFlipped {
ny = 1.0 - ny
}
@@ -116,15 +123,15 @@ class VPhoneVMView: VZVirtualMachineView {
}
private func hitTestEdge(at point: CGPoint) -> Int {
- let w = self.bounds.width
- let h = self.bounds.height
-
+ let w = bounds.width
+ let h = bounds.height
+
let edgeThreshold: CGFloat = 32.0
-
+
let distLeft = point.x
let distRight = w - point.x
- let distTop = self.isFlipped ? point.y : (h - point.y)
- let distBottom = self.isFlipped ? (h - point.y) : point.y
+ let distTop = isFlipped ? point.y : (h - point.y)
+ let distBottom = isFlipped ? (h - point.y) : point.y
var minDist = distLeft
var edgeCode = 8 // Left
@@ -133,12 +140,12 @@ class VPhoneVMView: VZVirtualMachineView {
minDist = distRight
edgeCode = 4 // Right
}
-
+
if distBottom < minDist {
minDist = distBottom
edgeCode = 2 // Bottom (Home bar swipe up)
}
-
+
if distTop < minDist {
minDist = distTop
edgeCode = 1 // Top (Notification Center)