Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Shut a guest down from vphoned and the VM's Device menu

Jacky58c069f92331
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index c2c9cc1a..4a9c4cd6 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -282,7 +282,7 @@ request carries `"force": true`.
| Darwin notifications | `notify.post {name, state?}` (`postDarwinNotification`; `state` is a UInt64, as a number or a decimal string, stored before the post), `notify.state {name}` (`darwinNotificationState`) |
| Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.ipv4.get {interface?}`, `network.ipv4.set {interface?, method, address?, subnet_mask?, router?, dns?}`, `network.hostname.get`, `network.hostname.set {local_host_name?}`, `network.static_names.get`, `network.static_names.set {entries}`, `network.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` |
| Apps | `apps.list`, `search`, `refresh`, `launch`, `terminate`, `foreground`, `open_url`, `install`, `info`, `binary`, `data_dir`, `url_schemes`, `handlers`, `registration`, `register`, `network_policy {repair?}`; `apps.uninstall`, `unregister`, `unregister_dir` **force** |
-| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}` (see below), `diagnostics.self_test` |
+| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `system.shutdown` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}` (see below), `diagnostics.self_test` |
| Files | `files.list`, `mkdir`, `remove`, `rename`, `read {binary?, limit?}`, `write`, `find`, `copy`, `symlink`, `chmod`, `chown`, `plist`, `plist_set {value \| remove}` |
| Preferences, clipboard, location | `settings.get/set/delete`, `clipboard.get/set/clear`, `location.set/clear/current` |
| Keychain | `keychain.list {class?}`, `add`, `delete`, `get`, `update`, `database` |
@@ -404,7 +404,7 @@ Account passwords, boot logo rendering and package installation, removal and
repository changes are deliberately not exposed. `/v1/health` lists the new
areas in `capabilities` (`device_info`, `display`, `audio`, `input_gestures`,
`ui_inspection`, `processes`, `services`, `logs`, `network_capture`,
-`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_ipv4`, `network_hostname`, `network_static_names`, `network_resolve`, `display_auto_lock`, `screen_unlock`) so a host can hide
+`app_details`, `system_control`, `system_shutdown`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_ipv4`, `network_hostname`, `network_static_names`, `network_resolve`, `display_auto_lock`, `screen_unlock`) so a host can hide
panels an older agent cannot serve. icli failures reach the caller with
icli's own error `code` (`failed`, `unavailable`, `device_locked`, …) and
message.
diff --git a/Skills/vphone-guest-control/SKILL.md b/Skills/vphone-guest-control/SKILL.md
index f3899364..85ec14b9 100644
--- a/Skills/vphone-guest-control/SKILL.md
+++ b/Skills/vphone-guest-control/SKILL.md
@@ -78,9 +78,9 @@ These exist because each one has cost the user real time or disk before.
second `vm create` over existing work unless the user asked. Report what is
needed; the Mac's owner decides.
- **`force` methods need the user's intent.** `processes.kill`, `services.stop`,
- `apps.uninstall`, `system.respring`, `system.reboot` and similar refuse to run
- without `"force":true`. Passing it is the confirmation, so pass it only for an
- action the user asked for.
+ `apps.uninstall`, `system.respring`, `system.reboot`, `system.shutdown` and
+ similar refuse to run without `"force":true`. Passing it is the confirmation,
+ so pass it only for an action the user asked for.
- **Do not edit a machine's folder (`~/.vphone/machines/<name>/`) while it runs.**
Use RPC for guest files instead.
- **Keep the host API listener on loopback.** `--api-listen` sends its token in
diff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.md
index 9505151a..81afec13 100644
--- a/Skills/vphone-guest-control/references/rpc-methods.md
+++ b/Skills/vphone-guest-control/references/rpc-methods.md
@@ -34,8 +34,8 @@ invalid-request error, read the source named there instead of guessing keys.
- **force methods** refuse to run unless the params carry `"force":true`:
`processes.kill`, `services.stop|disable|remove|signal|unload`,
`apps.uninstall|unregister|unregister_dir`, `system.respring`,
- `system.reboot`, `setup.skip`. The flag is the confirmation: use it only for
- what the user asked.
+ `system.reboot`, `system.shutdown`, `setup.skip`. The flag is the
+ confirmation: use it only for what the user asked.
- Results can be large. Methods that read data take `limit`, `max_lines`,
`max_elements` or a `filter`; use them. A reply in the 8–16 KiB band can be
lost on close (see [troubleshooting](troubleshooting.md)).
@@ -175,6 +175,7 @@ size problem.
| --- | --- |
| `system.uicache` | none; re-registers apps |
| `system.respring` (force), `system.reboot` (force) | `userspace?` for reboot |
+| `system.shutdown` (force) | none; shuts the guest down, which stops the VM (capability `system_shutdown`) |
| `setup.status` | none; `setup.skip` (force) skips Setup Assistant |
| `developer_mode.status` / `enable` | none |
| `settings.get` | `domain`, `key?` |
diff --git a/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift b/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift
index 44d3f9ee..878b1706 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift
@@ -1,6 +1,7 @@
import Foundation
import IcliKit
import IcliSystem
+import VphonedNative
// MARK: - App Detail and System Control
@@ -42,6 +43,9 @@ extension GuestAPI {
let userspace = bool(params, "userspace")
try requireForce(params, userspace ? "restart userspace" : "reboot the guest")
return try requestReboot(userspace: userspace, force: true)
+ case "system.shutdown":
+ try requireForce(params, "shut down the guest")
+ return try requestShutdown()
default:
return nil
}
@@ -78,3 +82,19 @@ extension GuestAPI {
}
}
}
+
+// MARK: - Shutdown
+
+extension GuestAPI {
+ /// Asks launchd to shut the guest down. Success means launchd accepted the
+ /// request; the guest then stops, which ends the virtual machine on the
+ /// host, so the caller usually loses the connection before the reply.
+ static func requestShutdown() throws -> [String: Any] {
+ guard geteuid() == 0 else { throw GuestAPIError.operationFailed("shutdown requires root") }
+ let status = vp_system_halt()
+ guard status == 0 else {
+ throw GuestAPIError.operationFailed("shutdown request rejected: \(String(cString: strerror(status)))")
+ }
+ return ["accepted": true, "completion": "the virtual machine stops"]
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 77cd99f7..f5cf3e71 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -111,6 +111,7 @@ enum GuestAPI {
"network_capture",
"app_details",
"system_control",
+ "system_shutdown",
"file_tools",
"files_app_drop",
"packages",
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index ac4510c4..2b9eb4dd 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -30,6 +30,10 @@ void vp_hid_touch2(int phase, double x1, double y1, double x2, double y2);
/// SpringBoardServices has no SBSUndimScreen.
bool vp_screen_undim(void);
+/// Ask launchd to shut the guest down and halt. Returns 0 once the request is
+/// accepted, otherwise an errno value. Needs root.
+int vp_system_halt(void);
+
typedef struct {
int32_t pid;
int32_t ppid;
diff --git a/VPhoneDaemon/Native/vphoned_power.m b/VPhoneDaemon/Native/vphoned_power.m
new file mode 100644
index 00000000..0cc7e275
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_power.m
@@ -0,0 +1,25 @@
+/*
+ * vphoned_power — shut the guest down.
+ *
+ * reboot3 hands the request to launchd, which stops every service, unmounts
+ * the volumes and then halts the kernel. The flags are the ones
+ * `launchctl reboot halt` passes: a full reboot with RB_HALT set. The host
+ * sees the halt as the virtual machine stopping.
+ *
+ * icli's `requestReboot` covers the restart kinds; it has no halt.
+ */
+
+#import "Include/VphonedNative.h"
+
+#include <errno.h>
+
+extern int reboot3(uint64_t flags, ...);
+#define RB2_FULLREBOOT 0x8000000000000000ULL
+// <sys/reboot.h> is not in the iOS SDK.
+#define RB_HALT 0x08
+
+int vp_system_halt(void) {
+ errno = 0;
+ if (reboot3(RB2_FULLREBOOT | RB_HALT, 0) == 0) return 0;
+ return errno ?: EIO;
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index 0f3fd3d8..4c9a5a2a 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -2722,6 +2722,40 @@
}
}
},
+ "Apps in the guest quit and the virtual machine stops. This window closes when the guest has shut down." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Apps in the guest quit and the virtual machine stops. This window closes when the guest has shut down."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲスト内のアプリは終了し、仮想マシンは停止します。ゲストのシステム終了が完了すると、このウインドウは閉じます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트의 앱이 종료되고 가상 머신이 중지됩니다. 게스트가 종료되면 이 윈도우가 닫힙니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Các ứng dụng trong máy khách sẽ thoát và máy ảo sẽ dừng. Cửa sổ này đóng lại khi máy khách đã tắt."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "客户机中的应用将退出,虚拟机随之停止。客户机关机完成后,此窗口会关闭。"
+ }
+ }
+ }
+ },
"Apps in the guest quit. The guest agent reconnects after the guest starts up." : {
"localizations" : {
"en" : {
@@ -17543,6 +17577,108 @@
}
}
},
+ "Shut Down Guest" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Shut Down Guest"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストをシステム終了"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트 종료"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tắt máy khách"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "客户机关机"
+ }
+ }
+ }
+ },
+ "Shut Down Guest…" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Shut Down Guest…"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストをシステム終了…"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트 종료…"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tắt máy khách…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "客户机关机…"
+ }
+ }
+ }
+ },
+ "Shut down the guest?" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Shut down the guest?"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストをシステム終了しますか?"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트를 종료하시겠습니까?"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tắt máy khách?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "要将客户机关机吗?"
+ }
+ }
+ }
+ },
"Switch Guest Input Source" : {
"localizations" : {
"en" : {
@@ -17577,6 +17713,40 @@
}
}
},
+ "The guest refused the shutdown request." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The guest refused the shutdown request."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストがシステム終了の要求を拒否しました。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트가 종료 요청을 거부했습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Máy khách đã từ chối yêu cầu tắt máy."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "客户机拒绝了关机请求。"
+ }
+ }
+ }
+ },
"The guest removes them from its keychain. This cannot be undone." : {
"localizations" : {
"en" : {
@@ -17679,6 +17849,40 @@
}
}
},
+ "Unable to Shut Down Guest" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unable to Shut Down Guest"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストをシステム終了できません"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트를 종료할 수 없음"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Không thể tắt máy khách"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无法将客户机关机"
+ }
+ }
+ }
+ },
"Unable to update the keychain item. Try again." : {
"localizations" : {
"en" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index 25d31329..a6870fac 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -551,6 +551,15 @@ final class VPhoneGuestControl {
_ = try await call("system.reboot", params: ["force": true])
}
+ /// Asks the guest to shut down. The virtual machine stops with it, so a
+ /// dropped connection is the expected result.
+ func shutDownGuest() async throws {
+ guard guestCapabilities.contains("system_shutdown") else {
+ throw ControlError.unsupportedCapability("system_shutdown")
+ }
+ _ = try await call("system.shutdown", params: ["force": true])
+ }
+
func clipboardGet() async throws -> ClipboardContent {
let (info, image) = try await sendRequest(["t": "clipboard_get"])
return ClipboardContent(
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
index 36da28e2..24b99689 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
@@ -50,6 +50,7 @@ class VPhoneMenuController {
var settingsGetItem: NSMenuItem?
var settingsSetItem: NSMenuItem?
var restartGuestItem: NSMenuItem?
+ var shutDownGuestItem: NSMenuItem?
var setUDIDItem: NSMenuItem?
var resetUDIDItem: NSMenuItem?
var skipSetupAssistantItem: NSMenuItem?
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
index 420b4dac..9942bb71 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
@@ -108,6 +108,10 @@ extension VPhoneMenuController {
restart.isEnabled = false
restartGuestItem = restart
menu.addItem(restart)
+ let shutDown = makeItem("Shut Down Guest…", action: #selector(shutDownGuest), symbol: "power")
+ shutDown.isEnabled = false
+ shutDownGuestItem = shutDown
+ menu.addItem(shutDown)
item.submenu = menu
return item
}
@@ -302,6 +306,38 @@ extension VPhoneMenuController {
}
}
+ // MARK: - Shut Down
+
+ func updateShutDownAvailability(available: Bool) {
+ shutDownGuestItem?.isEnabled = available
+ }
+
+ @objc func shutDownGuest() {
+ VPhoneAlert.present(
+ title: "Shut down the guest?",
+ message: "Apps in the guest quit and the virtual machine stops. This window closes when the guest has shut down.",
+ style: .warning,
+ buttons: ["Shut Down Guest", "Cancel"],
+ ) { response in
+ guard response == .alertFirstButtonReturn else { return }
+ Task {
+ do {
+ try await self.control.shutDownGuest()
+ } catch let VPhoneGuestControl.ControlError.guestError(message) {
+ print("[shutdown] guest refused: \(message)")
+ VPhoneAlert.present(
+ title: "Unable to Shut Down Guest",
+ message: "The guest refused the shutdown request.",
+ style: .warning,
+ )
+ } catch {
+ // The guest can stop before it replies, so the connection
+ // drops. The process exits when the virtual machine stops.
+ }
+ }
+ }
+ }
+
@objc func toggleTouchIDForwarding() {
guard let monitor = touchIDMonitor, let item = touchIDMenuItem else { return }
monitor.isEnabled.toggle()
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index 4717fd2b..9d8f41c7 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -228,6 +228,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
mc?.updateClipboardAvailability(available: caps.contains("clipboard"))
mc?.updateSettingsAvailability(available: true)
mc?.updateRestartAvailability(available: caps.contains("system_control"))
+ mc?.updateShutDownAvailability(available: caps.contains("system_shutdown"))
mc?.updateUDIDAvailability(available: caps.contains("udid_override"))
mc?.updatePanelAvailability(capabilities: caps)
if caps.contains("location") {
@@ -261,6 +262,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
mc?.updateClipboardAvailability(available: false)
mc?.updateSettingsAvailability(available: false)
mc?.updateRestartAvailability(available: false)
+ mc?.updateShutDownAvailability(available: false)
mc?.updateUDIDAvailability(available: false)
mc?.updatePanelAvailability(capabilities: [])
provider?.stopReplay()