Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Start each VM through a launcher inside Launchpad's app bundle

Jacky53ce50672e23
diff --git a/AGENTS.md b/AGENTS.md
index 4a8966f3..703e40da 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -50,7 +50,7 @@ See `Research/` for detailed firmware pipeline, component origins, patch breakdo
- `VPhoneKit`: shared core, archive, and external access kits with their tests.
- `VPhoneDaemon`: guest `vphoned`, native operations, and daemon configuration.
- `VPhoneGuestComponents`: guest dylibs built by Makefile from the bundle build phase.
-- `VPhoneLaunchpad`: `vphone-launchpad.app`, the workstation app that downloads and manages `VPhone.bundle` releases and drives each VM through the `vphone-cli` of the Core Bundle that machine is bound to (`launchpad.json` in the machine folder; the default bundle only seeds new machines and library-wide commands), plus its SMJobBless helper `com.vphone.launchpad.helper` and `vphone-launchpad-cli`, a stateless client of the running app over a same-user Unix socket (`Documents/Guides/launchpad-cli.md`; use it to install and test a local `VPhone.bundle` build). Shipped separately from the bundle. Settings live only in `VPhoneLaunchpad/Configuration/*.xcconfig`; the pbxproj holds none.
+- `VPhoneLaunchpad`: `vphone-launchpad.app`, the workstation app that downloads and manages `VPhone.bundle` releases and drives each VM through the `vphone-cli` of the Core Bundle that machine is bound to (`launchpad.json` in the machine folder; the default bundle only seeds new machines and library-wide commands), plus its SMJobBless helper `com.vphone.launchpad.helper`, `vphone-launchpad-cli`, a stateless client of the running app over a same-user Unix socket (`Documents/Guides/launchpad-cli.md`; use it to install and test a local `VPhone.bundle` build), and `vphone-launchpad-launcher`, the responsible process for each VM it starts. Shipped separately from the bundle. Settings live only in `VPhoneLaunchpad/Configuration/*.xcconfig`; the pbxproj holds none.
The `VPhone` scheme puts host programs in `VPhone.bundle/Contents/MacOS` and everything installed into the guest (vphoned, guest dylibs, their plists) in `Contents/Resources/guest-resources`. Xcode targets have `CODE_SIGNING_ALLOWED=NO`; the bundle build phase signs each binary ad hoc with only its own entitlements, then seals the outer bundle. `VPhoneVirtualization.entitlements` belongs to `vphone-vm`; `VPhoneDaemon.entitlements` belongs to `vphoned`. The bundle and CLI have no private entitlements.
@@ -58,7 +58,7 @@ The `VPhone` scheme puts host programs in `VPhone.bundle/Contents/MacOS` and eve
- `vphone-cli` is the unentitled entry point. `VPhoneGuestLaunchPlanner` resolves `vphone-vm` beside the running executable, checks its entitlements, probes AMFI, and reports the exact allowlist command on refusal. It never obtains root itself.
- `vphone-escalator` manages AMFI cdhash admission only. It writes amfid heap state, not executable code. Root authorization belongs to the user or to `vphone-launchpad`; neither `vphone-cli` nor the bundle has an SMJobBless or sudo password flow.
-- `vphone-launchpad` has no entitlements. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles`, runs that bundle's `vphone-escalator allow` for its receipt-pinned `vphone-vm`, and runs `cfw install` from that store after rechecking the recorded cdhash. There is no generic command verb. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.
+- `vphone-launchpad` has no private entitlements. `SignLaunchpad.sh` gives its main executable two hardened-runtime resource entitlements, microphone (`com.apple.security.device.audio-input`) and location (`com.apple.security.personal-information.location`), from `VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements`; its helper, CLI and launcher have none. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles`, runs that bundle's `vphone-escalator allow` for its receipt-pinned `vphone-vm`, and runs `cfw install` from that store after rechecking the recorded cdhash. There is no generic command verb. Launchpad starts `vm launch` detached (own session, responsibility disclaimed) through `vphone-launchpad-launcher` in its `Contents/MacOS`, which starts `vphone-cli` as an ordinary child and stays until it exits, forwarding stop signals and exiting the same way. The launcher is therefore the responsible process for `vphone-vm`. As a tool in the app's `Contents/MacOS` it is attributed to the app, so privacy prompts, usage descriptions and grants (microphone, location) are the app's, asked once for its Developer ID signature instead of for each ad hoc signed bundle build; under the hardened runtime macOS refuses them without asking unless the app carries the matching entitlement. It refuses anything but `vm launch` of a `vphone-cli` in the root-owned store (`VPhoneLaunchpadLauncherPolicy`); without the launcher, Launchpad starts `vphone-cli` directly. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.
- Launchpad and `VPhone.bundle` match by series, the first two numbers of the version: Launchpad 2.2.3 works with any `VPhone.bundle` 2.2.x, and the reverse. Patch releases within a series must stay interchangeable in both directions. A change to anything Launchpad relies on in the bundle (`vphone-cli` arguments or output, `vphone-escalator`, the bundle layout or receipt) needs a new minor version and a raised `minimumBundleComponents` in `VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift`. `Documents/Downloads/README.md` states this rule to users.
- Host VM artifacts, caches, and archives created by vphone use mode `0777` for workstation access. Symlinks are not followed when changing permissions. Guest filesystem modes inside `Disk.img` remain unchanged.
- `VPhoneRestore` runs in the CLI process over vendored libirecovery and idevicerestore. No Python or runtime Homebrew dependency is allowed.
diff --git a/Documents/Guides/bundle-integration.md b/Documents/Guides/bundle-integration.md
index b37f4924..bb02c2e4 100644
--- a/Documents/Guides/bundle-integration.md
+++ b/Documents/Guides/bundle-integration.md
@@ -31,6 +31,21 @@ acquisition. The integrating application owns download, release verification,
host authorization, installation, and update policy. Developer Tools access
and AMFI authorization are separate host decisions.
+macOS asks for a privacy permission (microphone, location) on behalf of the
+responsible process and ties the grant to its code signature. When
+`vphone-cli` is started with responsibility disclaimed, it becomes the
+responsible process for `vphone-vm`; it is signed ad hoc, so each new bundle
+build is asked again. An integrating application that starts `vphone-cli` as
+an ordinary child of a process with a stable signature, without disclaiming
+responsibility, gets the permission asked once. Launchpad does this with
+`vphone-launchpad-launcher`, which it carries in its own `Contents/MacOS`.
+macOS attributes a tool there to the enclosing app, so the prompt, the usage
+description and the grant are the app's. Under the hardened runtime the app's
+main executable must carry the matching resource entitlement
+(`com.apple.security.device.audio-input`,
+`com.apple.security.personal-information.location`); without it macOS refuses
+the request without asking.
+
Install and update the whole bundle as one versioned unit. Do not rewrite a
signed binary in place. When `vphone-vm` changes, its cdhash changes; the
integrating application must arrange AMFI admission for the new build before
diff --git a/VPhoneLaunchpad/Build/SignLaunchpad.sh b/VPhoneLaunchpad/Build/SignLaunchpad.sh
index 74054afe..4a027820 100644
--- a/VPhoneLaunchpad/Build/SignLaunchpad.sh
+++ b/VPhoneLaunchpad/Build/SignLaunchpad.sh
@@ -6,13 +6,23 @@
#
# zsh VPhoneLaunchpad/Build/SignLaunchpad.sh <path/to/vphone-launchpad.app> "Developer ID Application: …"
#
-# The helper and the command line tool are signed before the app that seals
-# them. None of them gets entitlements. Afterwards the helper is checked against the app's
+# The helper, the command line tool and the VM launcher are signed before the
+# app that seals them, without entitlements. The app gets the two hardened
+# runtime resource entitlements in Resources/VPhoneLaunchpad.entitlements
+# (microphone and location) and no private ones. They are applied only here:
+# CODE_SIGNING_ALLOWED is NO at build time, so no xcconfig sets
+# CODE_SIGN_ENTITLEMENTS. The launcher is the process macOS holds responsible
+# for each VM Launchpad starts; as a tool in the app's Contents/MacOS it is
+# attributed to the app, so a guest's privacy prompts and grants are the
+# app's, and under the hardened runtime the app's main executable must carry
+# the matching entitlement or macOS refuses without asking. Afterwards the
+# app's entitlements are checked, and the helper is checked against the app's
# SMPrivilegedExecutables requirement, which is what SMJobBless enforces.
set -euo pipefail
app=${1:?usage: SignLaunchpad.sh <vphone-launchpad.app> <identity>}
identity=${2:?usage: SignLaunchpad.sh <vphone-launchpad.app> <identity>}
+entitlements="${0:a:h}/../Resources/VPhoneLaunchpad.entitlements"
label=com.vphone.launchpad.helper
helper="$app/Contents/Library/LaunchServices/$label"
@@ -25,8 +35,18 @@ fi
codesign --force --options runtime --timestamp --sign "$identity" "$helper"
codesign --force --options runtime --timestamp --identifier com.vphone.launchpad.cli \
--sign "$identity" "$app/Contents/MacOS/vphone-launchpad-cli"
-codesign --force --options runtime --timestamp --sign "$identity" "$app"
+codesign --force --options runtime --timestamp --identifier com.vphone.launchpad.launcher \
+ --sign "$identity" "$app/Contents/MacOS/vphone-launchpad-launcher"
+codesign --force --options runtime --timestamp --entitlements "$entitlements" \
+ --sign "$identity" "$app"
codesign --verify --strict --deep "$app"
+signed=$(codesign -d --entitlements - --xml "$app" 2>/dev/null)
+for key in com.apple.security.device.audio-input com.apple.security.personal-information.location; do
+ if [[ $signed != *"<key>$key</key><true/>"* ]]; then
+ print -u2 "error: $app is not signed with $key."
+ exit 1
+ fi
+done
codesign --verify --strict -R="$requirement" "$helper"
print "signed $app"
diff --git a/VPhoneLaunchpad/Configuration/Base.xcconfig b/VPhoneLaunchpad/Configuration/Base.xcconfig
index 39f7aa76..d60963fa 100644
--- a/VPhoneLaunchpad/Configuration/Base.xcconfig
+++ b/VPhoneLaunchpad/Configuration/Base.xcconfig
@@ -9,6 +9,8 @@
// Signing is a separate step with a Developer ID identity, run by whoever
// distributes the app: Build/SignLaunchpad.sh. Leaving CODE_SIGNING_ALLOWED
// on would sign with whatever identity the build machine happens to have.
+// CODE_SIGN_ENTITLEMENTS is not set either: the app's entitlements,
+// Resources/VPhoneLaunchpad.entitlements, are applied only by that script.
CODE_SIGNING_ALLOWED = NO
// The team pinned by SMPrivilegedExecutables (app → helper) and
diff --git a/VPhoneLaunchpad/Configuration/VPhoneLaunchpadLauncher.xcconfig b/VPhoneLaunchpad/Configuration/VPhoneLaunchpadLauncher.xcconfig
new file mode 100644
index 00000000..c8b15f5c
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/VPhoneLaunchpadLauncher.xcconfig
@@ -0,0 +1,14 @@
+// The VM launcher. It ships in the app's Contents/MacOS and is the process
+// macOS holds responsible for each VM Launchpad starts. Privacy requests are
+// attributed to the enclosing app, whose Developer ID signature stays the same
+// across VPhone.bundle builds. It links nothing but the system and has no
+// entitlements and no Info.plist of its own.
+
+PRODUCT_NAME = vphone-launchpad-launcher
+PRODUCT_MODULE_NAME = VPhoneLaunchpadLauncher
+PRODUCT_BUNDLE_IDENTIFIER = com.vphone.launchpad.launcher
+// Embedded in the app, never installed on its own.
+SKIP_INSTALL = YES
+
+// Top-level code that waits on a child: nothing here is UI.
+SWIFT_DEFAULT_ACTOR_ISOLATION = nonisolated
diff --git a/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist b/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist
index e5815b79..d0e639e3 100644
--- a/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist
+++ b/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist
@@ -26,10 +26,15 @@
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
- <!-- vphone-vm reads the host location for the guest. A VM started from
- Launchpad can have Launchpad as its responsible process, so TCC shows
- these descriptions from this bundle. Same text as VPhone.bundle,
- localized by VPhoneLaunchpad/InfoPlist.xcstrings. -->
+ <!-- vphone-vm reads the host location for the guest (through
+ VPhoneLocation.app). Launchpad starts each VM through
+ Contents/MacOS/vphone-launchpad-launcher, the responsible process for
+ vphone-cli, vphone-vm and their children. A tool in this app's
+ Contents/MacOS is attributed to this app, so TCC asks on the app's
+ behalf, shows these descriptions from this bundle and stores the grant
+ for the app. Under the hardened runtime the app also needs the
+ location entitlement in VPhoneLaunchpad.entitlements. Same text as
+ VPhone.bundle, localized by VPhoneLaunchpad/InfoPlist.xcstrings. -->
<key>NSLocationUsageDescription</key>
<string>Shares your location with the virtual iPhone so apps running inside it see the same location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
diff --git a/VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements b/VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements
new file mode 100644
index 00000000..e3f7d746
--- /dev/null
+++ b/VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements
@@ -0,0 +1,19 @@
+<?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">
+<!-- Hardened runtime resource entitlements for the app's main executable,
+ applied only by Build/SignLaunchpad.sh: the Xcode build does not sign.
+ Guests are started through Contents/MacOS/vphone-launchpad-launcher, so
+ macOS attributes their privacy requests to this app. Under the hardened
+ runtime it refuses the microphone or location to an app without the
+ matching entitlement, without asking. The microphone is used by guest
+ audio input; location by VPhoneLocation.app, which vphone-vm starts as a
+ child when Sync Host Location is on. The helper, the command line tool
+ and the launcher get no entitlements. -->
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.device.audio-input</key>
+ <true/>
+ <key>com.apple.security.personal-information.location</key>
+ <true/>
+</dict>
+</plist>
diff --git a/VPhoneLaunchpad/Tests/LauncherPolicyTests.sh b/VPhoneLaunchpad/Tests/LauncherPolicyTests.sh
new file mode 100755
index 00000000..7ec98003
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/LauncherPolicyTests.sh
@@ -0,0 +1,14 @@
+#!/bin/zsh
+set -euo pipefail
+
+launchpad="${0:a:h:h}"
+temporary="$(/usr/bin/mktemp -d)"
+trap '/bin/rm -rf "$temporary"' EXIT
+
+/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \
+ -parse-as-library \
+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift" \
+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLauncherPolicy.swift" \
+ "$launchpad/Tests/LauncherPolicyTests.swift" \
+ -o "$temporary/launcher-policy-tests"
+"$temporary/launcher-policy-tests" "$@"
diff --git a/VPhoneLaunchpad/Tests/LauncherPolicyTests.swift b/VPhoneLaunchpad/Tests/LauncherPolicyTests.swift
new file mode 100644
index 00000000..451d6f22
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/LauncherPolicyTests.swift
@@ -0,0 +1,133 @@
+import Darwin
+import Foundation
+
+@main
+struct LauncherPolicyTests {
+ typealias Policy = VPhoneLaunchpadLauncherPolicy
+
+ static let launch = ["vm", "launch", "research-01"]
+
+ static func main() throws {
+ let fileManager = FileManager.default
+ let temporary = try fileManager.url(
+ for: .itemReplacementDirectory, in: .userDomainMask,
+ appropriateFor: fileManager.temporaryDirectory, create: true,
+ )
+ defer { try? fileManager.removeItem(at: temporary) }
+ // The store and its parents are owned by this user here; the status
+ // lookup reports root as the owner unless a case says otherwise.
+ let base = Policy.resolvedPath(temporary.path)!
+ let store = base + "/Bundles"
+ let macOS = store + "/2.4.0/VPhone.bundle/Contents/MacOS"
+ let cli = macOS + "/vphone-cli"
+ try make(cli)
+ try make(macOS + "/vphone-vm")
+ try make(store + "/2.4.0/vphone-cli")
+ try make(store + "/a/b/VPhone.bundle/Contents/MacOS/vphone-cli")
+ try make(base + "/outside/VPhone.bundle/Contents/MacOS/vphone-cli")
+ try fileManager.createDirectory(
+ atPath: store + "/dir/VPhone.bundle/Contents/MacOS/vphone-cli", withIntermediateDirectories: true,
+ )
+ try fileManager.createDirectory(
+ atPath: store + "/2.5.0/VPhone.bundle/Contents/MacOS", withIntermediateDirectories: true,
+ )
+ try fileManager.createSymbolicLink(
+ atPath: store + "/2.5.0/VPhone.bundle/Contents/MacOS/vphone-cli",
+ withDestinationPath: base + "/outside/VPhone.bundle/Contents/MacOS/vphone-cli",
+ )
+ try fileManager.createSymbolicLink(atPath: base + "/link", withDestinationPath: cli)
+
+ func check(
+ _ executable: String,
+ _ arguments: [String] = launch,
+ root: String = store,
+ overrides: [String: Policy.FileStatus] = [:],
+ ) throws(VPhoneLaunchpadLauncherRefusal) -> String {
+ try Policy.check(executable: executable, arguments: arguments, storeRoot: root, resolve: Policy.resolvedPath) {
+ if let override = overrides[$0] {
+ return override
+ }
+ return Policy.fileStatus($0).map { Policy.FileStatus(owner: 0, mode: $0.mode) }
+ }
+ }
+
+ func expectRefused(
+ _ text: String,
+ _ executable: String,
+ _ arguments: [String] = launch,
+ root: String = store,
+ overrides: [String: Policy.FileStatus] = [:],
+ ) {
+ do {
+ let path = try check(executable, arguments, root: root, overrides: overrides)
+ fatalError("Expected a refusal (\(text)), accepted \(path)")
+ } catch {
+ precondition(error.message.contains(text), "Unexpected refusal: \(error.message)")
+ }
+ }
+
+ // The vphone-cli of a store entry, named directly or through a link
+ // from outside, runs from the store.
+ let accepted: [(String, [String])] = [
+ (cli, launch),
+ (base + "/link", launch),
+ (cli, ["vm", "launch", "research-01", "--dfu", "--library", "/tmp/x"]),
+ ]
+ for (path, arguments) in accepted {
+ let resolved = try check(path, arguments)
+ precondition(resolved == cli, "Accepted \(path) as \(resolved)")
+ }
+
+ // Only `vm launch <machine>`.
+ for arguments in [[], ["vm"], ["vm", "launch"], ["vm", "stop", "research-01"],
+ ["launch", "vm", "research-01"], ["--headless", "vm", "launch"],
+ ["cfw", "install", "research-01"]] {
+ expectRefused("only `vphone-cli vm launch <machine>`", cli, arguments)
+ }
+
+ // Only the vphone-cli of a bundle directly in the store.
+ for path in [base + "/outside/VPhone.bundle/Contents/MacOS/vphone-cli", macOS + "/vphone-vm",
+ store + "/2.4.0/vphone-cli", store + "/a/b/VPhone.bundle/Contents/MacOS/vphone-cli",
+ store + "/2.5.0/VPhone.bundle/Contents/MacOS/vphone-cli", "/bin/sh"] {
+ expectRefused("is not the vphone-cli of a bundle in \(store)", path)
+ }
+ expectRefused("is not a regular file", store + "/dir/VPhone.bundle/Contents/MacOS/vphone-cli")
+ expectRefused("does not exist", macOS + "/missing")
+ expectRefused("the bundle store", cli, root: base + "/none")
+
+ // The file and every directory up to / are root's alone.
+ let entries = [cli, macOS, store + "/2.4.0", store, base, "/"]
+ for path in entries {
+ let mode = Policy.fileStatus(path)!.mode
+ let rejected = [
+ Policy.FileStatus(owner: 501, mode: mode),
+ Policy.FileStatus(owner: 0, mode: mode | S_IWGRP),
+ Policy.FileStatus(owner: 0, mode: mode | S_IWOTH),
+ ]
+ for status in rejected {
+ expectRefused("\(path) must be owned by root", cli, overrides: [path: status])
+ }
+ }
+ expectRefused("\(macOS) is not a directory", cli, overrides: [macOS: Policy.FileStatus(owner: 0, mode: S_IFREG | 0o755)])
+ print("Launcher policy tests passed: accepted paths, arguments, store layout, ownership and modes")
+
+ if CommandLine.arguments.dropFirst().contains("--live") {
+ // Checks only; nothing is started.
+ let installed = (try? fileManager.contentsOfDirectory(atPath: VPhoneLaunchpadBundleStore.root.path)) ?? []
+ for version in installed.sorted() {
+ let path = VPhoneLaunchpadBundleStore.executable(version: version, named: "vphone-cli").path
+ do {
+ print("accepted \(try Policy.check(executable: path, arguments: launch))")
+ } catch {
+ print("refused \(version): \(error.message)")
+ }
+ }
+ }
+ }
+
+ static func make(_ path: String) throws {
+ let url = URL(fileURLWithPath: path)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: url)
+ }
+}
diff --git a/VPhoneLaunchpad/Tests/LauncherProcessTests.sh b/VPhoneLaunchpad/Tests/LauncherProcessTests.sh
new file mode 100755
index 00000000..1ca4d275
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/LauncherProcessTests.sh
@@ -0,0 +1,36 @@
+#!/bin/zsh
+set -euo pipefail
+
+launchpad="${0:a:h:h}"
+temporary="$(/usr/bin/mktemp -d)"
+trap '/bin/rm -rf "$temporary"' EXIT
+
+# The launcher as the Xcode target builds it: a usage error and a refusal
+# end with their own statuses before anything is started.
+/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \
+ -module-name VPhoneLaunchpadLauncher \
+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift" \
+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLauncherPolicy.swift" \
+ "$launchpad/VPhoneLaunchpadLauncher/"*.swift \
+ -o "$temporary/vphone-launchpad-launcher"
+expect_status() {
+ local expected=$1
+ shift
+ local actual=0
+ "$temporary/vphone-launchpad-launcher" "$@" 2>/dev/null || actual=$?
+ if (( actual != expected )); then
+ print -u2 "vphone-launchpad-launcher $*: expected status $expected, got $actual"
+ exit 1
+ fi
+}
+expect_status 64
+expect_status 77 /bin/sh vm launch research-01
+expect_status 77 /bin/sh -c 'exit 0'
+print "Launcher refusal tests passed: usage 64, refusal 77"
+
+/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \
+ -parse-as-library \
+ "$launchpad/VPhoneLaunchpadLauncher/VPhoneLaunchpadLauncherProcess.swift" \
+ "$launchpad/Tests/LauncherProcessTests.swift" \
+ -o "$temporary/launcher-process-tests"
+"$temporary/launcher-process-tests" "$@"
diff --git a/VPhoneLaunchpad/Tests/LauncherProcessTests.swift b/VPhoneLaunchpad/Tests/LauncherProcessTests.swift
new file mode 100644
index 00000000..ac8bb9fc
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/LauncherProcessTests.swift
@@ -0,0 +1,143 @@
+import Darwin
+import Foundation
+
+/// Drives the launcher's spawn, forward and wait core with /bin/sh. The
+/// launcher itself only starts a root-owned vphone-cli, so this binary runs
+/// the same core as a relay of its own (`--relay <program> <arguments…>`) and
+/// checks from outside what Launchpad would see.
+@main
+struct LauncherProcessTests {
+ static func main() throws {
+ let arguments = CommandLine.arguments
+ if arguments.count > 2, arguments[1] == "--relay" {
+ let argv = Array(arguments.dropFirst(2))
+ do {
+ let status = try VPhoneLaunchpadLauncherProcess.run(path: argv[0], argv: argv)
+ VPhoneLaunchpadLauncherProcess.exit(withStatusOf: status)
+ } catch {
+ fatalError(error.message)
+ }
+ }
+
+ // Exit codes come back unchanged.
+ for code in [0, 3, 255] as [Int32] {
+ let relay = try Relay("exit \(code)")
+ relay.expectExit(code)
+ }
+
+ // A child killed by a signal kills the launcher with the same one.
+ for signal in [SIGTERM, SIGKILL, SIGUSR1] {
+ let relay = try Relay("kill -\(signal) $$")
+ relay.expectSignal(signal)
+ }
+
+ // stdin, stdout, the working directory and the environment reach the
+ // child.
+ let directory = try FileManager.default.url(
+ for: .itemReplacementDirectory, in: .userDomainMask,
+ appropriateFor: FileManager.default.temporaryDirectory, create: true,
+ )
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let relay = try Relay(
+ "read line; printf '%s %s %s\\n' \"$line\" \"$VPHONE_LAUNCHER_TEST\" \"$(/bin/pwd -P)\"",
+ directory: directory,
+ environment: ["VPHONE_LAUNCHER_TEST": "inherited"],
+ input: "hello\n",
+ )
+ relay.expectExit(0)
+ let expected = "hello inherited \(realPath(directory.path))"
+ precondition(relay.output.hasPrefix(expected), "Unexpected output: \(relay.output)")
+
+ // Each stop signal is forwarded: the child's trap decides the exit
+ // code, and the launcher survives to report it.
+ let traps = VPhoneLaunchpadLauncherProcess.forwardedSignals.enumerated()
+ .map { "trap 'exit \(40 + $0.offset)' \($0.element)" }
+ .joined(separator: "; ")
+ for (offset, signal) in VPhoneLaunchpadLauncherProcess.forwardedSignals.enumerated() {
+ let relay = try Relay("\(traps); echo ready; while :; do /bin/sleep 0.05; done")
+ relay.waitForReady()
+ kill(relay.process.processIdentifier, signal)
+ relay.expectExit(Int32(40 + offset))
+ }
+
+ // The launcher ignores the forwarded signals itself, but a child
+ // without a trap gets them at their default and dies of them.
+ for signal in VPhoneLaunchpadLauncherProcess.forwardedSignals {
+ let relay = try Relay("echo ready; while :; do /bin/sleep 0.05; done")
+ relay.waitForReady()
+ kill(relay.process.processIdentifier, signal)
+ relay.expectSignal(signal)
+ }
+
+ print("Launcher process tests passed: exit codes, signal deaths, inherited stdio/cwd/environment, forwarded signals")
+ }
+}
+
+// MARK: - Relay
+
+final class Relay {
+ let process = Process()
+ private let outputPipe = Pipe()
+ private var collected = Data()
+ private let script: String
+
+ init(_ script: String, directory: URL? = nil, environment: [String: String] = [:], input: String? = nil) throws {
+ self.script = script
+ process.executableURL = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
+ process.arguments = ["--relay", "/bin/sh", "-c", script]
+ if let directory {
+ process.currentDirectoryURL = directory
+ }
+ process.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }
+ let stdin = Pipe()
+ process.standardInput = stdin
+ process.standardOutput = outputPipe
+ try process.run()
+ if let input {
+ stdin.fileHandleForWriting.write(Data(input.utf8))
+ }
+ try stdin.fileHandleForWriting.close()
+ }
+
+ var output: String {
+ String(decoding: collected, as: UTF8.self)
+ }
+
+ func waitForReady() {
+ while !output.contains("ready\n") {
+ let chunk = outputPipe.fileHandleForReading.availableData
+ precondition(!chunk.isEmpty, "\(script): exited before it was ready")
+ collected.append(chunk)
+ }
+ }
+
+ private func finish() {
+ collected.append(outputPipe.fileHandleForReading.readDataToEndOfFile())
+ process.waitUntilExit()
+ }
+
+ func expectExit(_ code: Int32) {
+ finish()
+ precondition(
+ process.terminationReason == .exit && process.terminationStatus == code,
+ "\(script): expected exit \(code), got \(process.terminationReason.rawValue)/\(process.terminationStatus)",
+ )
+ }
+
+ func expectSignal(_ signal: Int32) {
+ finish()
+ precondition(
+ process.terminationReason == .uncaughtSignal && process.terminationStatus == signal,
+ "\(script): expected signal \(signal), got \(process.terminationReason.rawValue)/\(process.terminationStatus)",
+ )
+ }
+}
+
+// /var is a symlink to /private/var; the child reports the physical path.
+func realPath(_ path: String) -> String {
+ guard let resolved = realpath(path, nil) else {
+ return path
+ }
+ defer { free(resolved) }
+ return String(cString: resolved)
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
index 5ff75e48..d5f5e144 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
+++ b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
@@ -9,15 +9,18 @@
5A1000000000000000000062 /* GhosttyTerminal in Frameworks */ = {isa = PBXBuildFile; productRef = 5A10000000000000000000B1 /* GhosttyTerminal */; };
5A10000000000000000000CC /* vphone-launchpad-cli in Embed Command Line Tool */ = {isa = PBXBuildFile; fileRef = 5A10000000000000000000C1 /* vphone-launchpad-cli */; };
5A10000000000000000000D2 /* vphone-guest-control in Embed Skill */ = {isa = PBXBuildFile; fileRef = 5A10000000000000000000D1 /* vphone-guest-control */; };
+ 5A10000000000000000000EC /* vphone-launchpad-launcher in Embed VM Launcher */ = {isa = PBXBuildFile; fileRef = 5A10000000000000000000E1 /* vphone-launchpad-launcher */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
5A1000000000000000000071 /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A1000000000000000000012; remoteInfo = VPhoneLaunchpadHelper; };
5A10000000000000000000CA /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A10000000000000000000C4; remoteInfo = VPhoneLaunchpadCLI; };
+ 5A10000000000000000000EA /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A10000000000000000000E4; remoteInfo = VPhoneLaunchpadLauncher; };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
5A1000000000000000000053 /* Embed Privileged Helper */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = Contents/Library/LaunchServices; dstSubfolderSpec = 1; files = (5A1000000000000000000061 /* com.vphone.launchpad.helper in Embed Privileged Helper */, ); name = "Embed Privileged Helper"; runOnlyForDeploymentPostprocessing = 0; };
5A10000000000000000000CD /* Embed Command Line Tool */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 6; files = (5A10000000000000000000CC /* vphone-launchpad-cli in Embed Command Line Tool */, ); name = "Embed Command Line Tool"; runOnlyForDeploymentPostprocessing = 0; };
5A10000000000000000000D3 /* Embed Skill */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = Skills; dstSubfolderSpec = 7; files = (5A10000000000000000000D2 /* vphone-guest-control in Embed Skill */, ); name = "Embed Skill"; runOnlyForDeploymentPostprocessing = 0; };
+ 5A10000000000000000000ED /* Embed VM Launcher */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 6; files = (5A10000000000000000000EC /* vphone-launchpad-launcher in Embed VM Launcher */, ); name = "Embed VM Launcher"; runOnlyForDeploymentPostprocessing = 0; };
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
5A1000000000000000000031 /* vphone-launchpad.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "vphone-launchpad.app"; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -34,34 +37,41 @@
5A10000000000000000000C1 /* vphone-launchpad-cli */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "vphone-launchpad-cli"; sourceTree = BUILT_PRODUCTS_DIR; };
5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpadCLI.xcconfig; sourceTree = "<group>"; };
5A10000000000000000000D1 /* vphone-guest-control */ = {isa = PBXFileReference; lastKnownFileType = folder; name = "vphone-guest-control"; path = "../Skills/vphone-guest-control"; sourceTree = SOURCE_ROOT; };
+ 5A10000000000000000000E1 /* vphone-launchpad-launcher */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "vphone-launchpad-launcher"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 5A10000000000000000000E2 /* VPhoneLaunchpadLauncher.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpadLauncher.xcconfig; sourceTree = "<group>"; };
+ 5A10000000000000000000F1 /* VPhoneLaunchpad.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = VPhoneLaunchpad.entitlements; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- 5A10000000000000000000CE /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = (VPhoneLaunchpadControl.swift, ); target = 5A1000000000000000000012 /* VPhoneLaunchpadHelper */; };
+ 5A10000000000000000000CE /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = (VPhoneLaunchpadControl.swift, VPhoneLaunchpadLauncherPolicy.swift, ); target = 5A1000000000000000000012 /* VPhoneLaunchpadHelper */; };
+ 5A10000000000000000000EE /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = (VPhoneLaunchpadControl.swift, VPhoneLaunchpadHelperProtocol.swift, VPhoneLaunchpadHostPolicy.swift, VPhoneLaunchpadLineReader.swift, ); target = 5A10000000000000000000E4 /* VPhoneLaunchpadLauncher */; };
+ 5A10000000000000000000EF /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = (VPhoneLaunchpadLauncherPolicy.swift, ); target = 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */; };
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
5A1000000000000000000021 /* VPhoneLaunchpad */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpad; sourceTree = "<group>"; };
5A1000000000000000000022 /* VPhoneLaunchpadHelper */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadHelper; sourceTree = "<group>"; };
- 5A1000000000000000000023 /* VPhoneLaunchpadShared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (5A10000000000000000000CE /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadShared; sourceTree = "<group>"; };
+ 5A1000000000000000000023 /* VPhoneLaunchpadShared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (5A10000000000000000000CE /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 5A10000000000000000000EE /* PBXFileSystemSynchronizedBuildFileExceptionSet */, 5A10000000000000000000EF /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadShared; sourceTree = "<group>"; };
5A10000000000000000000C3 /* VPhoneLaunchpadCLI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadCLI; sourceTree = "<group>"; };
+ 5A10000000000000000000E3 /* VPhoneLaunchpadLauncher */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadLauncher; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
5A1000000000000000000041 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (5A1000000000000000000062 /* GhosttyTerminal in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; };
5A1000000000000000000042 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
5A10000000000000000000C6 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+ 5A10000000000000000000E6 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
- 5A1000000000000000000002 = {isa = PBXGroup; children = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000022 /* VPhoneLaunchpadHelper */, 5A10000000000000000000C3 /* VPhoneLaunchpadCLI */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, 5A1000000000000000000004 /* Configuration */, 5A1000000000000000000005 /* Resources */, 5A1000000000000000000003 /* Products */, ); sourceTree = "<group>"; };
- 5A1000000000000000000003 /* Products */ = {isa = PBXGroup; children = (5A1000000000000000000031 /* vphone-launchpad.app */, 5A1000000000000000000032 /* com.vphone.launchpad.helper */, 5A10000000000000000000C1 /* vphone-launchpad-cli */, ); name = Products; sourceTree = "<group>"; };
- 5A1000000000000000000004 /* Configuration */ = {isa = PBXGroup; children = (5A1000000000000000000037 /* Version.xcconfig */, 5A1000000000000000000033 /* Base.xcconfig */, 5A1000000000000000000038 /* Development.xcconfig */, 5A1000000000000000000039 /* Release.xcconfig */, 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */, 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */, 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */, ); path = Configuration; sourceTree = "<group>"; };
- 5A1000000000000000000005 /* Resources */ = {isa = PBXGroup; children = (5A1000000000000000000034 /* VPhoneLaunchpad.Info.plist */, 5A1000000000000000000035 /* VPhoneLaunchpadHelper.Info.plist */, 5A1000000000000000000036 /* VPhoneLaunchpadHelper.Launchd.plist */, 5A10000000000000000000D1 /* vphone-guest-control */, ); path = Resources; sourceTree = "<group>"; };
+ 5A1000000000000000000002 = {isa = PBXGroup; children = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000022 /* VPhoneLaunchpadHelper */, 5A10000000000000000000C3 /* VPhoneLaunchpadCLI */, 5A10000000000000000000E3 /* VPhoneLaunchpadLauncher */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, 5A1000000000000000000004 /* Configuration */, 5A1000000000000000000005 /* Resources */, 5A1000000000000000000003 /* Products */, ); sourceTree = "<group>"; };
+ 5A1000000000000000000003 /* Products */ = {isa = PBXGroup; children = (5A1000000000000000000031 /* vphone-launchpad.app */, 5A1000000000000000000032 /* com.vphone.launchpad.helper */, 5A10000000000000000000C1 /* vphone-launchpad-cli */, 5A10000000000000000000E1 /* vphone-launchpad-launcher */, ); name = Products; sourceTree = "<group>"; };
+ 5A1000000000000000000004 /* Configuration */ = {isa = PBXGroup; children = (5A1000000000000000000037 /* Version.xcconfig */, 5A1000000000000000000033 /* Base.xcconfig */, 5A1000000000000000000038 /* Development.xcconfig */, 5A1000000000000000000039 /* Release.xcconfig */, 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */, 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */, 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */, 5A10000000000000000000E2 /* VPhoneLaunchpadLauncher.xcconfig */, ); path = Configuration; sourceTree = "<group>"; };
+ 5A1000000000000000000005 /* Resources */ = {isa = PBXGroup; children = (5A1000000000000000000034 /* VPhoneLaunchpad.Info.plist */, 5A10000000000000000000F1 /* VPhoneLaunchpad.entitlements */, 5A1000000000000000000035 /* VPhoneLaunchpadHelper.Info.plist */, 5A1000000000000000000036 /* VPhoneLaunchpadHelper.Launchd.plist */, 5A10000000000000000000D1 /* vphone-guest-control */, ); path = Resources; sourceTree = "<group>"; };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
5A1000000000000000000011 /* VPhoneLaunchpad */ = {
isa = PBXNativeTarget;
buildConfigurationList = 5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */;
- buildPhases = (5A1000000000000000000051 /* Sources */, 5A1000000000000000000041 /* Frameworks */, 5A1000000000000000000052 /* Resources */, 5A1000000000000000000053 /* Embed Privileged Helper */, 5A10000000000000000000CD /* Embed Command Line Tool */, 5A10000000000000000000D3 /* Embed Skill */, );
+ buildPhases = (5A1000000000000000000051 /* Sources */, 5A1000000000000000000041 /* Frameworks */, 5A1000000000000000000052 /* Resources */, 5A1000000000000000000053 /* Embed Privileged Helper */, 5A10000000000000000000CD /* Embed Command Line Tool */, 5A10000000000000000000ED /* Embed VM Launcher */, 5A10000000000000000000D3 /* Embed Skill */, );
buildRules = ();
- dependencies = (5A1000000000000000000072 /* PBXTargetDependency */, 5A10000000000000000000CB /* PBXTargetDependency */, );
+ dependencies = (5A1000000000000000000072 /* PBXTargetDependency */, 5A10000000000000000000CB /* PBXTargetDependency */, 5A10000000000000000000EB /* PBXTargetDependency */, );
fileSystemSynchronizedGroups = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );
name = VPhoneLaunchpad;
packageProductDependencies = (5A10000000000000000000B1 /* GhosttyTerminal */, );
@@ -93,6 +103,18 @@
productReference = 5A10000000000000000000C1 /* vphone-launchpad-cli */;
productType = "com.apple.product-type.tool";
};
+ 5A10000000000000000000E4 /* VPhoneLaunchpadLauncher */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 5A10000000000000000000E9 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadLauncher" */;
+ buildPhases = (5A10000000000000000000E5 /* Sources */, 5A10000000000000000000E6 /* Frameworks */, );
+ buildRules = ();
+ dependencies = ();
+ fileSystemSynchronizedGroups = (5A10000000000000000000E3 /* VPhoneLaunchpadLauncher */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );
+ name = VPhoneLaunchpadLauncher;
+ productName = VPhoneLaunchpadLauncher;
+ productReference = 5A10000000000000000000E1 /* vphone-launchpad-launcher */;
+ productType = "com.apple.product-type.tool";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
5A1000000000000000000001 /* Project object */ = {
@@ -107,7 +129,7 @@
productRefGroup = 5A1000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
- targets = (5A1000000000000000000011 /* VPhoneLaunchpad */, 5A1000000000000000000012 /* VPhoneLaunchpadHelper */, 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */, );
+ targets = (5A1000000000000000000011 /* VPhoneLaunchpad */, 5A1000000000000000000012 /* VPhoneLaunchpadHelper */, 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */, 5A10000000000000000000E4 /* VPhoneLaunchpadLauncher */, );
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
@@ -117,10 +139,12 @@
5A1000000000000000000051 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
5A1000000000000000000054 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
5A10000000000000000000C5 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+ 5A10000000000000000000E5 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
5A1000000000000000000072 /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 5A1000000000000000000012 /* VPhoneLaunchpadHelper */; targetProxy = 5A1000000000000000000071 /* PBXContainerItemProxy */; };
5A10000000000000000000CB /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */; targetProxy = 5A10000000000000000000CA /* PBXContainerItemProxy */; };
+ 5A10000000000000000000EB /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 5A10000000000000000000E4 /* VPhoneLaunchpadLauncher */; targetProxy = 5A10000000000000000000EA /* PBXContainerItemProxy */; };
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
5A1000000000000000000081 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A1000000000000000000038 /* Development.xcconfig */; buildSettings = {}; name = Debug; };
@@ -131,12 +155,15 @@
5A1000000000000000000086 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */; buildSettings = {}; name = Release; };
5A10000000000000000000C7 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */; buildSettings = {}; name = Debug; };
5A10000000000000000000C8 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */; buildSettings = {}; name = Release; };
+ 5A10000000000000000000E7 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A10000000000000000000E2 /* VPhoneLaunchpadLauncher.xcconfig */; buildSettings = {}; name = Debug; };
+ 5A10000000000000000000E8 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A10000000000000000000E2 /* VPhoneLaunchpadLauncher.xcconfig */; buildSettings = {}; name = Release; };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
5A1000000000000000000091 /* Build configuration list for PBXProject "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000081 /* Debug */, 5A1000000000000000000082 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000083 /* Debug */, 5A1000000000000000000084 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
5A1000000000000000000093 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadHelper" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000085 /* Debug */, 5A1000000000000000000086 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
5A10000000000000000000C9 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadCLI" */ = {isa = XCConfigurationList; buildConfigurations = (5A10000000000000000000C7 /* Debug */, 5A10000000000000000000C8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
+ 5A10000000000000000000E9 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadLauncher" */ = {isa = XCConfigurationList; buildConfigurations = (5A10000000000000000000E7 /* Debug */, 5A10000000000000000000E8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
5A10000000000000000000A1 /* XCRemoteSwiftPackageReference "libghostty-spm" */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/Lakr233/libghostty-spm.git"; requirement = {kind = upToNextMajorVersion; minimumVersion = 1.6.20260928; }; };
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift
index d15b4791..008df1d9 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift
@@ -10,10 +10,23 @@ import Foundation
/// pipe, quitting the app would close the read end and the next line of
/// guest serial output would kill the VM with SIGPIPE. The file is tailed
/// while the app runs and stays behind as the machine's console log.
-/// The guest is also detached: it gets its own session and is responsible
-/// for itself, so macOS does not keep Launchpad listed as running in the
-/// background, or attribute the guest's privacy prompts to it, after the
-/// app quits.
+/// The guest is also detached: it gets its own session and Launchpad
+/// disclaims responsibility for it, so macOS does not keep Launchpad listed
+/// as running in the background after the app quits.
+///
+/// What is started detached is `vphone-launchpad-launcher` from the app's
+/// Contents/MacOS, with `vphone-cli` and its arguments after it. The
+/// launcher is responsible for itself and starts `vphone-cli` without
+/// disclaiming, so it is responsible for `vphone-vm` and its Virtualization
+/// service. macOS ties a privacy permission (microphone, location) to the
+/// responsible process's signature. `vphone-cli` is signed ad hoc, so every
+/// bundle build would be asked again. A tool in the app's Contents/MacOS
+/// is attributed to the app, so the request is the app's and is asked
+/// once for its Developer ID signature; under the hardened runtime the app
+/// needs the matching entitlement (Resources/VPhoneLaunchpad.entitlements).
+/// Without the launcher (previews, a build that lacks it) or for a
+/// `vphone-cli` it would refuse, Launchpad starts `vphone-cli` directly,
+/// responsible for itself as before.
final nonisolated class VPhoneLaunchpadChildProcess: @unchecked Sendable {
private let process = Process()
/// Set instead of `process` for a detached child.
@@ -44,9 +57,10 @@ final nonisolated class VPhoneLaunchpadChildProcess: @unchecked Sendable {
withIntermediateDirectories: true,
)
FileManager.default.createFile(atPath: logFile.path, contents: nil)
+ let command = Self.throughLauncher(executable: executable, arguments: arguments)
let pid = try Self.spawnDetached(
- executable: executable,
- arguments: arguments,
+ executable: command.executable,
+ arguments: command.arguments,
currentDirectory: currentDirectory,
logFile: logFile,
)
@@ -112,7 +126,8 @@ final nonisolated class VPhoneLaunchpadChildProcess: @unchecked Sendable {
private func signal(_ signal: Int32) {
if let detachedPID {
// Until waitpid reaps it the PID cannot be reused, so this only
- // ever reaches our own child.
+ // ever reaches our own child. The launcher passes the signal on
+ // to vphone-cli and exits the way it does.
if lock.withLock({ !hasExited }) {
kill(detachedPID, signal)
}
@@ -140,6 +155,23 @@ final nonisolated class VPhoneLaunchpadChildProcess: @unchecked Sendable {
// MARK: - Detached spawn
+ /// The launcher with `executable` and `arguments` after it, when the app
+ /// carries one and it would accept them; otherwise the command unchanged.
+ private static func throughLauncher(
+ executable: URL,
+ arguments: [String],
+ ) -> (executable: URL, arguments: [String]) {
+ guard let launcher = Bundle.main.executableURL?
+ .deletingLastPathComponent()
+ .appendingPathComponent(VPhoneLaunchpadLauncherPolicy.executableName),
+ FileManager.default.isExecutableFile(atPath: launcher.path),
+ (try? VPhoneLaunchpadLauncherPolicy.check(executable: executable.path, arguments: arguments)) != nil
+ else {
+ return (executable, arguments)
+ }
+ return (launcher, [executable.path] + arguments)
+ }
+
private typealias SetDisclaim = @convention(c) (UnsafeMutablePointer<posix_spawnattr_t?>, Int32) -> Int32
/// Starts `executable` in a new session, responsible for itself, with
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadLauncher/VPhoneLaunchpadLauncherProcess.swift b/VPhoneLaunchpad/VPhoneLaunchpadLauncher/VPhoneLaunchpadLauncherProcess.swift
new file mode 100644
index 00000000..58b135e5
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadLauncher/VPhoneLaunchpadLauncherProcess.swift
@@ -0,0 +1,143 @@
+import Darwin
+
+// MARK: - Failure
+
+nonisolated struct VPhoneLaunchpadLauncherFailure: Error {
+ let message: String
+}
+
+// MARK: - Child process
+
+/// Runs one child for the launcher's whole life. The child is started without
+/// disclaiming responsibility, so the process responsible for the launcher is
+/// responsible for it too. The launcher only forwards stop signals and waits.
+nonisolated enum VPhoneLaunchpadLauncherProcess {
+ /// What Launchpad sends to stop a VM, plus what a terminal would.
+ static let forwardedSignals: [Int32] = [SIGINT, SIGTERM, SIGHUP, SIGQUIT]
+
+ /// Starts `path` with `argv` (argv[0] included), inheriting stdin, stdout,
+ /// stderr, the working directory and the environment, and returns its wait
+ /// status once it exits. The forwarded signals reach the child, not the
+ /// launcher.
+ static func run(path: String, argv: [String]) throws(VPhoneLaunchpadLauncherFailure) -> Int32 {
+ let queue = kqueue()
+ guard queue >= 0 else {
+ throw VPhoneLaunchpadLauncherFailure(message: "kqueue failed: \(String(cString: strerror(errno)))")
+ }
+ defer { close(queue) }
+
+ // A kqueue records a signal even while it is ignored, so ignoring them
+ // here keeps the launcher alive and still sees each one. Signals that
+ // arrive before the child exists are forwarded once it does. Those at
+ // their default go back to it in the child; an inherited SIG_IGN is
+ // inherited as before.
+ var defaults = sigset_t()
+ sigemptyset(&defaults)
+ var changes: [kevent] = []
+ for number in forwardedSignals {
+ var previous = sigaction()
+ sigaction(number, nil, &previous)
+ if unsafeBitCast(previous.__sigaction_u, to: Int.self) == 0 {
+ sigaddset(&defaults, number)
+ }
+ var ignore = sigaction()
+ ignore.__sigaction_u.__sa_handler = SIG_IGN
+ sigaction(number, &ignore, nil)
+ changes.append(kevent(
+ ident: UInt(number), filter: Int16(EVFILT_SIGNAL), flags: UInt16(EV_ADD),
+ fflags: 0, data: 0, udata: nil,
+ ))
+ }
+ guard kevent(queue, changes, Int32(changes.count), nil, 0, nil) == 0 else {
+ throw VPhoneLaunchpadLauncherFailure(message: "kevent failed: \(String(cString: strerror(errno)))")
+ }
+
+ let pid = try spawn(path: path, argv: argv, defaults: &defaults)
+
+ var childExit = kevent(
+ ident: UInt(pid), filter: Int16(EVFILT_PROC), flags: UInt16(EV_ADD | EV_ONESHOT),
+ fflags: UInt32(NOTE_EXIT), data: 0, udata: nil,
+ )
+ // ESRCH: the child already exited and only waits to be reaped.
+ var running = kevent(queue, &childExit, 1, nil, 0, nil) == 0
+ while running {
+ var event = kevent()
+ let count = kevent(queue, nil, 0, &event, 1, nil)
+ if count < 0 {
+ if errno == EINTR {
+ continue
+ }
+ break
+ }
+ if event.filter == Int16(EVFILT_SIGNAL) {
+ // Until waitpid reaps it the PID cannot be reused, so this
+ // only ever reaches our own child.
+ kill(pid, Int32(event.ident))
+ } else if event.filter == Int16(EVFILT_PROC) {
+ running = false
+ }
+ }
+
+ var status: Int32 = 0
+ while waitpid(pid, &status, 0) == -1, errno == EINTR {}
+ return status
+ }
+
+ /// Ends the launcher the way the child ended: with its exit code, or
+ /// killed by the same signal, so whoever waits for the launcher sees the
+ /// same status it would have seen for the child.
+ static func exit(withStatusOf status: Int32) -> Never {
+ let signal = status & 0x7F
+ guard signal != 0 else {
+ Darwin.exit((status >> 8) & 0xFF)
+ }
+ // The child already dumped core if it was going to.
+ var limit = rlimit(rlim_cur: 0, rlim_max: 0)
+ setrlimit(RLIMIT_CORE, &limit)
+ var reset = sigaction()
+ reset.__sigaction_u.__sa_handler = SIG_DFL
+ sigaction(signal, &reset, nil)
+ var unblock = sigset_t()
+ sigemptyset(&unblock)
+ sigaddset(&unblock, signal)
+ sigprocmask(SIG_UNBLOCK, &unblock, nil)
+ kill(getpid(), signal)
+ Darwin.exit(128 + signal)
+ }
+
+ // MARK: - Spawn
+
+ private static func spawn(
+ path: String,
+ argv: [String],
+ defaults: inout sigset_t,
+ ) throws(VPhoneLaunchpadLauncherFailure) -> pid_t {
+ var attributes: posix_spawnattr_t?
+ posix_spawnattr_init(&attributes)
+ defer { posix_spawnattr_destroy(&attributes) }
+ // No POSIX_SPAWN_SETSID and no disclaim: the child stays in the
+ // launcher's session, and the launcher stays responsible for it.
+ posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_CLOEXEC_DEFAULT))
+ posix_spawnattr_setsigdefault(&attributes, &defaults)
+
+ // Only the standard descriptors, which is all Launchpad gives the
+ // launcher. The kqueue stays behind.
+ var actions: posix_spawn_file_actions_t?
+ posix_spawn_file_actions_init(&actions)
+ defer { posix_spawn_file_actions_destroy(&actions) }
+ for descriptor in [STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO] where fcntl(descriptor, F_GETFD) != -1 {
+ posix_spawn_file_actions_addinherit_np(&actions, descriptor)
+ }
+
+ let arguments = argv.map { strdup($0) } + [nil]
+ defer { arguments.forEach { free($0) } }
+ var pid: pid_t = 0
+ let result = posix_spawn(&pid, path, &actions, &attributes, arguments, environ)
+ guard result == 0 else {
+ throw VPhoneLaunchpadLauncherFailure(
+ message: "unable to start \(path): \(String(cString: strerror(result)))",
+ )
+ }
+ return pid
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadLauncher/main.swift b/VPhoneLaunchpad/VPhoneLaunchpadLauncher/main.swift
new file mode 100644
index 00000000..24ae3dbe
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadLauncher/main.swift
@@ -0,0 +1,49 @@
+import Darwin
+
+// vphone-launchpad-launcher: the process macOS holds responsible for every VM
+// Launchpad starts. Launchpad starts it detached and responsible for itself;
+// it starts `vphone-cli vm launch …` as an ordinary child and stays until that
+// exits. As a tool in the app's Contents/MacOS it is attributed to the app,
+// so privacy permissions the guest uses are asked for, and granted to, the
+// Developer ID signed app once, instead of each ad hoc signed VPhone.bundle
+// build. Because those grants are worth borrowing, it starts
+// nothing but `vm launch` of a vphone-cli in the root-owned bundle store.
+//
+// Exit status: the child's, or the child's signal; 64 for a usage error, 77
+// for a refusal, 71 when the child cannot be started.
+
+// MARK: - Status
+
+let usageStatus: Int32 = 64
+let refusedStatus: Int32 = 77
+let failedStatus: Int32 = 71
+
+func fail(_ status: Int32, _ message: String) -> Never {
+ let line = "vphone-launchpad-launcher: \(message)\n"
+ _ = line.withCString { write(STDERR_FILENO, $0, strlen($0)) }
+ exit(status)
+}
+
+// MARK: - Main
+
+let arguments = Array(CommandLine.arguments.dropFirst())
+guard let executable = arguments.first else {
+ fail(usageStatus, "usage: vphone-launchpad-launcher <vphone-cli> vm launch <machine> [options]")
+}
+
+let path: String
+do {
+ path = try VPhoneLaunchpadLauncherPolicy.check(executable: executable, arguments: Array(arguments.dropFirst()))
+} catch {
+ fail(refusedStatus, "refused: \(error.message)")
+}
+
+let status: Int32
+do {
+ // argv[0] stays the path Launchpad named, as when it started vphone-cli
+ // itself.
+ status = try VPhoneLaunchpadLauncherProcess.run(path: path, argv: arguments)
+} catch {
+ fail(failedStatus, error.message)
+}
+VPhoneLaunchpadLauncherProcess.exit(withStatusOf: status)
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLauncherPolicy.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLauncherPolicy.swift
new file mode 100644
index 00000000..6f59a454
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLauncherPolicy.swift
@@ -0,0 +1,141 @@
+import Darwin
+import Foundation
+
+// MARK: - Refusal
+
+nonisolated struct VPhoneLaunchpadLauncherRefusal: Error, CustomStringConvertible {
+ let message: String
+
+ init(_ message: String) {
+ self.message = message
+ }
+
+ var description: String {
+ message
+ }
+}
+
+// MARK: - Policy
+
+/// What `vphone-launchpad-launcher` agrees to start. The app checks it to
+/// decide whether to go through the launcher; the launcher checks it again
+/// because anything on the machine can run it.
+///
+/// The launcher is attributed to the Developer ID signed app it ships in, so
+/// every VM it starts uses the app's privacy permissions (microphone,
+/// location). Running any path it was given would let any local
+/// process borrow them. It therefore only starts `vm launch` of a `vphone-cli`
+/// in the root-owned bundle store, where nobody but root can change what that
+/// path runs.
+nonisolated enum VPhoneLaunchpadLauncherPolicy {
+ static let executableName = "vphone-launchpad-launcher"
+
+ /// The part of the path below a store entry.
+ static let executableTail = ["VPhone.bundle", "Contents", "MacOS", "vphone-cli"]
+
+ /// The leading arguments every start must have. Launchpad goes through
+ /// the launcher only for commands that outlive it, and that is always
+ /// `vm launch`.
+ static let requiredArguments = ["vm", "launch"]
+
+ struct FileStatus: Equatable {
+ let owner: uid_t
+ let mode: mode_t
+
+ var isDirectory: Bool {
+ mode & S_IFMT == S_IFDIR
+ }
+
+ var isRegularFile: Bool {
+ mode & S_IFMT == S_IFREG
+ }
+
+ /// Writable by anyone but its owner.
+ var isSharedWritable: Bool {
+ mode & (S_IWGRP | S_IWOTH) != 0
+ }
+ }
+
+ typealias Resolve = (String) -> String?
+ typealias Status = (String) -> FileStatus?
+
+ /// The executable `path` names once symlinks are followed.
+ static func resolvedPath(_ path: String) -> String? {
+ guard let resolved = realpath(path, nil) else {
+ return nil
+ }
+ defer { free(resolved) }
+ return String(cString: resolved)
+ }
+
+ /// `lstat`, so a symlink is never taken for what it points at.
+ static func fileStatus(_ path: String) -> FileStatus? {
+ var information = stat()
+ guard lstat(path, &information) == 0 else {
+ return nil
+ }
+ return FileStatus(owner: information.st_uid, mode: information.st_mode)
+ }
+
+ /// The path to execute for `executable` with `arguments`, or a refusal
+ /// that says why not. Every directory from the file up to `/` must be
+ /// owned by root and writable by nobody else, so the path cannot be
+ /// redirected after this check.
+ static func check(
+ executable: String,
+ arguments: [String],
+ storeRoot: String = VPhoneLaunchpadBundleStore.root.path,
+ resolve: Resolve = resolvedPath,
+ status: Status = fileStatus,
+ ) throws(VPhoneLaunchpadLauncherRefusal) -> String {
+ guard arguments.count > requiredArguments.count,
+ Array(arguments.prefix(requiredArguments.count)) == requiredArguments
+ else {
+ throw VPhoneLaunchpadLauncherRefusal("only `vphone-cli vm launch <machine>` can be started")
+ }
+ guard let root = resolve(storeRoot) else {
+ throw VPhoneLaunchpadLauncherRefusal("the bundle store \(storeRoot) does not exist")
+ }
+ guard let path = resolve(executable) else {
+ throw VPhoneLaunchpadLauncherRefusal("\(executable) does not exist")
+ }
+ let rootComponents = components(root)
+ let pathComponents = components(path)
+ guard pathComponents.count == rootComponents.count + 1 + executableTail.count,
+ Array(pathComponents.prefix(rootComponents.count)) == rootComponents,
+ Array(pathComponents.suffix(executableTail.count)) == executableTail
+ else {
+ throw VPhoneLaunchpadLauncherRefusal(
+ "\(path) is not the vphone-cli of a bundle in \(root)",
+ )
+ }
+
+ guard let file = status(path), file.isRegularFile else {
+ throw VPhoneLaunchpadLauncherRefusal("\(path) is not a regular file")
+ }
+ try requireRootOnly(path, file)
+ for count in stride(from: pathComponents.count - 1, through: 0, by: -1) {
+ let directory = "/" + pathComponents.prefix(count).joined(separator: "/")
+ guard let entry = status(directory), entry.isDirectory else {
+ throw VPhoneLaunchpadLauncherRefusal("\(directory) is not a directory")
+ }
+ try requireRootOnly(directory, entry)
+ }
+ return path
+ }
+
+ private static func requireRootOnly(
+ _ path: String,
+ _ entry: FileStatus,
+ ) throws(VPhoneLaunchpadLauncherRefusal) {
+ guard entry.owner == 0, !entry.isSharedWritable else {
+ throw VPhoneLaunchpadLauncherRefusal(
+ "\(path) must be owned by root and writable by nobody else",
+ )
+ }
+ }
+
+ private static func components(_ path: String) -> [String] {
+ path.split(separator: "/").map(String.init)
+ }
+}