Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Expose the rest of icli through vphoned

Lakr233ce3e8fc8915a
diff --git a/VPhoneDaemon/Daemon/APIWire.swift b/VPhoneDaemon/Daemon/APIWire.swift
index 2cd682ae..dae8b71d 100644
--- a/VPhoneDaemon/Daemon/APIWire.swift
+++ b/VPhoneDaemon/Daemon/APIWire.swift
@@ -1,4 +1,5 @@
import Foundation
+import IcliSystem
import NIOCore
import NIOWebSocket
@@ -40,10 +41,15 @@ enum APIWire {
let result = try GuestAPI.execute(method: request.method, params: request.params)
return .json(["type": "response", "id": request.id ?? NSNull(), "result": result])
} catch {
- let code = error is GuestAPIError ? "invalid_operation" : "operation_failed"
+ let (code, message): (String, String) =
+ if let error = error as? IcliError {
+ (error.code, error.message)
+ } else {
+ (error is GuestAPIError ? "invalid_operation" : "operation_failed", String(describing: error))
+ }
return .json(status: 400, [
"type": "response", "id": request.id ?? NSNull(),
- "error": ["code": code, "message": String(describing: error)],
+ "error": ["code": code, "message": message],
])
}
}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift b/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift
new file mode 100644
index 00000000..c3819f7c
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift
@@ -0,0 +1,48 @@
+import Foundation
+import IcliKit
+
+// MARK: - App Detail and System Control
+
+extension GuestAPI {
+ static func executeAppDetail(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "apps.info":
+ return try appInfo(string(params, "bundle_id"))
+ case "apps.binary":
+ return try appBinaryInfo(string(params, "bundle_id"))
+ case "apps.data_dir":
+ return try appDataDir(string(params, "bundle_id"))
+ case "apps.url_schemes":
+ return try appURLSchemes()
+ case "apps.handlers":
+ return try appHandlers(string(params, "url"))
+ case "apps.registration":
+ return try appRegistration(string(params, "path"))
+ case "apps.register":
+ return try registerApp(string(params, "path"))
+ case "apps.unregister":
+ let path = try string(params, "path")
+ try requireForce(params, "unregister \(path)")
+ return try unregisterApp(path, force: true)
+ case "apps.unregister_dir":
+ let directory = try string(params, "directory")
+ try requireForce(params, "unregister every app in \(directory)")
+ return try unregisterAppsInDirectory(directory, force: true)
+ case "apps.network_policy":
+ return try appNetworkPolicy(string(params, "bundle_id"), repair: bool(params, "repair"))
+ case "system.uicache":
+ return try refreshApps(directory: optionalString(params, "directory"))
+ case "system.system_apps":
+ return try systemAppsVisibility(set: params["visible"] as? Bool)
+ case "system.respring":
+ try requireForce(params, "restart SpringBoard")
+ return try respring()
+ case "system.reboot":
+ let userspace = bool(params, "userspace")
+ try requireForce(params, userspace ? "restart userspace" : "reboot the guest")
+ return try requestReboot(userspace: userspace, force: true)
+ default:
+ return nil
+ }
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
new file mode 100644
index 00000000..2a0b8c62
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
@@ -0,0 +1,73 @@
+import Foundation
+import IcliKit
+import IcliSystem
+
+// MARK: - Device, Display, Audio, Network
+
+extension GuestAPI {
+ static func executeDevice(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "device.info":
+ var info = try collectDeviceSnapshot()
+ info["jailbreak"] = jailbreakInfo()
+ info["network"] = networkInfo()
+ info["screen"] = screenInfo()
+ info["rotation"] = rotationInfo()
+ info["brightness"] = brightnessState()
+ info["volume"] = volume()
+ info["low_power_mode"] = (try? lowPowerMode()) ?? [:]
+ info["developer_mode"] = (try? developerModeStatus()) ?? [:]
+ info["agent"] = ["binary_hash": binaryHash, "pid": getpid()]
+ return info
+ case "device.network":
+ return networkInfo()
+ case "device.ioreg":
+ return try ioregistry(plane: optionalString(params, "plane") ?? "IOService")
+ case "device.environment":
+ return try environmentReport()
+ case "device.basebin":
+ return try compareBaseBin(bundled: optionalString(params, "archive"))
+ case "display.brightness":
+ if params["value"] != nil {
+ try setBrightness(requiredNumber(params, "value"))
+ }
+ return brightnessState()
+ case "display.rotation":
+ if let orientation = optionalString(params, "orientation") {
+ return try setRotation(orientation)
+ }
+ return rotationInfo()
+ case "display.rotation_lock":
+ guard let locked = params["locked"] as? Bool else {
+ throw GuestAPIError.invalidRequest("locked must be true or false")
+ }
+ return try setRotationLock(locked)
+ case "audio.volume":
+ let category = optionalString(params, "category") ?? "Audio/Video"
+ if params["value"] != nil {
+ return try setVolume(requiredNumber(params, "value"), category: category)
+ }
+ return ["volume": volume(category), "category": category]
+ case "audio.state":
+ return try audioState()
+ case "network.capture":
+ let seconds = number(params, "seconds", default: 5)
+ let result = try capturePackets(
+ seconds: seconds,
+ interface: optionalString(params, "interface") ?? "en0",
+ filter: optionalString(params, "filter"),
+ )
+ return result
+ case "security.ssl_killswitch":
+ return sslKillswitchStatus()
+ case "diagnostics.self_test":
+ return try runSelfTests()
+ default:
+ return nil
+ }
+ }
+
+ private static func brightnessState() -> [String: Any] {
+ ["value": brightness(), "auto": autoBrightness().map { $0 as Any } ?? NSNull()]
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
new file mode 100644
index 00000000..650f9cc5
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -0,0 +1,24 @@
+import Foundation
+
+/// Methods beyond the original surface live in one file per area. Each area
+/// returns nil for a method it does not own, so the first match answers.
+extension GuestAPI {
+ static func executeExtended(method: String, params: [String: Any]) throws -> [String: Any]? {
+ let areas: [(String, [String: Any]) throws -> [String: Any]?] = [
+ executeDevice,
+ executeInput,
+ executeInterface,
+ executeProcess,
+ executeService,
+ executeLog,
+ executeAppDetail,
+ executeFileTool,
+ ]
+ for area in areas {
+ if let result = try area(method, params) {
+ return result
+ }
+ }
+ return nil
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift b/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift
new file mode 100644
index 00000000..2817377d
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+FileTool.swift
@@ -0,0 +1,89 @@
+import Foundation
+import IcliKit
+import IcliSystem
+
+// MARK: - Files, Keychain, Packages
+
+extension GuestAPI {
+ static func executeFileTool(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "files.read":
+ return try readFile(
+ string(params, "path"),
+ binary: bool(params, "binary"),
+ limit: (params["limit"] as? NSNumber)?.intValue,
+ )
+ case "files.write":
+ guard let content = params["content"] as? String else {
+ throw GuestAPIError.invalidRequest("content is required")
+ }
+ return try writeFile(
+ string(params, "path"),
+ content: content,
+ encoding: optionalString(params, "encoding") ?? "utf8",
+ )
+ case "files.find":
+ return try findFiles(root: string(params, "root"), pattern: string(params, "pattern"))
+ case "files.copy":
+ return try copyPath(string(params, "from"), to: string(params, "to"))
+ case "files.symlink":
+ return try createSymlink(
+ target: string(params, "target"),
+ link: string(params, "link"),
+ replace: bool(params, "replace"),
+ )
+ case "files.chmod":
+ return try changeMode(string(params, "path"), mode: string(params, "mode"))
+ case "files.chown":
+ return try changeOwner(string(params, "path"), owner: string(params, "owner"))
+ case "files.plist":
+ return try readPlist(string(params, "path"))
+ case "files.plist_set":
+ let json: String? =
+ if bool(params, "remove") {
+ nil
+ } else if let value = params["value"] {
+ try String(
+ decoding: JSONSerialization.data(withJSONObject: value, options: .fragmentsAllowed),
+ as: UTF8.self,
+ )
+ } else {
+ throw GuestAPIError.invalidRequest("value is required unless remove is true")
+ }
+ return try setPlistValue(string(params, "path"), key: string(params, "key"), json: json)
+ case "keychain.get":
+ return try getKeychain(
+ className: optionalString(params, "class") ?? "genp",
+ service: optionalString(params, "service"),
+ account: optionalString(params, "account"),
+ server: optionalString(params, "server"),
+ group: optionalString(params, "group"),
+ )
+ case "keychain.update":
+ return try updateKeychain(
+ className: optionalString(params, "class") ?? "genp",
+ service: optionalString(params, "service"),
+ account: string(params, "account"),
+ server: optionalString(params, "server"),
+ group: optionalString(params, "group"),
+ data: string(params, "data"),
+ )
+ case "keychain.database":
+ return try listKeychainDatabaseMetadata(className: optionalString(params, "class"))
+ case "packages.list":
+ return try listPackages(filter: optionalString(params, "filter"))
+ case "packages.status":
+ return try packageStatus(string(params, "name"))
+ case "packages.info":
+ return try readDeb(string(params, "path"))
+ case "packages.compare":
+ return try compareDebianVersions(string(params, "left"), string(params, "right"))
+ case "packages.tweaks":
+ return try listTweaks()
+ case "packages.repos":
+ return try listRepos()
+ default:
+ return nil
+ }
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Input.swift b/VPhoneDaemon/Daemon/GuestAPI+Input.swift
new file mode 100644
index 00000000..8763a401
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Input.swift
@@ -0,0 +1,109 @@
+import Foundation
+import IcliKit
+
+// MARK: - Buttons, Text, Gestures
+
+extension GuestAPI {
+ /// Gesture coordinates are screen points, as `device.screen` reports them.
+ static func executeInput(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "input.button":
+ return try pressButton(string(params, "name"))
+ case "input.key":
+ return try pressKey(string(params, "name"))
+ case "input.type":
+ return try typeText(string(params, "text"), delayMS: number(params, "delay_ms", default: 30))
+ case "input.paste":
+ return try pasteText(string(params, "text"))
+ case "input.tap":
+ return try tap(x: requiredNumber(params, "x"), y: requiredNumber(params, "y"))
+ case "input.double_tap":
+ return try doubleTap(
+ x: requiredNumber(params, "x"),
+ y: requiredNumber(params, "y"),
+ interval: number(params, "interval", default: 0.1),
+ )
+ case "input.long_press":
+ return try longPress(
+ x: requiredNumber(params, "x"),
+ y: requiredNumber(params, "y"),
+ seconds: number(params, "seconds", default: 1),
+ )
+ case "input.swipe":
+ return try swipe(
+ x1: requiredNumber(params, "x1"),
+ y1: requiredNumber(params, "y1"),
+ x2: requiredNumber(params, "x2"),
+ y2: requiredNumber(params, "y2"),
+ seconds: number(params, "seconds", default: 0.3),
+ steps: (params["steps"] as? NSNumber)?.intValue ?? 20,
+ )
+ case "input.drag":
+ guard let rows = params["points"] as? [[NSNumber]], rows.count >= 2,
+ rows.allSatisfy({ $0.count == 2 })
+ else {
+ throw GuestAPIError.invalidRequest("points must be at least two [x, y] pairs")
+ }
+ return try drag(
+ points: rows.map { ($0[0].doubleValue, $0[1].doubleValue) },
+ seconds: number(params, "seconds", default: 0.5),
+ hold: number(params, "hold", default: 0.5),
+ steps: (params["steps"] as? NSNumber)?.intValue ?? 20,
+ )
+ case "input.touch_sequence":
+ guard let events = params["events"] as? [[String: Any]] else {
+ throw GuestAPIError.invalidRequest("events must be an array of {phase, x, y, delay_ms}")
+ }
+ let json = try String(decoding: JSONSerialization.data(withJSONObject: events), as: UTF8.self)
+ return try touchSequence(
+ TouchEvent.list(fromJSON: json),
+ normalized: bool(params, "normalized", default: true),
+ )
+ default:
+ return nil
+ }
+ }
+
+ // MARK: - Accessibility and OCR
+
+ static func executeInterface(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "ui.tree", "accessibility.tree":
+ return try uiElements(
+ maxElements: (params["max_elements"] as? NSNumber)?.intValue ?? 500,
+ visibleOnly: bool(params, "visible_only", default: true),
+ clickableOnly: bool(params, "clickable_only"),
+ limit: (params["limit"] as? NSNumber)?.intValue,
+ )
+ case "ui.element_at":
+ return try elementAt(x: requiredNumber(params, "x"), y: requiredNumber(params, "y"))
+ case "ui.tap_element":
+ return try tapElement(selector(params))
+ case "ui.wait", "ui.wait_gone":
+ return try waitForElement(
+ selector(params),
+ appear: method == "ui.wait",
+ timeout: number(params, "timeout", default: 10),
+ )
+ case "ui.ocr":
+ return try recognizeScreen(
+ languages: params["languages"] as? [String] ?? ["en-US"],
+ minConfidence: Float(number(params, "min_confidence", default: 0.3)),
+ )
+ case "ui.describe":
+ return try describeScreen()
+ default:
+ return nil
+ }
+ }
+
+ private static func selector(_ params: [String: Any]) throws -> ElementSelector {
+ try ElementSelector(
+ text: optionalString(params, "text"),
+ identifier: optionalString(params, "identifier"),
+ role: optionalString(params, "role"),
+ match: optionalString(params, "match") ?? "contains",
+ index: (params["index"] as? NSNumber)?.intValue ?? 0,
+ )
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Log.swift b/VPhoneDaemon/Daemon/GuestAPI+Log.swift
new file mode 100644
index 00000000..364d400c
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Log.swift
@@ -0,0 +1,46 @@
+import Foundation
+import IcliKit
+
+// MARK: - Unified Log and Crash Reports
+
+extension GuestAPI {
+ static func executeLog(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "logs.syslog":
+ return try captureSyslog(
+ seconds: number(params, "seconds", default: 2),
+ process: optionalString(params, "process"),
+ level: optionalString(params, "level") ?? "all",
+ maxLines: (params["max_lines"] as? NSNumber)?.intValue ?? 500,
+ )
+ case "logs.crashes":
+ let paths = try crashLogs(bundleID: optionalString(params, "bundle_id"))["crashes"] as? [String] ?? []
+ let reports = paths.map { path -> [String: Any] in
+ let name = (path as NSString).lastPathComponent
+ let attributes = try? FileManager.default.attributesOfItem(atPath: path)
+ return [
+ "path": path,
+ "name": name,
+ "process": crashProcessName(name),
+ "size": attributes?[.size] as? Int ?? 0,
+ "mtime": (attributes?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0,
+ ]
+ }
+ return ["crashes": reports, "count": reports.count]
+ case "logs.crash":
+ return try readCrashLog(string(params, "path"))
+ default:
+ return nil
+ }
+ }
+
+ /// Crash report names start with the process name, then a date or a kind:
+ /// `SpringBoard-2026-09-25-101500.ips`, `JetsamEvent-2026-….ips`.
+ private static func crashProcessName(_ name: String) -> String {
+ let stem = (name as NSString).deletingPathExtension
+ if let range = stem.range(of: #"-\d{4}-\d{2}-\d{2}"#, options: .regularExpression) {
+ return String(stem[..<range.lowerBound])
+ }
+ return stem.split(separator: "-").first.map(String.init) ?? stem
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Process.swift b/VPhoneDaemon/Daemon/GuestAPI+Process.swift
new file mode 100644
index 00000000..25dcaa71
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Process.swift
@@ -0,0 +1,84 @@
+import Darwin
+import Foundation
+import IcliKit
+import IcliSystem
+import VphonedNative
+
+// MARK: - Processes and Memory
+
+extension GuestAPI {
+ static func executeProcess(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "processes.list":
+ return try processList(filter: optionalString(params, "filter"))
+ case "processes.kill":
+ let pid = try integer(params, "pid")
+ guard pid > 1, pid != Int(getpid()) else {
+ throw GuestAPIError.invalidRequest("pid \(pid) cannot be signalled")
+ }
+ let name = optionalString(params, "signal")?.uppercased() ?? "TERM"
+ guard let signal = signals[name.hasPrefix("SIG") ? String(name.dropFirst(3)) : name] else {
+ throw GuestAPIError.invalidRequest("signal must be one of \(signals.keys.sorted().joined(separator: ", "))")
+ }
+ try requireForce(params, "send SIG\(name) to \(pid)")
+ guard kill(pid_t(pid), signal) == 0 else {
+ throw GuestAPIError.operationFailed("kill(\(pid)): \(String(cString: strerror(errno)))")
+ }
+ return ["pid": pid, "signal": name]
+ case "memory.jetsam":
+ return try jetsamSnapshot()
+ default:
+ return nil
+ }
+ }
+
+ private static let signals: [String: Int32] = [
+ "HUP": SIGHUP, "INT": SIGINT, "QUIT": SIGQUIT, "KILL": SIGKILL, "TERM": SIGTERM,
+ "STOP": SIGSTOP, "CONT": SIGCONT, "USR1": SIGUSR1, "USR2": SIGUSR2,
+ ]
+
+ /// The kernel's process list joined with resource usage, jetsam bands and
+ /// the bundle identifier RunningBoard reports for app processes.
+ private static func processList(filter: String?) throws -> [String: Any] {
+ let rows = try listProcesses(filter: filter)["processes"] as? [[String: Any]] ?? []
+ let jetsam = (try? jetsamSnapshot())?["priorities"] as? [[String: Any]] ?? []
+ let bands = Dictionary(
+ jetsam.compactMap { row -> (Int, [String: Any])? in
+ guard let pid = row["pid"] as? Int else { return nil }
+ return (pid, row)
+ },
+ uniquingKeysWith: { first, _ in first },
+ )
+ let apps = (try? runningApps())?["apps"] as? [[String: Any]] ?? []
+ let bundles = Dictionary(
+ apps.compactMap { app -> (Int, String)? in
+ guard let pid = app["pid"] as? Int, let id = app["bundle_id"] as? String else { return nil }
+ return (pid, id)
+ },
+ uniquingKeysWith: { first, _ in first },
+ )
+ let processes = rows.compactMap { row -> [String: Any]? in
+ guard let pid = row["pid"] as? Int else { return nil }
+ var usage = VPProcessUsage()
+ guard vp_process_usage(Int32(pid), &usage) else { return nil }
+ var process = row
+ process["ppid"] = Int(usage.ppid)
+ process["uid"] = Int(usage.uid)
+ process["start_time"] = usage.start_time
+ if usage.has_task_info {
+ process["cpu_seconds"] = usage.cpu_seconds
+ process["footprint_bytes"] = usage.footprint_bytes
+ process["resident_bytes"] = usage.resident_bytes
+ }
+ if let band = bands[pid] {
+ process["jetsam_priority"] = band["priority"]
+ process["jetsam_limit_mb"] = band["limit_mb"]
+ }
+ if let bundle = bundles[pid] {
+ process["bundle_id"] = bundle
+ }
+ return process
+ }
+ return ["processes": processes, "count": processes.count]
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Service.swift b/VPhoneDaemon/Daemon/GuestAPI+Service.swift
new file mode 100644
index 00000000..5a0a947d
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Service.swift
@@ -0,0 +1,71 @@
+import Foundation
+import IcliKit
+import IcliSystem
+
+// MARK: - launchd Services
+
+extension GuestAPI {
+ static func executeService(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "services.list":
+ var result = try listServices()
+ if let disabled = try? disabledServiceOverrides()["disabled"] as? [String: Bool] {
+ let rows = result["services"] as? [[String: Any]] ?? []
+ result["services"] = rows.map { row -> [String: Any] in
+ var service = row
+ if let label = row["label"] as? String, let isDisabled = disabled[label] {
+ service["disabled"] = isDisabled
+ }
+ return service
+ }
+ }
+ return result
+ case "services.status":
+ return try serviceStatus(string(params, "label"))
+ case "services.print":
+ return try printService(string(params, "label"))
+ case "services.dump":
+ return try servicesDump()
+ case "services.disabled":
+ return try disabledServiceOverrides()
+ case "services.start":
+ return try startService(string(params, "label"))
+ case "services.enable":
+ return try setServiceEnabled(string(params, "label"), enabled: true)
+ case "services.stop":
+ let label = try string(params, "label")
+ try requireForce(params, "stop \(label)")
+ return try stopService(label)
+ case "services.disable":
+ let label = try string(params, "label")
+ try requireForce(params, "disable \(label)")
+ return try setServiceEnabled(label, enabled: false)
+ case "services.remove":
+ let label = try string(params, "label")
+ try requireForce(params, "remove \(label)")
+ return try removeService(label)
+ case "services.signal":
+ let label = try string(params, "label")
+ let signal = try string(params, "signal")
+ try requireForce(params, "send \(signal) to \(label)")
+ return try signalService(label, signal: signal)
+ case "services.load", "services.unload":
+ guard let paths = params["paths"] as? [String], !paths.isEmpty else {
+ throw GuestAPIError.invalidRequest("paths must list plist files or directories")
+ }
+ let load = method == "services.load"
+ if !load {
+ try requireForce(params, "unload services")
+ }
+ return try loadServices(paths, load: load, override: bool(params, "override"))
+ case "launchd.getenv":
+ return try launchdEnvironment(string(params, "key"))
+ case "launchd.setenv":
+ return try setLaunchdEnvironment(string(params, "key"), value: string(params, "value"))
+ case "launchd.unsetenv":
+ return try setLaunchdEnvironment(string(params, "key"), value: nil)
+ default:
+ return nil
+ }
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index a7b1ca51..74b68da0 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -65,6 +65,19 @@ enum GuestAPI {
"port_forward",
"camera",
"screenshot",
+ "device_info",
+ "display",
+ "audio",
+ "input_gestures",
+ "ui_inspection",
+ "processes",
+ "services",
+ "logs",
+ "network_capture",
+ "app_details",
+ "system_control",
+ "file_tools",
+ "packages",
],
]
}
@@ -161,7 +174,9 @@ enum GuestAPI {
case "apps.terminate":
return try killApp(string(params, "bundle_id"), force: true)
case "apps.uninstall":
- return try uninstallApp(string(params, "bundle_id"), force: params["force"] as? Bool == true)
+ let id = try string(params, "bundle_id")
+ try requireForce(params, "uninstall \(id)")
+ return try uninstallApp(id, force: true)
case "apps.foreground":
let front = frontmostApp()
let id = front["bundle_id"] as? String ?? ""
@@ -279,8 +294,6 @@ enum GuestAPI {
)
case "settings.delete":
return try deletePreference(domain: string(params, "domain"), key: string(params, "key"))
- case "accessibility.tree":
- throw GuestAPIError.operationFailed("The accessibility tree is not available on this guest yet.")
case "keychain.list":
return try GuestKeychain.list(className: params["class"] as? String)
case "keychain.add":
@@ -312,6 +325,9 @@ enum GuestAPI {
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { exit(0) }
return ["restarting": true]
default:
+ if let result = try executeExtended(method: method, params: params) {
+ return result
+ }
throw GuestAPIError.unsupportedMethod(method)
}
}
@@ -360,7 +376,7 @@ enum GuestAPI {
return result
}
- private static func jailbreakInfo() -> [String: Any] {
+ static func jailbreakInfo() -> [String: Any] {
func isDirectory(_ path: String) -> Bool {
var directory: ObjCBool = false
return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
@@ -395,21 +411,21 @@ enum GuestAPI {
return ["layout": NSNull(), "jbroot": NSNull(), "source": "not detected"]
}
- private static func string(_ params: [String: Any], _ key: String) throws -> String {
+ static func string(_ params: [String: Any], _ key: String) throws -> String {
guard let value = params[key] as? String, !value.isEmpty else {
throw GuestAPIError.invalidRequest("\(key) is required")
}
return value
}
- private static func integer(_ params: [String: Any], _ key: String) throws -> Int {
+ static func integer(_ params: [String: Any], _ key: String) throws -> Int {
guard let value = params[key] as? NSNumber else {
throw GuestAPIError.invalidRequest("\(key) must be an integer")
}
return value.intValue
}
- private static func number(_ params: [String: Any], _ key: String, default fallback: Double = .nan) -> Double {
+ static func number(_ params: [String: Any], _ key: String, default fallback: Double = .nan) -> Double {
if let value = params[key] as? NSNumber {
return value.doubleValue
}
@@ -418,4 +434,27 @@ enum GuestAPI {
}
return fallback
}
+
+ static func optionalString(_ params: [String: Any], _ key: String) -> String? {
+ guard let value = params[key] as? String, !value.isEmpty else { return nil }
+ return value
+ }
+
+ static func bool(_ params: [String: Any], _ key: String, default fallback: Bool = false) -> Bool {
+ (params[key] as? NSNumber)?.boolValue ?? fallback
+ }
+
+ static func requiredNumber(_ params: [String: Any], _ key: String) throws -> Double {
+ let value = number(params, key)
+ guard value.isFinite else { throw GuestAPIError.invalidRequest("\(key) must be a number") }
+ return value
+ }
+
+ /// Operations that end a process, stop a service, remove an app or restart
+ /// the guest run only when the caller says so, so a stray request cannot.
+ static func requireForce(_ params: [String: Any], _ action: String) throws {
+ guard bool(params, "force") else {
+ throw GuestAPIError.invalidRequest("Pass force: true to \(action)")
+ }
+ }
}
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index fe5af81b..645f9622 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -6,3 +6,17 @@ char *vp_sign_app_for_install(const char *appPath, const char *certificatePath);
void vp_native_bootstrap_cached_binary(void);
void vp_native_confirm_cached_binary(void);
void vp_vcam_start(void);
+
+typedef struct {
+ int32_t pid;
+ int32_t ppid;
+ uint32_t uid;
+ double start_time;
+ double cpu_seconds;
+ uint64_t footprint_bytes;
+ uint64_t resident_bytes;
+ bool has_task_info;
+} VPProcessUsage;
+
+/// Identity and resource usage for one process. Returns false when the process is gone.
+bool vp_process_usage(int pid, VPProcessUsage *usage);
diff --git a/VPhoneDaemon/Native/vphoned_process.m b/VPhoneDaemon/Native/vphoned_process.m
new file mode 100644
index 00000000..5b43f853
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_process.m
@@ -0,0 +1,34 @@
+#import "Include/VphonedNative.h"
+#include <mach/mach_time.h>
+#include <sys/resource.h>
+#include <sys/sysctl.h>
+
+// libproc is not in the iOS SDK; this is its stable libsystem_kernel export.
+extern int proc_pid_rusage(int pid, int flavor, rusage_info_t *buffer);
+
+bool vp_process_usage(int pid, VPProcessUsage *usage) {
+ memset(usage, 0, sizeof(*usage));
+ usage->pid = pid;
+
+ struct kinfo_proc info;
+ size_t size = sizeof(info);
+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
+ if (sysctl(mib, 4, &info, &size, NULL, 0) != 0 || size == 0) return false;
+ usage->ppid = info.kp_eproc.e_ppid;
+ usage->uid = info.kp_eproc.e_ucred.cr_uid;
+ usage->start_time = (double)info.kp_proc.p_starttime.tv_sec + info.kp_proc.p_starttime.tv_usec / 1e6;
+
+ // Task statistics need the target to be inspectable; a failure here still
+ // leaves the identity fields above valid.
+ struct rusage_info_v4 rusage;
+ if (proc_pid_rusage(pid, RUSAGE_INFO_V4, (rusage_info_t *)&rusage) == 0) {
+ static mach_timebase_info_data_t timebase;
+ if (timebase.denom == 0) mach_timebase_info(&timebase);
+ uint64_t ticks = rusage.ri_user_time + rusage.ri_system_time;
+ usage->cpu_seconds = (double)ticks * timebase.numer / timebase.denom / 1e9;
+ usage->footprint_bytes = rusage.ri_phys_footprint;
+ usage->resident_bytes = rusage.ri_resident_size;
+ usage->has_task_info = true;
+ }
+ return true;
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index 5786dbe8..b17bd8a4 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -236,7 +236,8 @@ final class VPhoneGuestControl {
return (result, nil)
}
- private func call(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {
+ /// Calls one named vphoned operation over `/v1/rpc` and returns its result object.
+ func call(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {
let object: [String: Any] = ["id": UUID().uuidString, "method": method, "params": params]
let body = try JSONSerialization.data(withJSONObject: object)
let response = try await http(method: "POST", path: "/v1/rpc", body: body)
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
index a62886b0..7a8d6159 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
@@ -42,8 +42,8 @@ extension VPhoneGuestControl {
// MARK: - Accessibility
func accessibilityTree(depth: Int = -1) async throws -> [String: Any] {
- guard guestCapabilities.contains("accessibility_tree") else {
- throw ControlError.unsupportedCapability("accessibility_tree")
+ guard guestCapabilities.contains("ui_inspection") else {
+ throw ControlError.unsupportedCapability("ui_inspection")
}
let (resp, _) = try await sendRequest(["t": "accessibility_tree", "depth": depth])
return resp
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhonePanelShared.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhonePanelShared.swift
new file mode 100644
index 00000000..622a9e85
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/VPhonePanelShared.swift
@@ -0,0 +1,137 @@
+import Foundation
+import SwiftUI
+
+// MARK: - JSON Values
+
+/// vphoned answers with JSONSerialization objects. These readers accept the
+/// NSNumber and string spellings the guest uses for the same field.
+extension Dictionary where Key == String, Value == Any {
+ func string(_ key: String) -> String? {
+ switch self[key] {
+ case let value as String: value
+ case let value as NSNumber: value.stringValue
+ default: nil
+ }
+ }
+
+ func int(_ key: String) -> Int? {
+ switch self[key] {
+ case let value as NSNumber: value.intValue
+ case let value as String: Int(value)
+ default: nil
+ }
+ }
+
+ func double(_ key: String) -> Double? {
+ switch self[key] {
+ case let value as NSNumber: value.doubleValue
+ case let value as String: Double(value)
+ default: nil
+ }
+ }
+
+ func bool(_ key: String) -> Bool? {
+ switch self[key] {
+ case let value as NSNumber: value.boolValue
+ case let value as String: ["1", "true", "yes", "on"].contains(value.lowercased())
+ default: nil
+ }
+ }
+
+ func object(_ key: String) -> [String: Any]? {
+ self[key] as? [String: Any]
+ }
+
+ func objects(_ key: String) -> [[String: Any]] {
+ self[key] as? [[String: Any]] ?? []
+ }
+}
+
+// MARK: - Formatting
+
+enum VPhonePanelFormat {
+ static func bytes(_ value: Int64?) -> String {
+ guard let value else { return "—" }
+ return ByteCountFormatter.string(fromByteCount: value, countStyle: .memory)
+ }
+
+ static func bytes(_ value: Int?) -> String {
+ bytes(value.map(Int64.init))
+ }
+
+ /// A duration such as `2d 4h`, `3h 12m`, `41s`.
+ static func duration(_ seconds: Double?) -> String {
+ guard let seconds, seconds.isFinite, seconds >= 0 else { return "—" }
+ let formatter = DateComponentsFormatter()
+ formatter.unitsStyle = .abbreviated
+ formatter.maximumUnitCount = 2
+ formatter.allowedUnits = seconds < 60 ? [.second] : [.day, .hour, .minute, .second]
+ return formatter.string(from: seconds) ?? "—"
+ }
+
+ /// CPU time with sub-second precision for short-lived processes.
+ static func cpuTime(_ seconds: Double?) -> String {
+ guard let seconds, seconds.isFinite else { return "—" }
+ if seconds < 60 {
+ return String(format: "%.2fs", seconds)
+ }
+ return duration(seconds)
+ }
+
+ static func date(_ epoch: Double?) -> String {
+ guard let epoch, epoch > 0 else { return "—" }
+ return Date(timeIntervalSince1970: epoch).formatted(date: .abbreviated, time: .standard)
+ }
+
+ static func percent(_ fraction: Double?) -> String {
+ guard let fraction, fraction.isFinite else { return "—" }
+ return fraction.formatted(.percent.precision(.fractionLength(0)))
+ }
+}
+
+// MARK: - Empty State
+
+/// The centered placeholder a panel shows before its first load or when a
+/// filter matches nothing.
+struct VPhonePanelEmptyState: View {
+ let title: LocalizedStringKey
+ let systemImage: String
+ var message: LocalizedStringKey?
+
+ var body: some View {
+ ContentUnavailableView {
+ Label {
+ Text(title, bundle: VPhoneLocalization.bundle)
+ } icon: {
+ Image(systemName: systemImage)
+ }
+ } description: {
+ if let message {
+ Text(message, bundle: VPhoneLocalization.bundle)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+}
+
+// MARK: - Monospaced Cell
+
+/// A single-line table cell in the research-instrument monospace style.
+struct VPhonePanelMonoText: View {
+ let value: String
+ var secondary = false
+
+ init(_ value: String, secondary: Bool = false) {
+ self.value = value
+ self.secondary = secondary
+ }
+
+ var body: some View {
+ Text(value)
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundStyle(secondary ? .secondary : .primary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(value)
+ }
+}