Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add a scripting session to vphoned, and a terminal for it
Lakr9b32069ebece
diff --git a/Research/Firmware/tvos_support.md b/Research/Firmware/tvos_support.mdindex 733e67ba..ae9cb439 100644--- a/Research/Firmware/tvos_support.md+++ b/Research/Firmware/tvos_support.md@@ -412,6 +412,21 @@ Verified on 23L5208m and 23L773: `vm wait` returns, `device.info` reports`own_name` "Apple TV", screenshots and `apps.launch` work, and consumer-pageHID input moves the TVSetup focus.+A TV guest has no shell, no package manager, and the `tvos` preset admits+neither debugserver nor any Frida patch, so the scripting session is the+debugging environment there: `script.eval` and the `/v1/shell` WebSocket run+JavaScript with vphoned's identity inside the guest. JavaScriptCore is a+public tvOS framework and the tvOS SDK ships its stub, so nothing has to be+installed. See "Scripting sessions" in `Research/vphoned_http_api.md`.++Nothing about the session needed a tvOS build: the tvOS SDK marks+`posix_spawn`, `execv` and the rest of the process API `__TVOS_PROHIBITED`,+but `vphoned-tvos` is the iOS build with its platform retagged, so those+declarations are never consulted, and the proxy has been spawning its worker+that way on TV guests all along. Compiling the daemon against the tvOS SDK+would fail on them; do not try to, and do not guard the session's code for+tvOS availability.+## TV button, Home and Control CenterA USB keyboard cannot press the TV button: no keyboard-page key maps to it.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex ab2ed577..2ffdd731 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -287,6 +287,114 @@ WebSocket fragmentation is reassembled before forwarding. On disconnect, theguest tunnel and the host TCP-to-VSOCK proxy let their final queued writefinish before closing the opposite socket, with a five-second drain limit.+## Scripting sessions++A guest has no shell, and the `tvos` preset has neither debugserver nor any+Frida patch, so a script run with vphoned's own identity is the only way to+reach what the guest keeps to itself. The runtime is JavaScriptCore, which+iOS and tvOS ship and watchOS does not; vphoned links it weakly and reports+`script_js` in `capabilities` only where it is present. `shell` is reported+everywhere, because the interactive route also runs a program from the+bootstrap.++Every session is a process of its own, spawned from vphoned's own executable+(`--session`), so it carries the same signature and entitlements as the+daemon and nothing else. A script that crashes, over-releases an object or+never returns ends its own session and no more: the worker keeps serving, and+`processes.list` shows nothing left behind. Each session leads its own+process group, so a program a script started dies with it rather than+outliving it as an orphan. None of the worker's startup has run in a session,+which is the one thing a script cannot work around: methods that depend on+state the worker set up at startup, such as the virtual camera or the+preloaded HID symbols, are not available through a session's `api()`.++`POST /v1/rpc` with `script.eval` takes `{source, timeout?}` and answers+`{ok, result, output, crashed}`, or `{ok: false, error, output, crashed}`. A+script that throws is an answer rather than a failed request, so its output+comes back either way; `result` is the value described as text and `output`+is everything the script printed. `timeout` defaults to 30 seconds and is+clamped to 1 through 600; a script that outruns it is killed with its group+and the request fails. `crashed` is true when the session died before it+could answer, and `error` then names the signal. `script.info` reports+`available`, `engine`, the globals below, and which of `bash`, `sh` and `zsh`+this guest's bootstrap actually has.++For an interactive session, upgrade `GET /v1/shell` to WebSocket. Admission+is the same as `/v1/events`: no `Origin`, a loopback `Host`, and the host+proxy's token in front of it. `program` selects what runs — unset or `repl`+for vphoned's JavaScript session, a bare name resolved from the bootstrap's+`bin`, `usr/bin` and `usr/local/bin`, or an absolute path. `cols` and `rows`+set the initial terminal size. Each binary frame is a chunk of the terminal's+byte stream in either direction, so `^C` is simply byte 3 and the terminal+driver turns it into a signal. Text frames from the client are control+messages, `{"resize": [columns, rows]}` and `{"signal": "INT"}`; the server+sends one text frame last, `{"exit": status}` or `{"signal": number}`, and a+session that could not be opened at all sends `{"error": message}` and closes+with 1011. The session is a session leader with the terminal as its+controlling one, claimed by the child rather than by `posix_spawn`'s file+actions so the order never depends on the kernel's. Closing the WebSocket+hangs the terminal up, and a session still running three seconds later is+killed with its group. Output is written one frame at a time and the next+read waits for it, so a client that cannot keep up slows the session down+instead of filling the worker's memory.++Two things on the Mac open this route rather than asking a client to speak+WebSocket itself. The VM window has **Diagnostics ▸ Session** (⌥⌘T), a+terminal view on a session of its own, closed with the window. And+`{"t":"shell"}` on the machine's `vphone.sock` hands that connection to the+terminal. The end of that client's input reaches the terminal as a `^D`+rather than hanging it up, because `nc` and pipes shut their sending half as+soon as their input runs out, so a pipe into `nc -U` runs as a script and+still gets the session's last output; only a client gone altogether hangs the+terminal up. See `Skills/vphone-guest-control/references/guest-socket.md`.+Both go through the+VM process's own VSOCK connection, so neither needs `--api-listen` or a token.++A guest runs at most 8 interactive sessions and 16 scripts at once. Each one+is a process, and a script holds its place in the concurrent queue the rest+of the API shares for as long as its timeout allows, so the request past+either limit is refused outright — `{"error": …}` and close 1011 for+`/v1/shell`, `operation_failed` for `script.eval` — rather than answered+slowly with everything else queued behind it.++The session's globals are `ObjC`, `api`, `fs`, `proc`, `console`, `print`,+`sleep` and `exit`. `ObjC.use('NSProcessInfo')` and+`ObjC.classes.NSProcessInfo` both give a class, and methods are called by+name: an underscore stands for a colon (`setValue_forKey_(v, k)`), a bare+name takes one colon per argument, and a name written with colons is used as+it stands (`obj['setValue:forKey:'](v, k)`). Dispatch is `NSInvocation` over+the method signature the runtime reports, so every method it can describe can+be called and an `NSException` arrives as a JavaScript error rather than a+crash. A string, a number and a date come back as themselves; everything+else, collections included, stays an object, because converting an `NSArray`+would hand back a copy of something a script asked for in order to mutate.+`$value` converts one when that is what was wanted, `$class` names the class+and `$isClass` says whether it is one. A JavaScript array or object passed+where an object is expected is converted on the way in. Three things are+deliberately not supported: struct arguments and returns, which would need+the encoding's layout read out (`frame`, `bounds` and `operatingSystemVersion`+raise a refusal that names the type), pointer arguments other than null, and+variadic methods, which the runtime cannot describe. An `alloc` comes back as+an object and never as a value, because an allocated `NSString` is a+placeholder that raises on anything but an initializer.++`api(method, params)` runs any method in this catalog in the session's own+process and returns its result, raising the error if it fails. `fs.ls`,+`fs.read`, `fs.write` and `fs.stat` are the root-privileged file operations,+`proc.run(path, args, input)` runs one program and collects+`{status, signal, stdout, stderr}`, and `console.log` and `print` write to+the terminal, or into `output` for `script.eval`.++This opens no privilege the API did not already have: the same connection can+already write any file as root and load a launch daemon. What it does change+is how directly that privilege is reached, so the host proxy's token and the+loopback checks are the whole of the protection, exactly as for every other+method. Nothing in the daemon's entitlements is granted per session; a+session is vphoned. The daemon does carry `dynamic-codesigning` so that+JavaScriptCore can use its JIT, and JSC falls back to its interpreter by+itself where that is refused, so a guest whose AMFI declines it still runs+scripts, more slowly.+`apps.launch` returns a PID and `frontmost_verified`. IcliKit 0.6.8 checksRunningBoard's live focal assertion and accepts it only when one real app ownsit. iOS 26.6.2 uses `SuspendableRole-UIFocal`; older systems may use@@ -392,6 +500,7 @@ request carries `"force": true`.| Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) || Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) || Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID the guest gives its profile checks and the host (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids`, `usb_serial` and `usb_reenumerated` (see below) |+| Scripting | `script.eval {source, timeout?}` (`{ok, result, output, crashed}`; evaluated in a session process, capability `script_js`), `script.info` (`{available, engine, globals, programs}`) — the interactive form is the `/v1/shell` WebSocket, see "Scripting sessions" || Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version, data_migration_done}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`; while the first boot's data migration is still running it does not restart SpringBoard, which reads the keys when migration ends, and `respring` is `{restarted: false, reason: "data_migration_pending"}`; a restart FrontBoard ignored is refused with `reason: busy`, `retryable: true`, the keys already written); `setup.settle {timeout_s?, poll_s?, stable_polls?}` (read-only wait for first-boot work, see below); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |`input.hid` sends a keyboard/consumer usage with 16-bit `page` and `usage`.@@ -1040,6 +1149,16 @@ curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8765/v1/healthcurl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \-d '{"method":"device.snapshot","params":{}}' http://127.0.0.1:8765/v1/rpcwebsocat "ws://127.0.0.1:8765/v1/events?token=$TOKEN"++# One script, with its value and whatever it printed.+curl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \+ -d '{"method":"script.eval","params":{"source":"api(\"device.snapshot\").name"}}' \+ http://127.0.0.1:8765/v1/rpc++# An interactive session. websocat sends what it reads as text frames, so pass+# --binary; it has no window size to report, so the terminal starts at 80x24.+websocat --binary "ws://127.0.0.1:8765/v1/shell?token=$TOKEN&cols=120&rows=40"+websocat --binary "ws://127.0.0.1:8765/v1/shell?program=bash&token=$TOKEN"``````swiftdiff --git a/Skills/vphone-guest-control/references/guest-layout.md b/Skills/vphone-guest-control/references/guest-layout.mdindex 59914ef6..11194597 100644--- a/Skills/vphone-guest-control/references/guest-layout.md+++ b/Skills/vphone-guest-control/references/guest-layout.md@@ -4,7 +4,9 @@ A fresh guest has vphoned and the system changes the project ships, andnothing else: no package manager, no sshd, no shell tools. Everything in thisfile is about adding that environment (the "bootstrap") and then finding yourway around it. Until it is installed, work only through `guest send` and-`guest rpc`.+`guest rpc` — including `script.eval`, which runs JavaScript with vphoned's+identity and needs nothing installed at all (see+[rpc-methods](rpc-methods.md)).## Contentsdiff --git a/Skills/vphone-guest-control/references/guest-socket.md b/Skills/vphone-guest-control/references/guest-socket.mdindex d5ff53d9..a490d42d 100644--- a/Skills/vphone-guest-control/references/guest-socket.md+++ b/Skills/vphone-guest-control/references/guest-socket.md@@ -34,9 +34,46 @@ not there yet.| `{"t":"rpc","method":"<vphoned method>","params":{…}}` | Calls any vphoned method; see [rpc-methods](rpc-methods.md) || `{"t":"push","local":"/abs/host/file","path":"/abs/guest/file","mode":"755"}` | Streams a Mac file into the guest, any size. A `path` ending in `/` keeps the file's name; `mode` defaults to the Mac file's permissions. `result` has `path`, `local`, `size` || `{"t":"pull","path":"/abs/guest/file","local":"/abs/host/file"}` | Streams a guest file to the Mac; `local` may be a folder. Written beside `local` and renamed when complete |+| `{"t":"shell","program":"bash","cols":120,"rows":40}` | Hands the connection to a terminal in the guest (see below). `program` unset runs vphoned's own JavaScript session, which needs nothing installed |Unknown `t`, or missing fields, give `{"ok":false,"error":"…"}`.+## A terminal in the guest++`shell` is the one request with no single reply: the connection becomes the+terminal. Every byte sent after the command line is input, everything the+session writes comes back as it arrives, and one JSON line at the end says how+it finished — `{"ok":true,"exit":0}`, `{"ok":true,"signal":2}`, or+`{"ok":false,"error":"…"}` when no session could be opened.++When the client's input ends, the terminal gets a `^D`, the way a keyboard+ends input, and the session keeps running, so what it prints on the way out+and that last line still arrive. A pipe is therefore a script:++```zsh+{ print '{"t":"shell"}'; print '6 * 7' } | nc -U "$machine/vphone.sock"+```++For a terminal you type into, put your own in raw mode so every key goes to+the guest as typed; `^C` is then simply byte 3, which the guest's terminal+driver turns into a signal. When the session ends, press one more key to get+the prompt back, because `cat` is still waiting for one:++```zsh+stty raw -echo; { print '{"t":"shell"}'; cat } | nc -U "$machine/vphone.sock"; stty sane+```++The guest side is vphoned's `/v1/shell`, so `program` resolves the same way+there: unset for the JavaScript session, a bare name from the bootstrap's+`bin`, `usr/bin` and `usr/local/bin`, or an absolute path. A client that goes+away altogether, rather than only ending its input, hangs the terminal up and+the session goes with it.++The VM window's **Diagnostics ▸ Session** (⌥⌘T) opens the same route in a+terminal view, and `script.eval` through `rpc` runs one script without a+terminal at all. See "Scripting sessions" in+`Research/vphoned_http_api.md`.+## Replies and the attached screenSuccess is `{"ok":true}`, with `result` for `rpc`, `path` for `screenshot`, anddiff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.mdindex 5c43702d..2152dc1a 100644--- a/Skills/vphone-guest-control/references/rpc-methods.md+++ b/Skills/vphone-guest-control/references/rpc-methods.md@@ -27,6 +27,7 @@ invalid-request error, read the source named there instead of guessing keys.- Processes, logs, services- System and preferences- Bootstrap+- Running a script in the guest- Raw HTTP and WebSocket## Conventions@@ -203,6 +204,33 @@ are the usual way to hit the reply size problem.`bootstrap.inspect`, `bootstrap.uninstall {roots, force, reboot?}`,`bootstrap.firmware`. Behavior and the install flow: [guest-layout](guest-layout.md).+## Running a script in the guest++`script.eval {source, timeout?}` evaluates JavaScript with vphoned's own+identity and answers `{ok, result, output, crashed}`. It is the way to reach+something no method covers, and on an Apple TV guest it is the only+debugging environment there is: no shell, no package manager, no debugserver.+`script.info` reports whether this guest has it (capability `script_js`;+watchOS does not ship JavaScriptCore).++The script runs in a session process of its own, so a crash or a runaway loop+costs the session and nothing else; `timeout` defaults to 30 seconds. Inside+it, `api('method', {...})` calls any method in this file, `ObjC.use('NSFoo')`+and `ObjC.classes.NSFoo` call ObjC methods by name — an underscore stands for+a colon, `setValue_forKey_(v, k)` — and `fs`, `proc`, `console` and `print`+cover files, one program, and output. A returned collection stays an object;+`$value` converts it to plain JSON.++```sh+guest rpc script.eval '{"source":"ObjC.use(\"NSProcessInfo\").processInfo().operatingSystemVersionString()"}'+```++Prefer a real method when one exists: it is checked, documented and stable.+Reach for a script when nothing covers what is needed, then say so, because a+missing method is usually worth adding. The interactive form is the+`/v1/shell` WebSocket, which needs `--api-listen` — see+`Research/vphoned_http_api.md` ("Scripting sessions").+## Raw HTTP and WebSocketThe same methods are served as HTTP/WebSocket on guest VSOCK 1339. A hostdiff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlementsindex 031cbfa9..e547db57 100644--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements@@ -570,6 +570,8 @@<array><string>/</string></array>+ <key>dynamic-codesigning</key>+ <true/><key>file-read-data</key><true/><key>file-read-metadata</key>diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swiftindex 71252ff8..342dff37 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift@@ -26,6 +26,7 @@ extension GuestAPI {executeAttitude,executeHomePodDisplay,executeHomePodDebug,+ executeScript,]for area in areas {if let result = try area(method, params) {diff --git a/VPhoneDaemon/Daemon/GuestAPI+Script.swift b/VPhoneDaemon/Daemon/GuestAPI+Script.swiftnew file mode 100644index 00000000..98329135--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestAPI+Script.swift@@ -0,0 +1,100 @@+import Darwin+import Foundation+import VphonedNative++// MARK: - Scripting++/// A guest has no shell and the tvos preset has no debugger, so a script run+/// with vphoned's own identity is the only way to reach what the guest keeps+/// to itself. `script.eval` is the one-shot form and `/v1/shell` the+/// interactive one; both run in a session process rather than in the worker,+/// so a script that crashes or never returns ends only its own session.+///+/// `script.eval` takes `{source, timeout?}` and answers+/// `{ok, result | error, output, crashed}`: a script that throws is an answer,+/// not a failed request, and its output comes back either way.+extension GuestAPI {+ static func executeScript(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {+ switch method {+ case "script.eval":+ let source = try string(params, "source")+ return try evaluateScript(source: source, timeout: scriptTimeout(params))+ case "script.info":+ return scriptInfo()+ default:+ return nil+ }+ }++ static func scriptCapabilities() -> [String] {+ // The interactive route runs a program from the bootstrap as well, so+ // it is offered even where the built-in session cannot run.+ vp_js_available() ? ["shell", "script_js"] : ["shell"]+ }++ /// Long enough for a script that waits on a system service, short enough+ /// that a stuck one does not hold a client's request open indefinitely.+ private static func scriptTimeout(_ params: [String: Any]) -> Double {+ let value = number(params, "timeout", default: 30)+ guard value.isFinite, value > 0 else { return 30 }+ return min(max(value, 1), 600)+ }++ private static func evaluateScript(source: String, timeout: Double) throws -> [String: Any] {+ guard vp_js_available() else {+ throw GuestAPIError.operationFailed("This guest has no JavaScriptCore, so it cannot run a script")+ }+ guard GuestSessionLimit.evaluations.acquire() else {+ throw GuestAPIError.operationFailed(GuestSessionLimit.evaluations.refusal)+ }+ defer { GuestSessionLimit.evaluations.release() }+ var status: Int32 = -1+ guard let reply = source.withCString({ vp_session_evaluate($0, timeout, &status) }) else {+ if errno == ETIMEDOUT {+ throw GuestAPIError.operationFailed(+ "The script did not finish within \(Int(timeout)) seconds and was stopped",+ )+ }+ throw GuestAPIError.operationFailed("Could not start a session: \(String(cString: strerror(errno)))")+ }+ defer { free(reply) }++ let data = Data(String(cString: reply).utf8)+ guard let answer = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ answer["ok"] != nil+ else {+ // The session died before it could answer: how it ended is all+ // there is to report, and it is what a crash looks like here.+ return ["ok": false, "crashed": true, "output": "", "error": describe(sessionStatus: status)]+ }+ var result = answer+ result["crashed"] = false+ return result+ }++ private static func describe(sessionStatus status: Int32) -> String {+ guard status >= 0 else { return "The session ended before it answered" }+ let signalled = status & 0x7F+ if signalled != 0 {+ return "The script ended its session on signal \(signalled)"+ }+ return "The session exited with status \((status >> 8) & 0xFF) before it answered"+ }++ private static func scriptInfo() -> [String: Any] {+ // What `/v1/shell?program=` resolves to, so a client can offer only+ // what this guest actually has.+ var programs: [String: Any] = [:]+ for name in ["bash", "sh", "zsh"] {+ if let path = try? GuestShellSessionHandler.resolveProgram(name) {+ programs[name] = path+ }+ }+ return [+ "available": vp_js_available(),+ "engine": "JavaScriptCore",+ "globals": ["ObjC", "api", "fs", "proc", "console", "print", "sleep", "exit"],+ "programs": programs,+ ]+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex bf7d85ee..1f3d84a8 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -151,7 +151,8 @@ enum GuestAPI {"motion_gyroscope","motion_gyroscope_toggle","motion_attitude",- ] + pointerCapabilities() + GuestHomePodDisplay.capabilities + GuestHomePodDebug.capabilities,+ ] + pointerCapabilities() + scriptCapabilities() + GuestHomePodDisplay.capabilities+ + GuestHomePodDebug.capabilities,]}diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 6706ad66..4acaf304 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -121,7 +121,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandleSelf.send(APIWire.error("Port must be a decimal number from 1 to 65535"), on: channel)return}- if path == "/v1/events" || path.hasPrefix("/v1/ports/") {+ if path == "/v1/events" || path == "/v1/shell" || path.hasPrefix("/v1/ports/") {Self.send(APIWire.error("WebSocket upgrade required", status: 426), on: channel)return}diff --git a/VPhoneDaemon/Daemon/GuestShellSessionHandler.swift b/VPhoneDaemon/Daemon/GuestShellSessionHandler.swiftnew file mode 100644index 00000000..45ff74e5--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestShellSessionHandler.swift@@ -0,0 +1,420 @@+import Darwin+import Foundation+import NIOCore+import NIOWebSocket+import VphonedNative++/// How many sessions a guest runs at once. Each one is a process, and an+/// interactive one is also a thread waiting on its terminal, so a client that+/// opened them without limit would spend the guest's memory and fill the+/// concurrent queue the rest of the API shares — a script may hold its place+/// in that queue for as long as its timeout allows. Refusing the next one+/// says so plainly, where answering everything slowly would not.+final class GuestSessionLimit: @unchecked Sendable {+ static let interactive = GuestSessionLimit(limit: 8, what: "interactive sessions")+ static let evaluations = GuestSessionLimit(limit: 16, what: "scripts")++ private let lock = NSLock()+ private let limit: Int+ private let what: String+ private var count = 0++ init(limit: Int, what: String) {+ self.limit = limit+ self.what = what+ }++ var refusal: String {+ "This guest is already running \(limit) \(what); end one and try again"+ }++ func acquire() -> Bool {+ lock.lock()+ defer { lock.unlock() }+ guard count < limit else { return false }+ count += 1+ return true+ }++ func release() {+ lock.lock()+ if count > 0 { count -= 1 }+ lock.unlock()+ }+}++/// One scripting session, over a WebSocket. A binary frame is a chunk of the+/// terminal's byte stream in either direction, and a text frame carries a+/// control message. The session itself runs in a process of its own, so a+/// script that crashes or never returns ends only its own session.+///+/// `GET /v1/shell?program=repl&cols=100&rows=40`+/// - `program` is `repl` (the default, vphoned's JavaScript session), the+/// name of a program in the bootstrap, or an absolute path.+/// - client to server: `{"resize": [columns, rows]}`, `{"signal": "INT"}`.+/// - server to client: `{"exit": status}` or `{"signal": number}` last.+final class GuestShellSessionHandler: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = WebSocketFrame+ typealias OutboundOut = WebSocketFrame++ struct Request {+ var program: String+ var columns: Int32+ var rows: Int32+ }++ /// Whether the reader thread saw a failed write and should stop. A class+ /// so the event loop can report it without the reader sharing a variable.+ private final class Delivery: @unchecked Sendable {+ var active = true+ }++ private let request: Request+ private let terminalWrites = DispatchQueue(label: "vphoned.session.terminal", qos: .userInitiated)+ /// Guards the terminal and the session's pid for as long as either is+ /// used: a descriptor and a pid are both reused once released, and a+ /// write or a signal that arrived late must not reach whatever took them.+ private let lock = NSLock()+ private var master: Int32 = -1+ private var session: pid_t = -1+ private var ended = false+ private var closing = false++ init(request: Request) {+ self.request = request+ }++ // MARK: - Requests++ static func request(from uri: String) -> Request? {+ let path = uri.split(separator: "?", maxSplits: 1).first.map(String.init) ?? uri+ guard path == "/v1/shell" else { return nil }+ let components = URLComponents(string: "http://vphoned\(uri)")+ var request = Request(program: "repl", columns: 80, rows: 24)+ for item in components?.queryItems ?? [] {+ guard let value = item.value, !value.isEmpty else { continue }+ switch item.name {+ case "program": request.program = value+ case "cols", "columns": request.columns = size(value) ?? request.columns+ case "rows": request.rows = size(value) ?? request.rows+ default: break+ }+ }+ return request+ }++ /// A terminal dimension. The driver's own field is 16 bits, and a client+ /// is free to send anything at all.+ private static func size(_ value: String) -> Int32? {+ guard let number = Int(value), number > 0 else { return nil }+ return clamped(number)+ }++ private static func clamped(_ size: Int) -> Int32 {+ Int32(min(max(size, 0), 9999))+ }++ /// The program a session runs: nothing for vphoned's own session, or the+ /// path of a program to run on the terminal instead. A bare name comes+ /// from the bootstrap, which a fresh guest does not have.+ static func resolveProgram(_ name: String) throws -> String? {+ if name.isEmpty || name == "repl" || name == "js" { return nil }+ if name.hasPrefix("/") {+ guard access(name, X_OK) == 0 else {+ throw GuestAPIError.invalidRequest("\(name) is not an executable file in this guest")+ }+ return name+ }+ guard !name.contains("/") else {+ throw GuestAPIError.invalidRequest("program must be a name or an absolute path")+ }+ guard let root = GuestAPI.jailbreakInfo()["jbroot"] as? String else {+ throw GuestAPIError.invalidRequest(+ "This guest has no bootstrap, so there is no \(name) to run. "+ + "Leave program unset for vphoned's own session.",+ )+ }+ let prefix = root == "/" ? "" : root+ for candidate in ["\(prefix)/bin/\(name)", "\(prefix)/usr/bin/\(name)", "\(prefix)/usr/local/bin/\(name)"]+ where access(candidate, X_OK) == 0+ {+ return candidate+ }+ throw GuestAPIError.invalidRequest("The bootstrap at \(root) has no \(name)")+ }++ // MARK: - Opening++ func handlerAdded(context: ChannelHandlerContext) {+ let channel = context.channel+ guard GuestSessionLimit.interactive.acquire() else {+ refuse(GuestSessionLimit.interactive.refusal, on: channel)+ return+ }+ // From here the session's place is held, and every way out but a+ // started session gives it back. A started one is given back by+ // finish(), which runs once for each.+ let program: String?+ do {+ program = try Self.resolveProgram(request.program)+ } catch {+ GuestSessionLimit.interactive.release()+ refuse(String(describing: error), on: channel)+ return+ }+ if program == nil, !vp_js_available() {+ GuestSessionLimit.interactive.release()+ refuse("This guest has no JavaScriptCore, so there is no session to open.", on: channel)+ return+ }++ var started: pid_t = -1+ let descriptor: Int32 = if let program {+ program.withCString { vp_session_open($0, request.columns, request.rows, &started) }+ } else {+ vp_session_open(nil, request.columns, request.rows, &started)+ }+ guard descriptor >= 0 else {+ GuestSessionLimit.interactive.release()+ refuse("Could not open a session: \(String(cString: strerror(errno)))", on: channel)+ return+ }+ lock.lock()+ master = descriptor+ session = started+ lock.unlock()++ let reader = Thread { [self] in pump(on: channel, terminal: descriptor) }+ reader.name = "vphoned.session.reader"+ reader.stackSize = 512 * 1024+ reader.start()+ }++ // MARK: - The Terminal++ /// Reads the terminal until the session closes it. Each frame is awaited+ /// before the next read, so a client that cannot keep up slows the+ /// session down instead of filling the worker's memory with its output.+ /// This thread owns the descriptor: nothing else closes it.+ private func pump(on channel: Channel, terminal: Int32) {+ var bytes = [UInt8](repeating: 0, count: 8192)+ while true {+ let count = bytes.withUnsafeMutableBytes { Darwin.read(terminal, $0.baseAddress, $0.count) }+ if count > 0 {+ guard forward(Array(bytes[0 ..< count]), to: channel) else { break }+ continue+ }+ // A pseudo-terminal reports EIO once the last program holding the+ // other end has gone, where a pipe would report end of file.+ if count < 0, errno == EINTR { continue }+ break+ }+ finish(on: channel)+ }++ private func forward(_ bytes: [UInt8], to channel: Channel) -> Bool {+ let delivered = DispatchSemaphore(value: 0)+ let delivery = Delivery()+ channel.eventLoop.execute {+ guard channel.isActive else {+ delivery.active = false+ delivered.signal()+ return+ }+ var payload = channel.allocator.buffer(capacity: bytes.count)+ payload.writeBytes(bytes)+ channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .binary, data: payload))+ .whenComplete { result in+ if case .failure = result { delivery.active = false }+ delivered.signal()+ }+ }+ // The wait is what applies the backpressure; the timeout only keeps a+ // wedged event loop from holding this thread for good.+ _ = delivered.wait(timeout: .now() + 30)+ return delivery.active+ }++ private func sendToTerminal(_ buffer: ByteBuffer) {+ var buffer = buffer+ guard let bytes = buffer.readBytes(length: buffer.readableBytes), !bytes.isEmpty else { return }+ terminalWrites.async { [self] in+ lock.lock()+ defer { lock.unlock() }+ guard !ended, master >= 0 else { return }+ var offset = 0+ while offset < bytes.count {+ let sent = bytes.withUnsafeBytes {+ Darwin.write(master, $0.baseAddress?.advanced(by: offset), bytes.count - offset)+ }+ if sent > 0 {+ offset += sent+ continue+ }+ if sent < 0, errno == EINTR { continue }+ break+ }+ }+ }++ // MARK: - Control Messages++ private func handle(control text: String) {+ guard let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { return }+ if let size = object["resize"] as? [Any], size.count == 2,+ let columns = (size[0] as? NSNumber)?.intValue, let rows = (size[1] as? NSNumber)?.intValue+ {+ lock.lock()+ if !ended, master >= 0 {+ vp_session_resize(master, Self.clamped(columns), Self.clamped(rows))+ }+ lock.unlock()+ }+ if let name = object["signal"] as? String, let number = Self.signals[name.uppercased()] {+ lock.lock()+ // The group, so a program the session started receives it too.+ if !ended, session > 0 { kill(-session, number) }+ lock.unlock()+ }+ }++ private static let signals: [String: Int32] = [+ "HUP": SIGHUP, "SIGHUP": SIGHUP,+ "INT": SIGINT, "SIGINT": SIGINT,+ "QUIT": SIGQUIT, "SIGQUIT": SIGQUIT,+ "TERM": SIGTERM, "SIGTERM": SIGTERM,+ "KILL": SIGKILL, "SIGKILL": SIGKILL,+ ]++ // MARK: - Channel++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ let frame = unwrapInboundIn(data)+ guard !closing else { return }+ switch frame.opcode {+ case .binary:+ sendToTerminal(frame.unmaskedData)+ case .text:+ var payload = frame.unmaskedData+ if let text = payload.readString(length: payload.readableBytes) {+ handle(control: text)+ }+ case .ping:+ context.writeAndFlush(+ wrapOutboundOut(WebSocketFrame(fin: true, opcode: .pong, data: frame.unmaskedData)),+ promise: nil,+ )+ case .connectionClose:+ closing = true+ let channel = context.channel+ context.writeAndFlush(+ wrapOutboundOut(WebSocketFrame(fin: true, opcode: .connectionClose, data: frame.unmaskedData)),+ ).whenComplete { _ in channel.closeAfterPeer() }+ default:+ close(1003, on: context.channel)+ }+ }++ func channelInactive(context: ChannelHandlerContext) {+ closing = true+ // The terminal is not closed here: the reader thread may be inside+ // read() on it. Hanging the session up makes it close its own end,+ // which ends that read, and the reader then reaps and closes.+ requestEnd()+ context.fireChannelInactive()+ }++ func errorCaught(context: ChannelHandlerContext, error _: Error) {+ context.close(promise: nil)+ }++ // MARK: - Ending++ private func requestEnd() {+ lock.lock()+ let ending = ended ? -1 : session+ // Signalled while the session is still this handler's, as the control+ // path does it: a pid released between the check and the signal+ // belongs to whatever the guest starts next.+ if ending > 0 {+ kill(ending, SIGHUP)+ kill(-ending, SIGHUP)+ }+ lock.unlock()+ guard ending > 0 else { return }+ DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [weak self] in+ guard let self else { return }+ lock.lock()+ defer { lock.unlock() }+ // Only while this session still owns the pid: once it is reaped+ // the number belongs to whatever the guest starts next.+ guard !ended, session == ending else { return }+ kill(ending, SIGKILL)+ kill(-ending, SIGKILL)+ }+ }++ /// Reap the session and tell the client how it ended. Runs once, on the+ /// reader thread, after the terminal has stopped producing bytes.+ private func finish(on channel: Channel) {+ lock.lock()+ if ended {+ lock.unlock()+ return+ }+ // Taking them out under the lock is what makes closing them safe: a+ // writer holding the lock finishes first, and every writer after this+ // sees `ended` and leaves the descriptor alone. Reaping itself waits+ // for the session, so it must not be done holding a lock the event+ // loop takes to resize the terminal.+ ended = true+ let terminal = master+ let ending = session+ master = -1+ session = -1+ lock.unlock()++ let status = vp_session_close(terminal, ending, 2)+ // Once the process is gone, so the count is of sessions a guest is+ // actually running rather than of handlers that have not tidied up.+ GuestSessionLimit.interactive.release()++ var ended: [String: Any] = ["exit": NSNull()]+ if status >= 0 {+ let signalled = status & 0x7F+ ended = signalled != 0 ? ["signal": signalled] : ["exit": (status >> 8) & 0xFF]+ }+ let data = (try? JSONSerialization.data(withJSONObject: ended, options: [.sortedKeys])) ?? Data()+ send(text: data, on: channel, thenClose: 1000)+ }++ /// A session that could not be opened: the reason reaches the client as a+ /// text frame, because a WebSocket that has been accepted has no status+ /// code left to carry it.+ private func refuse(_ message: String, on channel: Channel) {+ let data = (try? JSONSerialization.data(withJSONObject: ["error": message])) ?? Data()+ send(text: data, on: channel, thenClose: 1011)+ }++ private func send(text data: Data, on channel: Channel, thenClose code: UInt16) {+ let write: @Sendable () -> Void = { [self] in+ guard channel.isActive else { return }+ var payload = channel.allocator.buffer(capacity: data.count)+ payload.writeBytes(data)+ channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .text, data: payload)).whenComplete { _ in+ self.close(code, on: channel)+ }+ }+ if channel.eventLoop.inEventLoop { write() } else { channel.eventLoop.execute(write) }+ }++ private func close(_ code: UInt16, on channel: Channel) {+ guard channel.isActive else { return }+ closing = true+ var data = channel.allocator.buffer(capacity: 2)+ data.writeInteger(code, endianness: .big)+ channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .connectionClose, data: data)).whenComplete { _ in+ channel.closeAfterPeer()+ }+ }+}diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex 6ea3ac97..a4db30de 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -5,7 +5,28 @@ import NIOPosiximport NIOWebSocketimport VphonedNative+/// A session's `api(...)`, answered in the session's own process. The reply+/// is malloc-owned and the session frees it.+func answerSessionAPIRequest(_ request: UnsafePointer<CChar>) -> UnsafeMutablePointer<CChar>? {+ let reply: APIReply+ do {+ reply = APIWire.execute(try APIWire.decode(Data(String(cString: request).utf8)))+ } catch {+ reply = APIWire.error(String(describing: error))+ }+ return strdup(String(decoding: reply.data, as: UTF8.self))+}+let mode = vp_native_process_mode()+if mode == 2 {+ // A scripting session, spawned by the worker for one script or one+ // interactive session. None of the startup below belongs here: a session+ // owns no port and no device, several run at once, and whatever a script+ // does to this process stops at it. Methods that need state the worker+ // set up at startup are the ones a session cannot reach.+ vp_js_set_api_handler(answerSessionAPIRequest)+ exit(vp_native_run_session())+}if mode != 1 {guard mode == 0 else { exit(64) }vp_native_bootstrap_cached_binary()@@ -49,7 +70,8 @@ do {// that carries Origin or a non-loopback Host. The refused// request then reaches GuestHyperTextHandler, which replies 403.let allowed = GuestHyperTextHandler.isLocalClient(request.headers) &&- (request.uri == "/v1/events" || GuestPortForwardHandler.port(from: request.uri) != nil)+ (request.uri == "/v1/events" || GuestPortForwardHandler.port(from: request.uri) != nil ||+ GuestShellSessionHandler.request(from: request.uri) != nil)guard allowed else { return channel.eventLoop.makeSucceededFuture(nil) }// A client that gave the host proxy its token as a WebSocket// subprotocol expects the server to select that protocol.@@ -78,6 +100,15 @@ do {),GuestPortForwardHandler(port: port),])+ } else if let session = GuestShellSessionHandler.request(from: request.uri) {+ try sync.addHandlers([+ NIOWebSocketFrameAggregator(+ minNonFinalFragmentSize: 1,+ maxAccumulatedFrameCount: 32,+ maxAccumulatedFrameSize: 1 << 20,+ ),+ GuestShellSessionHandler(request: session),+ ])} else {try sync.addHandlers([NIOWebSocketFrameAggregator(diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex c1c9a632..ddda7312 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -2,6 +2,7 @@#include <stdbool.h>#include <stddef.h>#include <stdint.h>+#include <sys/types.h>#ifdef __OBJC__#import <Foundation/Foundation.h>#endif@@ -14,10 +15,44 @@char * _Null_unspecified vp_sign_app_for_install(const char * _Null_unspecified appPath, const char * _Null_unspecified certificatePath);void vp_native_bootstrap_cached_binary(void);void vp_native_confirm_cached_binary(void);-/// 0 = launchd proxy, 1 = --io worker, -1 = invalid arguments.+/// 0 = launchd proxy, 1 = --io worker, 2 = --session, -1 = invalid arguments.int vp_native_process_mode(void);int vp_native_run_proxy(void);int vp_native_watch_proxy(void);++// MARK: - Scripting Sessions++/// Run the `--session` process this one was started as, and return its exit+/// status. A session evaluates JavaScript with vphoned's own identity, in its+/// own process so neither a crashing script nor a wedged one can take the API+/// down with it. The worker never calls this; it spawns a session instead.+int vp_native_run_session(void);++/// Whether this guest has JavaScriptCore, which watchOS does not ship.+bool vp_js_available(void);++/// Let a session's scripts call the guest API. `request` is a JSON+/// `{method, params}`; the handler returns a malloc-owned JSON reply, which+/// the session frees. Set before vp_native_run_session.+void vp_js_set_api_handler(char * _Nullable (* _Nullable handler)(const char * _Nonnull request));++/// Start a session process on a pseudo-terminal, as a session leader with the+/// terminal as its controlling one, so job control and ^C work. `program` is+/// NULL for the built-in REPL or an absolute path to run instead. Returns the+/// master descriptor and sets `*pid`, or -1 with errno set.+int vp_session_open(const char * _Nullable program, int columns, int rows, pid_t * _Nonnull pid);++/// Tell a session's terminal its new size and signal the foreground group.+void vp_session_resize(int master, int columns, int rows);++/// Close a session: hang the terminal up, SIGKILL what is left after `grace`+/// seconds, and reap it. Returns the wait status, or -1.+int vp_session_close(int master, pid_t pid, double grace);++/// Evaluate `source` in a one-shot session process, which ends with it.+/// Returns the malloc-owned JSON object the session printed, or NULL with+/// `*status` holding the wait status; `timeout` seconds kills it first.+char * _Nullable vp_session_evaluate(const char * _Nonnull source, double timeout, int * _Nonnull status);void vp_vcam_start(void);/// Publish the HomePod MiniDisplay HID device when firmware has its geometry./// The device and its callback queue live for the worker process lifetime.diff --git a/VPhoneDaemon/Native/vphoned_jsbridge.h b/VPhoneDaemon/Native/vphoned_jsbridge.hnew file mode 100644index 00000000..a36cf143--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_jsbridge.h@@ -0,0 +1,22 @@+#pragma once+#import <Foundation/Foundation.h>+#import <JavaScriptCore/JavaScriptCore.h>++/// What a script holds for an ObjC object the bridge cannot convert. The+/// prelude wraps each one in a proxy, so a script calls methods by name+/// instead of calling `send` itself.+@protocol VPObjCHandleExports <JSExport>+@property (nonatomic, readonly) BOOL objcHandle;+@property (nonatomic, readonly) NSString *className;+@property (nonatomic, readonly) BOOL isClassHandle;+- (NSString *)toString;+/// The object as a plain JavaScript value: a collection becomes an array or+/// an object, and anything else its description.+- (JSValue *)plainValue;+JSExportAs(send, - (JSValue *)sendSelectorNamed:(NSString *)name arguments:(JSValue *)arguments);+@end++@interface VPObjCHandle : NSObject <VPObjCHandleExports>+@property (nonatomic, readonly, strong) id target;++ (instancetype)handleFor:(id)target;+@enddiff --git a/VPhoneDaemon/Native/vphoned_jsbridge.m b/VPhoneDaemon/Native/vphoned_jsbridge.mnew file mode 100644index 00000000..8cb35286--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_jsbridge.m@@ -0,0 +1,340 @@+#import "vphoned_jsbridge.h"++#import <objc/runtime.h>++// Reflection is the point of the session: without it a script can only do+// arithmetic, and the frameworks a guest keeps to itself are exactly what+// there is no other way to reach. NSInvocation covers every method the+// runtime can describe, which is every method but a variadic one.++static bool vp_bridge_is_value(id object);++/// Whether the method returns an object ARC has not accounted for, by the+/// same rule the compiler uses: a selector whose first word is alloc, new,+/// copy, mutableCopy or init belongs to that family. The word has to end+/// there, so `copyWithZone:` is in the family and `copyingProgress` is not —+/// taking ownership of a borrowed object would over-release it.+static bool vp_bridge_in_family(NSString *name, NSString *family) {+ if (![name hasPrefix:family]) return false;+ if (name.length == family.length) return true;+ unichar next = [name characterAtIndex:family.length];+ return next < 'a' || next > 'z';+}++static bool vp_bridge_returns_retained(SEL selector) {+ NSString *name = NSStringFromSelector(selector);+ for (NSString *family in @[@"alloc", @"new", @"copy", @"mutableCopy", @"init"]) {+ if (vp_bridge_in_family(name, family)) return true;+ }+ return false;+}++/// An allocated object is not yet an object: NSString's allocation is a+/// placeholder that raises on anything but an initializer, and asking JSC to+/// convert it as a string would be one such message. It is handed back as a+/// handle, whatever it claims to be a kind of.+static bool vp_bridge_returns_placeholder(SEL selector) {+ return vp_bridge_in_family(NSStringFromSelector(selector), @"alloc");+}++/// A method encoding carries qualifiers the type itself does not: `const char *`+/// arrives as `r*`, and in, out and inout parameters are prefixed as well.+/// None of them change how the value is passed.+static const char *vp_bridge_unqualified(const char *type) {+ while (*type && strchr("rnNoORV", *type)) type++;+ return type;+}++@implementation VPObjCHandle+++ (instancetype)handleFor:(id)target {+ if (!target) return nil;+ VPObjCHandle *handle = [VPObjCHandle new];+ handle->_target = target;+ return handle;+}++- (BOOL)objcHandle {+ return YES;+}++- (NSString *)className {+ Class owner = object_isClass(_target) ? _target : [_target class];+ return NSStringFromClass(owner);+}++- (BOOL)isClassHandle {+ return object_isClass(_target);+}++- (JSValue *)plainValue {+ JSContext *context = [JSContext currentContext];+ if (vp_bridge_is_value(_target) || [_target isKindOfClass:[NSArray class]] ||+ [_target isKindOfClass:[NSDictionary class]]) {+ return [JSValue valueWithObject:_target inContext:context];+ }+ return [JSValue valueWithObject:[self toString] inContext:context];+}++- (NSString *)toString {+ NSString *description = nil;+ @try {+ description = [_target description];+ } @catch (NSException *exception) {+ description = [NSString stringWithFormat:@"<%@: description threw %@>", self.className, exception.name];+ }+ return description ?: [NSString stringWithFormat:@"<%@>", self.className];+}++// MARK: - Dispatch++/// Whether JSC's own conversion carries everything the object is: a string, a+/// number and a date are values, and so is a collection of them.+static bool vp_bridge_is_value(id object) {+ return [object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] ||+ [object isKindOfClass:[NSDate class]] || [object isKindOfClass:[NSNull class]];+}++/// A script sees a string or a number where ObjC returned one, and a handle+/// for everything else, collections included: converting an NSArray would+/// hand back a copy, and a script that asked for a mutable one wants the+/// object. `$value` converts when that is what was wanted.+static JSValue *vp_bridge_result(id object, JSContext *context) {+ if (!object) return [JSValue valueWithNullInContext:context];+ if (vp_bridge_is_value(object)) return [JSValue valueWithObject:object inContext:context];+ return [JSValue valueWithObject:[VPObjCHandle handleFor:object] inContext:context];+}++static void vp_bridge_throw(JSContext *context, NSString *format, ...) {+ va_list arguments;+ va_start(arguments, format);+ NSString *message = [[NSString alloc] initWithFormat:format arguments:arguments];+ va_end(arguments);+ context.exception = [JSValue valueWithNewErrorFromMessage:message inContext:context];+}++/// The target object behind a JS value: a handle for anything the bridge+/// returned, and JSC's own conversion for a string, number, array or object.+static id vp_bridge_argument_object(JSValue *value) {+ if (value.isUndefined || value.isNull) return nil;+ id object = [value toObject];+ if ([object isKindOfClass:[VPObjCHandle class]]) return ((VPObjCHandle *)object).target;+ return object;+}++/// A method the runtime describes but +methodSignatureForSelector: did not,+/// which happens on a class whose metaclass resolves methods lazily.+static NSMethodSignature *vp_bridge_signature(id target, SEL selector) {+ NSMethodSignature *signature = [target methodSignatureForSelector:selector];+ if (signature) return signature;+ Method method = object_isClass(target) ? class_getClassMethod(target, selector)+ : class_getInstanceMethod([target class], selector);+ const char *types = method ? method_getTypeEncoding(method) : NULL;+ return types ? [NSMethodSignature signatureWithObjCTypes:types] : nil;+}++/// One argument slot, large enough for every scalar an invocation takes.+union VPArgumentSlot {+ bool asBool;+ char asChar;+ unsigned char asUnsignedChar;+ short asShort;+ unsigned short asUnsignedShort;+ int asInt;+ unsigned int asUnsignedInt;+ long asLong;+ unsigned long asUnsignedLong;+ long long asLongLong;+ unsigned long long asUnsignedLongLong;+ float asFloat;+ double asDouble;+ void *asPointer;+ const char *asCString;+ Class asClass;+ SEL asSelector;+ __unsafe_unretained id asObject;+};++/// Fill `slot` from `value` for one argument. `holds` keeps anything the+/// invocation borrows a pointer into alive until it returns. False once the+/// context's exception is set.+static bool vp_bridge_fill(union VPArgumentSlot *slot, const char *type, JSValue *value,+ NSMutableArray *holds, JSContext *context) {+ type = vp_bridge_unqualified(type);+ switch (type[0]) {+ case '@': {+ id object = vp_bridge_argument_object(value);+ if (object) [holds addObject:object];+ slot->asObject = object;+ return true;+ }+ case '#': {+ id object = vp_bridge_argument_object(value);+ if (object && !object_isClass(object)) {+ vp_bridge_throw(context, @"Expected a class argument, got %@", [object class]);+ return false;+ }+ slot->asClass = object;+ return true;+ }+ case ':': {+ NSString *name = [value toString];+ slot->asSelector = name.length ? NSSelectorFromString(name) : NULL;+ return true;+ }+ case '*': {+ if (value.isNull || value.isUndefined) {+ slot->asCString = NULL;+ return true;+ }+ NSString *text = [value toString];+ if (!text) {+ vp_bridge_throw(context, @"Expected a string argument");+ return false;+ }+ [holds addObject:text];+ slot->asCString = text.UTF8String;+ return true;+ }+ case 'B': slot->asBool = [value toBool]; return true;+ case 'c': slot->asChar = (char)[value toInt32]; return true;+ case 'C': slot->asUnsignedChar = (unsigned char)[value toUInt32]; return true;+ case 's': slot->asShort = (short)[value toInt32]; return true;+ case 'S': slot->asUnsignedShort = (unsigned short)[value toUInt32]; return true;+ case 'i': slot->asInt = [value toInt32]; return true;+ case 'I': slot->asUnsignedInt = [value toUInt32]; return true;+ case 'l': slot->asLong = (long)[value toDouble]; return true;+ case 'L': slot->asUnsignedLong = (unsigned long)[value toDouble]; return true;+ case 'q': slot->asLongLong = (long long)[value toDouble]; return true;+ case 'Q': slot->asUnsignedLongLong = (unsigned long long)[value toDouble]; return true;+ case 'f': slot->asFloat = (float)[value toDouble]; return true;+ case 'd': slot->asDouble = [value toDouble]; return true;+ case '^':+ // A script has no way to make a valid pointer, and letting it invent+ // one would only turn a typo into a crash.+ if (value.isNull || value.isUndefined) {+ slot->asPointer = NULL;+ return true;+ }+ vp_bridge_throw(context, @"Only null may be passed for the pointer argument '%s'", type);+ return false;+ default:+ vp_bridge_throw(context, @"Arguments of type '%s' are not supported", type);+ return false;+ }+}++/// Read the return value an invocation left behind.+static JSValue *vp_bridge_return(NSInvocation *invocation, const char *type, SEL selector, JSContext *context) {+ type = vp_bridge_unqualified(type);+ switch (type[0]) {+ case 'v': return [JSValue valueWithUndefinedInContext:context];+ case '@': {+ void *raw = NULL;+ [invocation getReturnValue:&raw];+ id object = vp_bridge_returns_retained(selector) ? (__bridge_transfer id)raw : (__bridge id)raw;+ if (object && vp_bridge_returns_placeholder(selector)) {+ return [JSValue valueWithObject:[VPObjCHandle handleFor:object] inContext:context];+ }+ return vp_bridge_result(object, context);+ }+ case '#': {+ Class result = Nil;+ [invocation getReturnValue:&result];+ return vp_bridge_result(result, context);+ }+ case ':': {+ SEL result = NULL;+ [invocation getReturnValue:&result];+ return result ? [JSValue valueWithObject:NSStringFromSelector(result) inContext:context]+ : [JSValue valueWithNullInContext:context];+ }+ case '*': {+ const char *result = NULL;+ [invocation getReturnValue:&result];+ return result ? [JSValue valueWithObject:@(result) inContext:context]+ : [JSValue valueWithNullInContext:context];+ }+#define VP_BRIDGE_SCALAR_RETURN(encoding, kind) \+ case encoding: { \+ kind result = 0; \+ [invocation getReturnValue:&result]; \+ return [JSValue valueWithDouble:(double)result inContext:context]; \+ }+ VP_BRIDGE_SCALAR_RETURN('c', char)+ VP_BRIDGE_SCALAR_RETURN('C', unsigned char)+ VP_BRIDGE_SCALAR_RETURN('s', short)+ VP_BRIDGE_SCALAR_RETURN('S', unsigned short)+ VP_BRIDGE_SCALAR_RETURN('i', int)+ VP_BRIDGE_SCALAR_RETURN('I', unsigned int)+ VP_BRIDGE_SCALAR_RETURN('l', long)+ VP_BRIDGE_SCALAR_RETURN('L', unsigned long)+ VP_BRIDGE_SCALAR_RETURN('q', long long)+ VP_BRIDGE_SCALAR_RETURN('Q', unsigned long long)+ VP_BRIDGE_SCALAR_RETURN('f', float)+ VP_BRIDGE_SCALAR_RETURN('d', double)+#undef VP_BRIDGE_SCALAR_RETURN+ case 'B': {+ bool result = false;+ [invocation getReturnValue:&result];+ return [JSValue valueWithBool:result inContext:context];+ }+ case '^': {+ void *result = NULL;+ [invocation getReturnValue:&result];+ // The address is worth reading; nothing can be done with it here.+ return result ? [JSValue valueWithDouble:(double)(uintptr_t)result inContext:context]+ : [JSValue valueWithNullInContext:context];+ }+ default:+ vp_bridge_throw(context, @"Return values of type '%s' are not supported", type);+ return [JSValue valueWithUndefinedInContext:context];+ }+}++- (JSValue *)sendSelectorNamed:(NSString *)name arguments:(JSValue *)arguments {+ JSContext *context = [JSContext currentContext];+ JSValue *undefined = [JSValue valueWithUndefinedInContext:context];+ SEL selector = name.length ? NSSelectorFromString(name) : NULL;+ if (!selector) {+ vp_bridge_throw(context, @"A selector is required");+ return undefined;+ }+ NSMethodSignature *signature = vp_bridge_signature(_target, selector);+ if (!signature) {+ vp_bridge_throw(context, @"%@ does not respond to %@", self.className, name);+ return undefined;+ }++ NSUInteger expected = signature.numberOfArguments - 2;+ NSUInteger given = [arguments[@"length"] toUInt32];+ if (given != expected) {+ vp_bridge_throw(context, @"%@ takes %lu argument%s, got %lu", name,+ (unsigned long)expected, expected == 1 ? "" : "s", (unsigned long)given);+ return undefined;+ }++ NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];+ invocation.selector = selector;+ invocation.target = _target;+ NSMutableArray *holds = [NSMutableArray array];+ union VPArgumentSlot slots[expected > 0 ? expected : 1];+ for (NSUInteger index = 0; index < expected; index++) {+ const char *type = [signature getArgumentTypeAtIndex:index + 2];+ if (!vp_bridge_fill(&slots[index], type, [arguments valueAtIndex:(NSUInteger)index], holds, context)) {+ return undefined;+ }+ [invocation setArgument:&slots[index] atIndex:(NSInteger)(index + 2)];+ }++ @try {+ [invocation invoke];+ } @catch (NSException *exception) {+ vp_bridge_throw(context, @"%@ raised %@: %@", name, exception.name, exception.reason ?: @"");+ return undefined;+ }+ if (signature.methodReturnLength == 0) return undefined;+ return vp_bridge_return(invocation, signature.methodReturnType, selector, context);+}++@enddiff --git a/VPhoneDaemon/Native/vphoned_jscontext.m b/VPhoneDaemon/Native/vphoned_jscontext.mnew file mode 100644index 00000000..a97d0bce--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_jscontext.m@@ -0,0 +1,381 @@+#import "vphoned_jsbridge.h"+#import "vphoned_session.h"++#include <sys/stat.h>+#include <unistd.h>++// The session's JavaScript context. JavaScriptCore is the one scripting+// runtime already on an iOS and a tvOS guest, so a session needs nothing+// installed; watchOS has no public copy, which is why vphoned links it+// weakly and every entry point here checks availability first.++static JSContext *vp_context;+static JSValue *vp_thrown;+static NSMutableString *vp_output;+static bool vp_capturing;+static char *(*vp_api_handler)(const char *);++/// What one script may collect before its output stops growing. A runaway+/// loop must not take the session's memory with it.+static const NSUInteger vp_output_limit = 1 << 20;++bool vp_js_available(void) {+ return NSClassFromString(@"JSContext") != nil;+}++void vp_js_set_api_handler(char *(*handler)(const char *request)) {+ vp_api_handler = handler;+}++// MARK: - Output++static void vp_js_write(int descriptor, NSString *text) {+ if (!text.length) return;+ if (vp_capturing) {+ if (vp_output.length < vp_output_limit) [vp_output appendString:text];+ return;+ }+ FILE *stream = descriptor == 2 ? stderr : stdout;+ fputs(text.UTF8String ?: "", stream);+ fflush(stream);+}++void vp_js_capture_output(bool enabled) {+ vp_capturing = enabled;+ if (enabled && !vp_output) vp_output = [NSMutableString string];+}++char *vp_js_take_output(void) {+ NSString *text = vp_output ?: @"";+ char *copy = strdup(text.UTF8String ?: "");+ [vp_output setString:@""];+ return copy;+}++// MARK: - Globals++static void vp_js_throw(NSString *format, ...) {+ va_list arguments;+ va_start(arguments, format);+ NSString *message = [[NSString alloc] initWithFormat:format arguments:arguments];+ va_end(arguments);+ JSContext *context = [JSContext currentContext] ?: vp_context;+ context.exception = [JSValue valueWithNewErrorFromMessage:message inContext:context];+}++static NSString *vp_js_posix_error(NSString *call, NSString *path) {+ return [NSString stringWithFormat:@"%@(%@): %s", call, path, strerror(errno)];+}++static void vp_js_install_files(JSContext *context) {+ context[@"__fs_list"] = ^id(NSString *path) {+ NSError *failure = nil;+ NSArray *names = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path ?: @"" error:&failure];+ if (!names) {+ vp_js_throw(@"%@", failure.localizedDescription ?: @"Could not list the directory");+ return nil;+ }+ return [names sortedArrayUsingSelector:@selector(compare:)];+ };++ context[@"__fs_read"] = ^id(NSString *path) {+ NSError *failure = nil;+ NSData *data = [NSData dataWithContentsOfFile:path ?: @"" options:0 error:&failure];+ if (!data) {+ vp_js_throw(@"%@", failure.localizedDescription ?: @"Could not read the file");+ return nil;+ }+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];+ if (!text) {+ vp_js_throw(@"%@ is not UTF-8 text; read it with the files API instead", path);+ return nil;+ }+ return text;+ };++ context[@"__fs_write"] = ^id(NSString *path, NSString *text) {+ NSData *data = [text ?: @"" dataUsingEncoding:NSUTF8StringEncoding];+ NSError *failure = nil;+ if (![data writeToFile:path ?: @"" options:NSDataWritingAtomic error:&failure]) {+ vp_js_throw(@"%@", failure.localizedDescription ?: @"Could not write the file");+ return nil;+ }+ return @(data.length);+ };++ context[@"__fs_stat"] = ^id(NSString *path) {+ struct stat info;+ if (lstat(path.fileSystemRepresentation ?: "", &info) != 0) {+ vp_js_throw(@"%@", vp_js_posix_error(@"lstat", path));+ return nil;+ }+ NSString *kind = @"other";+ switch (info.st_mode & S_IFMT) {+ case S_IFREG: kind = @"file"; break;+ case S_IFDIR: kind = @"directory"; break;+ case S_IFLNK: kind = @"symlink"; break;+ default: break;+ }+ return @{+ @"type": kind,+ @"size": @(info.st_size),+ @"mode": [NSString stringWithFormat:@"%o", info.st_mode & 07777],+ @"uid": @(info.st_uid),+ @"gid": @(info.st_gid),+ @"mtime": @(info.st_mtimespec.tv_sec),+ };+ };+}++static void vp_js_install_process(JSContext *context) {+ context[@"__proc_run"] = ^id(NSString *path, id arguments, id input) {+ NSArray *list = [arguments isKindOfClass:[NSArray class]] ? arguments : @[];+ // The argument vector is built on the stack, so a script must not be+ // the one deciding how large it is.+ if (list.count > 1024) {+ vp_js_throw(@"proc.run takes at most 1024 arguments, got %lu", (unsigned long)list.count);+ return nil;+ }+ NSMutableArray<NSString *> *words = [NSMutableArray arrayWithObject:path ?: @""];+ for (id argument in list) [words addObject:[argument description]];+ const char *argv[words.count + 1];+ for (NSUInteger index = 0; index < words.count; index++) {+ argv[index] = words[index].UTF8String;+ }+ argv[words.count] = NULL;++ NSString *text = [input isKindOfClass:[NSString class]] ? input : nil;+ int status = 0;+ char *output = NULL;+ char *errors = NULL;+ int failure = vp_spawn_collect(path.fileSystemRepresentation ?: "", argv,+ text ? text.UTF8String : NULL, &status, &output, &errors);+ if (failure != 0) {+ vp_js_throw(@"%@: %s", path, strerror(failure));+ free(output);+ free(errors);+ return nil;+ }+ NSDictionary *result = @{+ @"status": @(WIFEXITED(status) ? WEXITSTATUS(status) : -1),+ @"signal": WIFSIGNALED(status) ? @(WTERMSIG(status)) : [NSNull null],+ @"stdout": @(output ?: ""),+ @"stderr": @(errors ?: ""),+ };+ free(output);+ free(errors);+ return result;+ };++ context[@"__sleep"] = ^(double milliseconds) {+ if (milliseconds > 0 && milliseconds < 600000) usleep((useconds_t)(milliseconds * 1000));+ };++ context[@"__exit"] = ^(double code) {+ exit((int)code);+ };+}++static void vp_js_install_api(JSContext *context) {+ context[@"__api"] = ^id(NSString *method, id parameters) {+ if (!vp_api_handler) {+ vp_js_throw(@"This session has no API handler");+ return nil;+ }+ NSDictionary *params = [parameters isKindOfClass:[NSDictionary class]] ? parameters : @{};+ NSDictionary *request = @{@"method": method ?: @"", @"params": params};+ NSData *encoded = [NSJSONSerialization dataWithJSONObject:request options:0 error:nil];+ if (!encoded) {+ vp_js_throw(@"The parameters of %@ are not JSON", method);+ return nil;+ }+ NSMutableData *terminated = [encoded mutableCopy];+ [terminated appendBytes:"" length:1];+ char *reply = vp_api_handler(terminated.bytes);+ if (!reply) {+ vp_js_throw(@"%@ returned nothing", method);+ return nil;+ }+ NSData *data = [NSData dataWithBytesNoCopy:reply length:strlen(reply) freeWhenDone:YES];+ NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ if (![object isKindOfClass:[NSDictionary class]]) {+ vp_js_throw(@"%@ returned a malformed reply", method);+ return nil;+ }+ NSDictionary *failure = object[@"error"];+ if ([failure isKindOfClass:[NSDictionary class]]) {+ vp_js_throw(@"%@: %@", failure[@"code"] ?: @"error", failure[@"message"] ?: @"failed");+ return nil;+ }+ return object[@"result"] ?: [NSNull null];+ };+}++/// The ergonomic layer, written in the language it serves: a proxy per ObjC+/// object so a script calls methods by name, and `console`, `fs`, `proc` and+/// `api` over the primitives installed above. A method name's underscores+/// become colons (`setValue_forKey_`), or a bare name takes one colon per+/// argument; a name that already has colons is used as it stands.+static NSString *const vp_js_prelude =+ @"(function (global) {\n"+ @" 'use strict';\n"+ @" function describe(value) {\n"+ @" if (typeof value === 'string') return value;\n"+ @" if (value === null) return 'null';\n"+ @" if (value === undefined) return 'undefined';\n"+ @" if (typeof value === 'function') return String(value);\n"+ @" if (typeof value === 'object') {\n"+ @" if (value.objcHandle === true || value.$handle !== undefined) return String(value);\n"+ @" try { return JSON.stringify(value); } catch (error) { return String(value); }\n"+ @" }\n"+ @" return String(value);\n"+ @" }\n"+ @" function selectorFor(name, count) {\n"+ @" if (name.indexOf(':') >= 0) return name;\n"+ @" if (name.indexOf('_') >= 0) return name.replace(/_/g, ':');\n"+ @" return count > 0 ? name + ':'.repeat(count) : name;\n"+ @" }\n"+ @" function unwrap(value) {\n"+ @" if (value !== null && typeof value === 'object' && value.$handle !== undefined) return value.$handle;\n"+ @" return value;\n"+ @" }\n"+ @" function box(value) {\n"+ @" if (value !== null && typeof value === 'object' && value.objcHandle === true) return wrap(value);\n"+ @" return value;\n"+ @" }\n"+ @" function wrap(handle) {\n"+ @" return new Proxy({}, {\n"+ @" get: function (_, property) {\n"+ @" if (typeof property === 'symbol') {\n"+ @" if (property === Symbol.toPrimitive) return function () { return handle.toString(); };\n"+ @" if (property === Symbol.toStringTag) return handle.className;\n"+ @" return undefined;\n"+ @" }\n"+ @" if (property === '$handle') return handle;\n"+ @" if (property === '$class') return handle.className;\n"+ @" if (property === '$isClass') return handle.isClassHandle;\n"+ @" if (property === '$value') return handle.plainValue();\n"+ @" if (property === 'toString' || property === 'inspect') {\n"+ @" return function () { return handle.toString(); };\n"+ @" }\n"+ @" return function () {\n"+ @" var args = Array.prototype.slice.call(arguments).map(unwrap);\n"+ @" return box(handle.send(selectorFor(property, args.length), args));\n"+ @" };\n"+ @" },\n"+ @" });\n"+ @" }\n"+ @" var ObjC = {\n"+ @" use: function (name) {\n"+ @" var handle = global.__objc_class(name);\n"+ @" if (!handle) throw new Error('No ObjC class named ' + name);\n"+ @" return wrap(handle);\n"+ @" },\n"+ @" wrap: box,\n"+ @" classes: new Proxy({}, {\n"+ @" get: function (_, name) { return typeof name === 'string' ? ObjC.use(name) : undefined; },\n"+ @" }),\n"+ @" };\n"+ @" function writeLine(descriptor, values) {\n"+ @" global.__write(descriptor, values.map(describe).join(' ') + '\\n');\n"+ @" }\n"+ @" function toList(values) { return Array.prototype.slice.call(values); }\n"+ @" global.console = {\n"+ @" log: function () { writeLine(1, toList(arguments)); },\n"+ @" info: function () { writeLine(1, toList(arguments)); },\n"+ @" warn: function () { writeLine(2, toList(arguments)); },\n"+ @" error: function () { writeLine(2, toList(arguments)); },\n"+ @" };\n"+ @" global.print = global.console.log;\n"+ @" global.fs = {\n"+ @" ls: function (path) { return global.__fs_list(path); },\n"+ @" read: function (path) { return global.__fs_read(path); },\n"+ @" write: function (path, text) { return global.__fs_write(path, text); },\n"+ @" stat: function (path) { return global.__fs_stat(path); },\n"+ @" };\n"+ @" global.proc = {\n"+ @" run: function (path, args, input) {\n"+ @" return global.__proc_run(path, args || [], input === undefined ? null : input);\n"+ @" },\n"+ @" };\n"+ @" global.api = function (method, params) { return global.__api(method, params || {}); };\n"+ @" global.sleep = function (milliseconds) { global.__sleep(milliseconds); };\n"+ @" global.exit = function (code) { global.__exit(code === undefined ? 0 : code); };\n"+ @" global.ObjC = ObjC;\n"+ @" global.__describe = describe;\n"+ @"})(this);\n";++bool vp_js_start(void) {+ if (vp_context) return true;+ if (!vp_js_available()) return false;+ JSContext *context = [[JSContext alloc] init];+ if (!context) return false;+ context.name = @"vphoned";+ context.exceptionHandler = ^(JSContext *raising, JSValue *exception) {+ (void)raising;+ vp_thrown = exception;+ };++ context[@"__write"] = ^(double descriptor, NSString *text) {+ vp_js_write((int)descriptor, text ?: @"");+ };+ context[@"__objc_class"] = ^id(NSString *name) {+ Class owner = name.length ? NSClassFromString(name) : Nil;+ return owner ? [VPObjCHandle handleFor:owner] : nil;+ };+ vp_js_install_files(context);+ vp_js_install_process(context);+ vp_js_install_api(context);++ vp_thrown = nil;+ [context evaluateScript:vp_js_prelude withSourceURL:[NSURL URLWithString:@"vphoned://prelude.js"]];+ if (vp_thrown) {+ NSLog(@"vphoned session: the prelude failed: %@", [vp_thrown toString]);+ vp_thrown = nil;+ return false;+ }+ vp_context = context;+ return true;+}++// MARK: - Evaluation++static NSString *vp_js_describe(JSValue *value) {+ if (!value) return @"undefined";+ JSValue *describe = vp_context[@"__describe"];+ if (describe.isObject) {+ JSValue *text = [describe callWithArguments:@[value]];+ if (text.isString) return [text toString];+ }+ return [value toString] ?: @"undefined";+}++/// An uncaught error, with the stack JSC recorded when there is one: a script+/// in a guest cannot be stepped through, so the trace is all there is.+static NSString *vp_js_describe_exception(JSValue *exception) {+ NSString *message = [exception toString] ?: @"Unknown error";+ if (!exception.isObject) return message;+ JSValue *stack = exception[@"stack"];+ if (!stack.isString) return message;+ NSString *trace = [[stack toString] stringByTrimmingCharactersInSet:+ [NSCharacterSet whitespaceAndNewlineCharacterSet]];+ return trace.length ? [NSString stringWithFormat:@"%@\n%@", message, trace] : message;+}++char *vp_js_evaluate(const char *source, char **error) {+ if (error) *error = NULL;+ if (!vp_context && !vp_js_start()) {+ if (error) *error = strdup("This guest has no JavaScriptCore");+ return NULL;+ }+ vp_thrown = nil;+ JSValue *value = [vp_context evaluateScript:@(source ?: "")+ withSourceURL:[NSURL URLWithString:@"vphoned://session.js"]];+ if (vp_thrown) {+ JSValue *exception = vp_thrown;+ vp_thrown = nil;+ if (error) *error = strdup(vp_js_describe_exception(exception).UTF8String ?: "Unknown error");+ return NULL;+ }+ return strdup(vp_js_describe(value).UTF8String ?: "undefined");+}diff --git a/VPhoneDaemon/Native/vphoned_proxy.c b/VPhoneDaemon/Native/vphoned_proxy.cindex e3b49492..ba95161d 100644--- a/VPhoneDaemon/Native/vphoned_proxy.c+++ b/VPhoneDaemon/Native/vphoned_proxy.c@@ -1,4 +1,4 @@-#include "Include/VphonedNative.h"+#include "vphoned_session.h"#include <crt_externs.h>#include <errno.h>@@ -36,6 +36,7 @@ static int worker_fd(void) {int vp_native_process_mode(void) {int argc = *_NSGetArgc();if (argc == 1) return 0;+ if (vp_session_arguments_present()) return 2;return worker_fd() >= 0 ? 1 : -1;}diff --git a/VPhoneDaemon/Native/vphoned_pty.c b/VPhoneDaemon/Native/vphoned_pty.cnew file mode 100644index 00000000..8eb3d529--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_pty.c@@ -0,0 +1,434 @@+#include "vphoned_session.h"++#include <errno.h>+#include <fcntl.h>+#include <mach-o/dyld.h>+#include <poll.h>+#include <pthread.h>+#include <signal.h>+#include <spawn.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/ioctl.h>+#include <sys/wait.h>+#include <time.h>+#include <unistd.h>+#include <util.h>++extern char **environ;++// The worker's side of a session: it spawns its own executable again so the+// script runs with vphoned's signature and entitlements, and keeps it in+// another process so a script that crashes or wedges takes only itself down.++/// What one session may hand back. Past this a script is misusing the API+/// rather than reporting something, and the worker must not grow with it.+#define VP_COLLECT_LIMIT (8u << 20)++static void vp_ignore_broken_pipe(void) {+ // Writing to a child that has already gone must report EPIPE rather than+ // end the process. The worker runs NIO, which ignores SIGPIPE itself, but+ // a session process has only this: `proc.run` on a program that exits+ // before reading its input would otherwise kill the session.+ signal(SIGPIPE, SIG_IGN);+}++static void vp_prepare_spawning(void) {+ static pthread_once_t once = PTHREAD_ONCE_INIT;+ pthread_once(&once, vp_ignore_broken_pipe);+}++/// Keep a descriptor out of children started elsewhere in the worker. The+/// spawns here pass POSIX_SPAWN_CLOEXEC_DEFAULT, but two others in the daemon+/// pass no file actions at all, and a child of theirs that inherited one end+/// of a session's pipe would hold it open: an eval would then wait out its+/// whole timeout for an end of file that cannot arrive, and an interactive+/// session's terminal would never report that the session had ended, leaving+/// its reader waiting for good. Setting the flag right after the descriptor+/// exists leaves a window of a few instructions, which is as narrow as it+/// gets without an atomic pipe2 to open them with. The file actions below+/// dup2 onto 0, 1 and 2, which clears the flag for the child meant to have+/// them.+static void vp_keep_from_children(int descriptor) {+ if (descriptor < 0) return;+ int flags = fcntl(descriptor, F_GETFD);+ if (flags >= 0) fcntl(descriptor, F_SETFD, flags | FD_CLOEXEC);+}++// MARK: - Buffers++struct vp_buffer {+ char *data;+ size_t length;+ size_t capacity;+};++static bool vp_buffer_append(struct vp_buffer *buffer, const char *bytes, size_t count) {+ if (buffer->length + count + 1 > buffer->capacity) {+ size_t capacity = buffer->capacity ? buffer->capacity * 2 : 8192;+ while (capacity < buffer->length + count + 1) capacity *= 2;+ char *grown = realloc(buffer->data, capacity);+ if (!grown) return false;+ buffer->data = grown;+ buffer->capacity = capacity;+ }+ memcpy(buffer->data + buffer->length, bytes, count);+ buffer->length += count;+ buffer->data[buffer->length] = '\0';+ return true;+}++/// The buffer's bytes as a C string, or an empty one, and the buffer is spent.+static char *vp_buffer_finish(struct vp_buffer *buffer) {+ if (buffer->data) {+ char *data = buffer->data;+ *buffer = (struct vp_buffer){0};+ return data;+ }+ return strdup("");+}++// MARK: - Clock++static double vp_now(void) {+ struct timespec now;+ clock_gettime(CLOCK_MONOTONIC, &now);+ return (double)now.tv_sec + (double)now.tv_nsec / 1e9;+}++// MARK: - Pumping a Child++/// Feed `input` in and collect both outputs until each closes. `timeout` is+/// seconds, or 0 to wait as long as the child takes. Returns 0, or ETIMEDOUT+/// with whatever arrived so far kept.+///+/// Every descriptor passed in is closed before this returns, on the timeout+/// and error paths as much as on the ordinary one. A caller cannot close them+/// itself without racing the child it is still waiting for, and an eval that+/// timed out would otherwise leave the worker one descriptor short each time+/// until it could no longer accept a connection.+static int vp_pump(int input_fd, const char *input, int output_fd, struct vp_buffer *output,+ int errors_fd, struct vp_buffer *errors, double timeout) {+ int result = 0;+ size_t written = 0;+ size_t remaining = input ? strlen(input) : 0;+ if (input_fd >= 0 && remaining == 0) {+ close(input_fd);+ input_fd = -1;+ }+ double deadline = timeout > 0 ? vp_now() + timeout : 0;++ while (input_fd >= 0 || output_fd >= 0 || errors_fd >= 0) {+ struct pollfd watched[3];+ int slots[3];+ int count = 0;+ if (input_fd >= 0) {+ watched[count] = (struct pollfd){.fd = input_fd, .events = POLLOUT};+ slots[count++] = 0;+ }+ if (output_fd >= 0) {+ watched[count] = (struct pollfd){.fd = output_fd, .events = POLLIN};+ slots[count++] = 1;+ }+ if (errors_fd >= 0) {+ watched[count] = (struct pollfd){.fd = errors_fd, .events = POLLIN};+ slots[count++] = 2;+ }++ int wait_ms = -1;+ if (deadline > 0) {+ double left = deadline - vp_now();+ if (left <= 0) {+ result = ETIMEDOUT;+ goto done;+ }+ wait_ms = (int)(left * 1000) + 1;+ }+ int ready = poll(watched, (nfds_t)count, wait_ms);+ if (ready < 0) {+ if (errno == EINTR) continue;+ result = errno;+ goto done;+ }+ if (ready == 0) {+ result = ETIMEDOUT;+ goto done;+ }++ for (int index = 0; index < count; index++) {+ short events = watched[index].revents;+ if (!events) continue;+ if (slots[index] == 0) {+ // Nothing is reading any more: there is no one left to send+ // the rest to, and writing would only raise EPIPE.+ bool done = (events & (POLLERR | POLLHUP)) != 0;+ if (!done) {+ ssize_t sent = write(input_fd, input + written, remaining - written);+ if (sent > 0) written += (size_t)sent;+ done = sent == 0 || (sent < 0 && errno != EINTR && errno != EAGAIN) ||+ written >= remaining;+ }+ if (done) {+ close(input_fd);+ input_fd = -1;+ }+ continue;+ }+ int *source = slots[index] == 1 ? &output_fd : &errors_fd;+ struct vp_buffer *sink = slots[index] == 1 ? output : errors;+ char bytes[16384];+ ssize_t read_count = read(*source, bytes, sizeof(bytes));+ if (read_count > 0) {+ if (sink->length < VP_COLLECT_LIMIT) {+ if (!vp_buffer_append(sink, bytes, (size_t)read_count)) {+ result = ENOMEM;+ goto done;+ }+ }+ continue;+ }+ if (read_count < 0 && (errno == EINTR || errno == EAGAIN)) continue;+ close(*source);+ *source = -1;+ }+ }+done:+ if (input_fd >= 0) close(input_fd);+ if (output_fd >= 0) close(output_fd);+ if (errors_fd >= 0) close(errors_fd);+ return result;+}++static void vp_reap(pid_t pid, int *status) {+ int collected = 0;+ while (waitpid(pid, &collected, 0) < 0 && errno == EINTR) {}+ if (status) *status = collected;+}++// MARK: - Running One Program++int vp_spawn_collect(const char *path, const char *const *argv, const char *input,+ int *status, char **output, char **errors) {+ vp_prepare_spawning();+ if (output) *output = NULL;+ if (errors) *errors = NULL;+ int in[2] = {-1, -1};+ int out[2] = {-1, -1};+ int err[2] = {-1, -1};+ if (pipe(in) != 0) return errno;+ if (pipe(out) != 0 || pipe(err) != 0) {+ int failure = errno;+ for (int index = 0; index < 2; index++) {+ if (in[index] >= 0) close(in[index]);+ if (out[index] >= 0) close(out[index]);+ if (err[index] >= 0) close(err[index]);+ }+ return failure;+ }+ for (int index = 0; index < 2; index++) {+ vp_keep_from_children(in[index]);+ vp_keep_from_children(out[index]);+ vp_keep_from_children(err[index]);+ }++ posix_spawn_file_actions_t actions;+ posix_spawn_file_actions_init(&actions);+ posix_spawn_file_actions_adddup2(&actions, in[0], STDIN_FILENO);+ posix_spawn_file_actions_adddup2(&actions, out[1], STDOUT_FILENO);+ posix_spawn_file_actions_adddup2(&actions, err[1], STDERR_FILENO);+ posix_spawnattr_t attributes;+ posix_spawnattr_init(&attributes);+ // Only the three descriptors above reach the child: vphoned holds the+ // VSOCK listener and every client connection.+ posix_spawnattr_setflags(&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT);++ pid_t child = -1;+ int failure = posix_spawn(&child, path, &actions, &attributes, (char *const *)argv, environ);+ posix_spawn_file_actions_destroy(&actions);+ posix_spawnattr_destroy(&attributes);+ close(in[0]);+ close(out[1]);+ close(err[1]);+ if (failure != 0) {+ close(in[1]);+ close(out[0]);+ close(err[0]);+ return failure;+ }++ struct vp_buffer collected = {0};+ struct vp_buffer problems = {0};+ int pumped = vp_pump(in[1], input, out[0], &collected, err[0], &problems, 0);+ vp_reap(child, status);+ if (output) *output = vp_buffer_finish(&collected);+ else free(collected.data);+ if (errors) *errors = vp_buffer_finish(&problems);+ else free(problems.data);+ return pumped == ETIMEDOUT ? 0 : pumped;+}++// MARK: - Session Processes++/// vphoned's own path, which may be the verified copy in the cache rather+/// than the installed binary, so a session is always the same image.+static bool vp_own_executable(char *path, size_t size) {+ uint32_t length = (uint32_t)size;+ return _NSGetExecutablePath(path, &length) == 0;+}++int vp_session_open(const char *program, int columns, int rows, pid_t *pid) {+ vp_prepare_spawning();+ char executable[4096];+ if (!vp_own_executable(executable, sizeof(executable))) {+ errno = ENOENT;+ return -1;+ }+ struct winsize size = {+ .ws_col = (unsigned short)(columns > 0 && columns < 10000 ? columns : 80),+ .ws_row = (unsigned short)(rows > 0 && rows < 10000 ? rows : 24),+ };+ int master = -1;+ int slave = -1;+ if (openpty(&master, &slave, NULL, NULL, &size) != 0) return -1;+ vp_keep_from_children(master);+ vp_keep_from_children(slave);++ posix_spawn_file_actions_t actions;+ posix_spawn_file_actions_init(&actions);+ posix_spawn_file_actions_adddup2(&actions, slave, STDIN_FILENO);+ posix_spawn_file_actions_adddup2(&actions, slave, STDOUT_FILENO);+ posix_spawn_file_actions_adddup2(&actions, slave, STDERR_FILENO);+ posix_spawnattr_t attributes;+ posix_spawnattr_init(&attributes);+ posix_spawnattr_setflags(&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT);++ char *arguments[5];+ int count = 0;+ arguments[count++] = executable;+ arguments[count++] = "--session";+ if (program) {+ arguments[count++] = "exec";+ arguments[count++] = (char *)program;+ } else {+ arguments[count++] = "repl";+ }+ arguments[count] = NULL;++ pid_t child = -1;+ int failure = posix_spawn(&child, executable, &actions, &attributes, arguments, environ);+ posix_spawn_file_actions_destroy(&actions);+ posix_spawnattr_destroy(&attributes);+ close(slave);+ if (failure != 0) {+ close(master);+ errno = failure;+ return -1;+ }+ if (pid) *pid = child;+ return master;+}++void vp_session_resize(int master, int columns, int rows) {+ if (master < 0 || columns <= 0 || rows <= 0 || columns >= 10000 || rows >= 10000) return;+ struct winsize size = {.ws_col = (unsigned short)columns, .ws_row = (unsigned short)rows};+ // The terminal driver signals the foreground group itself, which is how+ // a program inside the session learns its window changed.+ ioctl(master, TIOCSWINSZ, &size);+}++/// A session leads its own process group, so the whole tree it started is+/// signalled with it. The pid is only a group while the session is alive and+/// unreaped; afterwards the number belongs to whatever the guest starts next,+/// which is why every caller signals before it reaps.+int vp_session_close(int master, pid_t pid, double grace) {+ if (master >= 0) {+ // Hanging the terminal up is what ends a well-behaved session: the+ // REPL reads EOF and the signal reaches anything it started.+ close(master);+ }+ if (pid <= 0) return -1;+ kill(pid, SIGHUP);+ kill(-pid, SIGHUP);++ double deadline = vp_now() + (grace > 0 ? grace : 2);+ for (;;) {+ int status = 0;+ pid_t waited = waitpid(pid, &status, WNOHANG);+ if (waited == pid) return status;+ if (waited < 0 && errno != EINTR) return -1;+ if (vp_now() >= deadline) break;+ struct timespec delay = {.tv_sec = 0, .tv_nsec = 20000000};+ nanosleep(&delay, NULL);+ }+ kill(pid, SIGKILL);+ kill(-pid, SIGKILL);+ int status = 0;+ vp_reap(pid, &status);+ return status;+}++char *vp_session_evaluate(const char *source, double timeout, int *status) {+ vp_prepare_spawning();+ if (status) *status = -1;+ char executable[4096];+ if (!vp_own_executable(executable, sizeof(executable))) {+ errno = ENOENT;+ return NULL;+ }+ int in[2] = {-1, -1};+ int out[2] = {-1, -1};+ if (pipe(in) != 0) return NULL;+ if (pipe(out) != 0) {+ int failure = errno;+ close(in[0]);+ close(in[1]);+ errno = failure;+ return NULL;+ }+ for (int index = 0; index < 2; index++) {+ vp_keep_from_children(in[index]);+ vp_keep_from_children(out[index]);+ }++ posix_spawn_file_actions_t actions;+ posix_spawn_file_actions_init(&actions);+ posix_spawn_file_actions_adddup2(&actions, in[0], STDIN_FILENO);+ posix_spawn_file_actions_adddup2(&actions, out[1], STDOUT_FILENO);+ // The session keeps vphoned's stderr: a crash report from a script belongs+ // in the guest log, and its stdout carries nothing but the reply.+ posix_spawn_file_actions_adddup2(&actions, STDERR_FILENO, STDERR_FILENO);+ posix_spawnattr_t attributes;+ posix_spawnattr_init(&attributes);+ posix_spawnattr_setflags(&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT);++ char *arguments[] = {executable, "--session", "eval", NULL};+ pid_t child = -1;+ int failure = posix_spawn(&child, executable, &actions, &attributes, arguments, environ);+ posix_spawn_file_actions_destroy(&actions);+ posix_spawnattr_destroy(&attributes);+ close(in[0]);+ close(out[1]);+ if (failure != 0) {+ close(in[1]);+ close(out[0]);+ errno = failure;+ return NULL;+ }++ struct vp_buffer collected = {0};+ int pumped = vp_pump(in[1], source, out[0], &collected, -1, NULL, timeout);+ if (pumped == ETIMEDOUT) {+ // The group, so a program the script started dies with it rather+ // than outliving the session as an orphan.+ kill(child, SIGKILL);+ kill(-child, SIGKILL);+ }+ vp_reap(child, status);+ if (pumped == ETIMEDOUT) {+ free(collected.data);+ errno = ETIMEDOUT;+ return NULL;+ }+ return vp_buffer_finish(&collected);+}diff --git a/VPhoneDaemon/Native/vphoned_session.h b/VPhoneDaemon/Native/vphoned_session.hnew file mode 100644index 00000000..cc41cf4c--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_session.h@@ -0,0 +1,43 @@+#pragma once+#include "Include/VphonedNative.h"++#include <stdbool.h>+#include <sys/types.h>++// The scripting session, which runs in its own process. vphoned has no shell+// and the tvos preset has no debugger, so a session is the only way to run+// code with vphoned's identity inside a guest. Everything here belongs to the+// `--session` process; the worker side is declared in VphonedNative.h.++/// Whether this process's arguments name a session, which decides the+/// process mode before anything else has run.+bool vp_session_arguments_present(void);++// MARK: - JavaScript Runtime++/// Build the session's context and install its globals. False when+/// JavaScriptCore is missing or the prelude failed to evaluate.+bool vp_js_start(void);++/// Collect what the script writes instead of letting it reach stdout, which+/// `eval` needs: its own stdout carries one JSON line and nothing else.+void vp_js_capture_output(bool enabled);++/// The collected output so far, malloc-owned, clearing the buffer.+char *vp_js_take_output(void);++/// Evaluate `source` and describe its value. Returns malloc-owned text, or+/// NULL with `*error` set to a malloc-owned message.+char *vp_js_evaluate(const char *source, char **error);++/// Whether `source` ends inside an open brace, bracket, string or comment,+/// which the REPL continues on the next line instead of evaluating.+bool vp_js_source_is_incomplete(const char *source);++// MARK: - Session Processes++/// Run one program and collect what it writes. `input` may be NULL. Both+/// outputs are malloc-owned and always set on success. Returns 0, or an errno+/// value; `*status` is the wait status.+int vp_spawn_collect(const char *path, const char *const *argv, const char *input,+ int *status, char **output, char **errors);diff --git a/VPhoneDaemon/Native/vphoned_session.m b/VPhoneDaemon/Native/vphoned_session.mnew file mode 100644index 00000000..27d5fa5e--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_session.m@@ -0,0 +1,391 @@+#import "vphoned_session.h"++#import <Foundation/Foundation.h>++#include <crt_externs.h>+#include <dlfcn.h>+#include <errno.h>+#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/ioctl.h>+#include <termios.h>+#include <unistd.h>++// The `--session` process: the worker spawned this to run one script or one+// interactive session, and nothing of the worker's own startup has run here.++static volatile sig_atomic_t vp_interrupted = 0;++static void vp_note_interrupt(int signal_number) {+ (void)signal_number;+ vp_interrupted = 1;+}++// MARK: - Arguments++/// `--session <kind> [program]`. Returns the kind, or NULL when the arguments+/// are not a session's.+static const char *vp_session_kind(int *argc, char ***argv) {+ int count = *_NSGetArgc();+ char **words = *_NSGetArgv();+ if (count < 3 || strcmp(words[1], "--session") != 0) return NULL;+ if (argc) *argc = count;+ if (argv) *argv = words;+ return words[2];+}++bool vp_session_arguments_present(void) {+ const char *kind = vp_session_kind(NULL, NULL);+ return kind && (strcmp(kind, "repl") == 0 || strcmp(kind, "eval") == 0 || strcmp(kind, "exec") == 0);+}++// MARK: - Controlling Terminal++/// Lead a process group of this session's own, and take the terminal as the+/// controlling one when there is a terminal.+///+/// The group comes first and applies to every kind of session: the worker+/// ends a session by signalling its group, and a program the script started+/// has to go with it rather than outlive it as an orphan. The terminal is+/// claimed by the child rather than by posix_spawn's file actions, so the+/// order never depends on the kernel's: ^C, job control and the hang-up that+/// ends an interactive session all need it in place before anything runs.+static void vp_session_detach(void) {+ setsid();+ if (!isatty(STDIN_FILENO)) return;+ ioctl(STDIN_FILENO, TIOCSCTTY, 0);+ tcsetpgrp(STDIN_FILENO, getpgrp());+}++// MARK: - Source Completeness++static bool vp_js_is_word(char character) {+ return character == '_' || character == '$' ||+ (character >= 'a' && character <= 'z') ||+ (character >= 'A' && character <= 'Z') ||+ (character >= '0' && character <= '9');+}++/// Whether a '/' here opens a regular expression rather than dividing. After+/// a value — a name, a number, a string, or a closing bracket — it divides;+/// after an operator, an opening bracket, or a keyword that takes an+/// expression, there is nothing for it to divide.+static bool vp_js_regex_starts(const char *source, const char *last) {+ if (!last) return true;+ char previous = *last;+ if (previous == ')' || previous == ']' || previous == '}' ||+ previous == '\'' || previous == '"' || previous == '`') {+ return false;+ }+ if (!vp_js_is_word(previous)) return true;+ const char *start = last;+ while (start > source && vp_js_is_word(start[-1])) start--;+ size_t length = (size_t)(last + 1 - start);+ static const char *const keywords[] = {+ "return", "typeof", "case", "in", "of", "new", "delete",+ "do", "else", "void", "instanceof", "yield", "await", "throw",+ };+ for (size_t index = 0; index < sizeof(keywords) / sizeof(*keywords); index++) {+ if (strlen(keywords[index]) == length && strncmp(start, keywords[index], length) == 0) {+ return true;+ }+ }+ return false;+}++/// The character after a regular expression's closing '/', or NULL when the+/// line ends first. A literal cannot span lines, so an unterminated one is a+/// syntax error for the engine to report rather than a statement the session+/// should wait for the rest of.+static const char *vp_js_after_regex(const char *slash) {+ bool in_class = false;+ for (const char *cursor = slash + 1; *cursor && *cursor != '\n'; cursor++) {+ if (*cursor == '\\') {+ if (!cursor[1] || cursor[1] == '\n') return NULL;+ cursor++;+ continue;+ }+ if (in_class) {+ if (*cursor == ']') in_class = false;+ continue;+ }+ if (*cursor == '[') in_class = true;+ else if (*cursor == '/') return cursor + 1;+ }+ return NULL;+}++bool vp_js_source_is_incomplete(const char *source) {+ if (!source) return false;+ int depth = 0;+ char quote = '\0';+ bool comment = false;+ // The last character that was not space. A '/' means one thing after a+ // value and another after an operator, and reading a regular expression+ // as a division is what makes `/['"]/` look like an unterminated string+ // and `/\{/` like an unclosed brace — either of which would leave the+ // session waiting for a line that is never coming.+ const char *last = NULL;+ for (const char *cursor = source; *cursor; cursor++) {+ char character = *cursor;+ if (comment) {+ if (character == '*' && cursor[1] == '/') {+ comment = false;+ cursor++;+ last = cursor;+ }+ continue;+ }+ if (quote) {+ if (character == '\\' && cursor[1]) {+ cursor++;+ } else if (character == quote) {+ quote = '\0';+ last = cursor;+ }+ continue;+ }+ switch (character) {+ case '\'': case '"': case '`': quote = character; break;+ case '/':+ if (cursor[1] == '*') {+ comment = true;+ cursor++;+ continue;+ }+ if (cursor[1] == '/') {+ while (cursor[1] && cursor[1] != '\n') cursor++;+ continue;+ }+ if (vp_js_regex_starts(source, last)) {+ const char *after = vp_js_after_regex(cursor);+ if (after) {+ cursor = after - 1;+ last = cursor;+ continue;+ }+ }+ break;+ case '(': case '[': case '{': depth++; break;+ case ')': case ']': case '}': if (depth > 0) depth--; break;+ default: break;+ }+ if (character != ' ' && character != '\t' && character != '\n' && character != '\r') {+ last = cursor;+ }+ }+ // A single-quoted or double-quoted string cannot span lines in JavaScript,+ // so only a template literal keeps the statement open.+ return depth > 0 || comment || quote == '`';+}++// MARK: - Reading Lines++static char *(*vp_readline)(const char *);+static void (*vp_add_history)(const char *);++/// libedit gives the session history and line editing. It is not a given on+/// every guest, and the terminal's own canonical mode still handles+/// backspace, ^U and ^C without it.+static void vp_load_line_editor(void) {+ void *library = dlopen("/usr/lib/libedit.3.dylib", RTLD_LAZY | RTLD_LOCAL);+ if (!library) library = dlopen("libedit.dylib", RTLD_LAZY | RTLD_LOCAL);+ if (!library) return;+ vp_readline = dlsym(library, "readline");+ vp_add_history = dlsym(library, "add_history");+ if (!vp_readline) vp_add_history = NULL;+}++/// One line without its newline, malloc-owned, or NULL at end of input.+/// `*interrupted` is set when ^C arrived instead of a line.+static char *vp_read_line(const char *prompt, bool *interrupted) {+ *interrupted = false;+ vp_interrupted = 0;+ if (vp_readline) {+ char *line = vp_readline(prompt);+ if (!line && vp_interrupted) {+ *interrupted = true;+ return NULL;+ }+ if (line && *line && vp_add_history) vp_add_history(line);+ return line;+ }++ fputs(prompt, stdout);+ fflush(stdout);+ char bytes[4096];+ if (!fgets(bytes, sizeof(bytes), stdin)) {+ if (vp_interrupted) {+ *interrupted = true;+ clearerr(stdin);+ }+ return NULL;+ }+ size_t length = strlen(bytes);+ while (length > 0 && (bytes[length - 1] == '\n' || bytes[length - 1] == '\r')) {+ bytes[--length] = '\0';+ }+ return strdup(bytes);+}++// MARK: - The REPL++static const char *vp_session_help =+ "vphoned session. Everything here runs as vphoned, in this process.\n"+ "\n"+ " ObjC.use('NSProcessInfo') a class; call its methods by name\n"+ " ObjC.classes.NSFileManager the same, by property\n"+ " obj.setValue_forKey_(v, k) an underscore stands for a colon\n"+ " obj['setValue:forKey:'](v, k) or write the selector out\n"+ " obj.$value obj.$class a collection as plain JSON; its class\n"+ " api('device.snapshot', {}) any guest API method, in process\n"+ " fs.ls / read / write / stat files, as root\n"+ " proc.run(path, [args]) one program, with its output\n"+ " console.log, print, sleep(ms) output and waiting\n"+ " .exit .help leave, or print this again\n"+ " ^C abandon a half-finished statement\n";++static int vp_session_repl(void) {+ vp_session_detach();+ struct sigaction interrupt = {.sa_handler = vp_note_interrupt};+ sigemptyset(&interrupt.sa_mask);+ sigaction(SIGINT, &interrupt, NULL);++ if (!vp_js_start()) {+ fputs("This guest has no JavaScriptCore, so there is no session to open.\n", stderr);+ return 70;+ }+ vp_load_line_editor();+ NSOperatingSystemVersion version = NSProcessInfo.processInfo.operatingSystemVersion;+ printf("vphoned session on %ld.%ld.%ld, pid %d. .help for what is here.\n",+ (long)version.majorVersion, (long)version.minorVersion, (long)version.patchVersion, getpid());+ fflush(stdout);++ NSMutableString *pending = [NSMutableString string];+ for (;;) {+ bool interrupted = false;+ char *line = vp_read_line(pending.length ? " ... " : "vphoned> ", &interrupted);+ if (interrupted) {+ [pending setString:@""];+ fputs("\n", stdout);+ continue;+ }+ if (!line) break;+ NSString *text = @(line);+ free(line);++ if (!pending.length) {+ NSString *command = [text stringByTrimmingCharactersInSet:+ [NSCharacterSet whitespaceAndNewlineCharacterSet]];+ if ([command isEqualToString:@".exit"] || [command isEqualToString:@".quit"]) break;+ if ([command isEqualToString:@".help"]) {+ fputs(vp_session_help, stdout);+ fflush(stdout);+ continue;+ }+ if (!command.length) continue;+ }+ [pending appendString:text ?: @""];+ [pending appendString:@"\n"];+ if (vp_js_source_is_incomplete(pending.UTF8String)) continue;++ char *failure = NULL;+ char *described = vp_js_evaluate(pending.UTF8String, &failure);+ [pending setString:@""];+ if (described) {+ if (strcmp(described, "undefined") != 0) printf("%s\n", described);+ free(described);+ } else {+ fprintf(stderr, "%s\n", failure ?: "Unknown error");+ free(failure);+ }+ fflush(stdout);+ fflush(stderr);+ }+ return 0;+}++// MARK: - One-Shot Evaluation++/// Everything on stdin, which the worker closes once it has sent the source.+static NSString *vp_read_all_input(void) {+ NSMutableData *collected = [NSMutableData data];+ char bytes[16384];+ for (;;) {+ ssize_t count = read(STDIN_FILENO, bytes, sizeof(bytes));+ if (count > 0) {+ if (collected.length < (4u << 20)) [collected appendBytes:bytes length:(NSUInteger)count];+ continue;+ }+ if (count < 0 && errno == EINTR) continue;+ break;+ }+ return [[NSString alloc] initWithData:collected encoding:NSUTF8StringEncoding] ?: @"";+}++static void vp_write_reply(NSDictionary *reply) {+ NSData *encoded = [NSJSONSerialization dataWithJSONObject:reply options:0 error:nil];+ if (!encoded) {+ encoded = [@"{\"ok\":false,\"error\":\"The reply could not be encoded\"}" dataUsingEncoding:NSUTF8StringEncoding];+ }+ fwrite(encoded.bytes, 1, encoded.length, stdout);+ fputc('\n', stdout);+ fflush(stdout);+}++static int vp_session_eval(void) {+ // No terminal here, but the group still matters: a timed-out session is+ // killed by its group so that nothing the script started is left behind.+ vp_session_detach();+ NSString *source = vp_read_all_input();+ vp_js_capture_output(true);+ if (!vp_js_start()) {+ vp_write_reply(@{@"ok": @NO, @"error": @"This guest has no JavaScriptCore", @"output": @""});+ return 70;+ }+ char *failure = NULL;+ char *described = vp_js_evaluate(source.UTF8String ?: "", &failure);+ char *output = vp_js_take_output();+ bool evaluated = described != NULL;+ NSMutableDictionary *reply = [NSMutableDictionary dictionary];+ reply[@"output"] = @(output ?: "");+ if (evaluated) {+ reply[@"ok"] = @YES;+ reply[@"result"] = @(described);+ } else {+ reply[@"ok"] = @NO;+ reply[@"error"] = @(failure ?: "Unknown error");+ }+ free(described);+ free(failure);+ free(output);+ vp_write_reply(reply);+ return evaluated ? 0 : 65;+}++// MARK: - Entry++static int vp_session_exec(int argc, char **argv) {+ if (argc < 4) {+ fputs("vphoned --session exec needs a program\n", stderr);+ return 64;+ }+ vp_session_detach();+ execv(argv[3], &argv[3]);+ fprintf(stderr, "vphoned session: %s: %s\n", argv[3], strerror(errno));+ return 127;+}++int vp_native_run_session(void) {+ int argc = 0;+ char **argv = NULL;+ const char *kind = vp_session_kind(&argc, &argv);+ if (!kind) return 64;+ if (strcmp(kind, "repl") == 0) return vp_session_repl();+ if (strcmp(kind, "eval") == 0) return vp_session_eval();+ if (strcmp(kind, "exec") == 0) return vp_session_exec(argc, argv);+ fprintf(stderr, "vphoned session: unknown kind %s\n", kind);+ return 64;+}diff --git a/VPhoneDaemon/Tests/SessionTests.m b/VPhoneDaemon/Tests/SessionTests.mnew file mode 100644index 00000000..4feff4db--- /dev/null+++ b/VPhoneDaemon/Tests/SessionTests.m@@ -0,0 +1,511 @@+#import "vphoned_session.h"++#import <Foundation/Foundation.h>++#include <errno.h>+#include <fcntl.h>+#include <poll.h>+#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/wait.h>+#include <unistd.h>++// Checks the scripting session on the Mac: the JavaScript runtime, the ObjC+// bridge, the session's own process modes, and the pseudo-terminal the worker+// opens for an interactive one. No guest is needed, and because this test+// binary answers `--session` the way vphoned does, the spawning paths are+// exercised for real rather than stubbed. `run-session-tests.sh` builds it.++static int checks;+static int failures;++static void expect(bool condition, const char *format, ...) {+ checks++;+ if (condition) return;+ failures++;+ va_list arguments;+ va_start(arguments, format);+ fputs("FAIL: ", stderr);+ vfprintf(stderr, format, arguments);+ fputc('\n', stderr);+ va_end(arguments);+}++// MARK: - Evaluation Helpers++/// The described value of `source`, or nil with the error reported.+static NSString *evaluate(const char *source) {+ char *failure = NULL;+ char *described = vp_js_evaluate(source, &failure);+ if (!described) {+ NSString *message = @(failure ?: "Unknown error");+ free(failure);+ expect(false, "%s threw %s", source, message.UTF8String);+ return nil;+ }+ NSString *text = @(described);+ free(described);+ return text;+}++static void expectValue(const char *source, NSString *expected) {+ NSString *actual = evaluate(source);+ if (!actual) return;+ expect([actual isEqualToString:expected], "%s: expected %s, got %s",+ source, expected.UTF8String, actual.UTF8String);+}++/// The error message `source` raised, or nil when it did not raise one.+static NSString *expectThrows(const char *source) {+ char *failure = NULL;+ char *described = vp_js_evaluate(source, &failure);+ checks++;+ if (described) {+ failures++;+ fprintf(stderr, "FAIL: %s should have thrown, returned %s\n", source, described);+ free(described);+ return nil;+ }+ NSString *message = @(failure ?: "");+ free(failure);+ return message;+}++static void expectThrowsContaining(const char *source, NSString *fragment) {+ NSString *message = expectThrows(source);+ if (!message) return;+ expect([message containsString:fragment], "%s: expected an error naming %s, got %s",+ source, fragment.UTF8String, message.UTF8String);+}++// MARK: - The Runtime++static void runtimeBasics(void) {+ expect(vp_js_available(), "JavaScriptCore is available on the Mac");+ expect(vp_js_start(), "the context starts");+ expect(vp_js_start(), "starting twice is harmless");++ expectValue("1 + 2", @"3");+ expectValue("'a' + 'b'", @"ab");+ expectValue("[1, 2, 3].map(function (n) { return n * 2; })", @"[2,4,6]");+ expectValue("JSON.stringify({a: 1})", @"{\"a\":1}");+ expectValue("({a: 1, b: [2]})", @"{\"a\":1,\"b\":[2]}");+ expectValue("null", @"null");+ expectValue("undefined", @"undefined");+ expectValue("var x = 5; x * x", @"25");+ expectValue("x + 1", @"6");++ expectThrowsContaining("throw new Error('boom')", @"boom");+ expectThrowsContaining("function (", @"SyntaxError");+ expectThrowsContaining("nothingHere()", @"nothingHere");+ // The trace is all a script in a guest has, so it must survive.+ NSString *trace = expectThrows("function inner() { throw new Error('deep'); }\ninner()");+ expect(!trace || [trace containsString:@"inner"], "the stack names the function that threw");+}++static void outputCapture(void) {+ vp_js_capture_output(true);+ expectValue("console.log('one', 2, {a: 3}); 'done'", @"done");+ char *output = vp_js_take_output();+ expect(strcmp(output, "one 2 {\"a\":3}\n") == 0, "console.log described each value: %s", output);+ free(output);++ expectValue("console.error('to stderr'); 1", @"1");+ output = vp_js_take_output();+ expect(strcmp(output, "to stderr\n") == 0, "stderr is collected too: %s", output);+ free(output);++ output = vp_js_take_output();+ expect(strcmp(output, "") == 0, "taking the output clears it");+ free(output);+ vp_js_capture_output(false);+}++// MARK: - The ObjC Bridge++static void bridgeBasics(void) {+ expectValue("typeof ObjC.use('NSProcessInfo')", @"object");+ expectValue("ObjC.use('NSProcessInfo').$isClass", @"true");+ expectThrowsContaining("ObjC.use('NoSuchClassHere')", @"No ObjC class");++ // A class method, then an instance method on what it returned.+ NSString *name = evaluate("ObjC.use('NSProcessInfo').processInfo().processName()");+ expect(name.length > 0, "processName returned a string: %s", name.UTF8String);+ expectValue("typeof ObjC.classes.NSProcessInfo.processInfo().processName()", @"string");++ // JSC's own types come back as themselves, not as handles.+ expectValue("ObjC.use('NSString').stringWithUTF8String_('hi')", @"hi");+ expectValue("typeof ObjC.use('NSString').stringWithUTF8String_('hi')", @"string");+ expectValue("ObjC.use('NSNumber').numberWithInt_(7) + 1", @"8");++ // An object the bridge has to keep as a handle.+ expectValue("var list = ObjC.use('NSMutableArray').array(); list.count()", @"0");+ expectValue("list.addObject_('first'); list.addObject_('second'); list.count()", @"2");+ expectValue("list.objectAtIndex_(1)", @"second");+ expectValue("list.componentsJoinedByString_('-')", @"first-second");+ // A collection stays an object, and converts only when asked to.+ expectValue("list.$value.join(',')", @"first,second");+ expectValue("Array.isArray(list.$value)", @"true");+ expectValue("typeof list.$handle", @"object");+ expectValue("list.$class", @"__NSArrayM");++ // A written-out selector, and an ObjC object as an argument.+ expectValue("var other = ObjC.use('NSMutableArray').array();"+ "other['addObjectsFromArray:'](list); other.count()",+ @"2");+ expectValue("var map = ObjC.use('NSMutableDictionary').dictionary();"+ "map.setValue_forKey_('v', 'k'); map.objectForKey_('k')",+ @"v");+ expectValue("JSON.stringify(map.$value)", @"{\"k\":\"v\"}");++ // Scalars in both directions.+ expectValue("ObjC.use('NSFileManager').defaultManager().fileExistsAtPath_('/')", @"true");+ expectValue("ObjC.use('NSFileManager').defaultManager().fileExistsAtPath_('/no/such/path')", @"false");+ expectValue("ObjC.use('NSString').stringWithUTF8String_('abc').length", @"3");++ // String conversion goes through the object's own description.+ expectValue("String(ObjC.use('NSMutableArray').array())", @"(\n)");++ // The alloc/init/copy families hand back an object the caller owns. Each+ // of these would over-release and take the process with it if the bridge+ // claimed ownership it had not been given, or leak if it missed one.+ expectValue("ObjC.use('NSMutableArray').alloc().init().count()", @"0");+ expectValue("ObjC.use('NSString').alloc()['initWithUTF8String:']('owned')", @"owned");+ expectValue("var copied = list.mutableCopy(); copied.addObject_('third'); copied.count()", @"3");+ expectValue("list.count()", @"2");+ expectValue("ObjC.use('NSMutableArray').array().copy().$class", @"__NSArray0");+ for (int round = 0; round < 200; round++) {+ char *described = vp_js_evaluate("ObjC.use('NSMutableDictionary').alloc().init().count()", NULL);+ free(described);+ }+ expect(true, "two hundred owned objects came and went without a crash");+}++static void bridgeRefusals(void) {+ expectThrowsContaining("ObjC.use('NSProcessInfo').processInfo().noSuchMethodAtAll()", @"does not respond to");+ expectThrowsContaining("ObjC.use('NSMutableArray').array().addObject_('a', 'b')", @"takes 1 argument");+ expectThrowsContaining("ObjC.use('NSMutableArray').array().addObject_()", @"takes 1 argument");+ // A struct return would need its layout read out of the encoding; the+ // refusal has to name the type so the limit is obvious from the message.+ expectThrowsContaining("ObjC.use('NSProcessInfo').processInfo().operatingSystemVersion()", @"not supported");+ // Raising rather than crashing is the whole point of the @try around invoke.+ expectThrowsContaining("ObjC.use('NSMutableArray').array().objectAtIndex_(4)", @"raised");+ expectThrowsContaining("ObjC.use('NSMutableArray').array().addObject_(null)", @"raised");+}++// MARK: - Files, Programs and the API++static void filesAndPrograms(void) {+ NSString *directory = [NSTemporaryDirectory() stringByAppendingPathComponent:@"vphone-session-tests"];+ [[NSFileManager defaultManager] createDirectoryAtPath:directory+ withIntermediateDirectories:YES attributes:nil error:nil];+ NSString *file = [directory stringByAppendingPathComponent:@"probe.txt"];+ vp_js_capture_output(true);++ NSString *source = [NSString stringWithFormat:@"fs.write('%@', 'written by a session')", file];+ expectValue(source.UTF8String, @"20");+ source = [NSString stringWithFormat:@"fs.read('%@')", file];+ expectValue(source.UTF8String, @"written by a session");+ source = [NSString stringWithFormat:@"fs.stat('%@').type", file];+ expectValue(source.UTF8String, @"file");+ source = [NSString stringWithFormat:@"fs.stat('%@').size", file];+ expectValue(source.UTF8String, @"20");+ source = [NSString stringWithFormat:@"fs.ls('%@').join(',')", directory];+ expectValue(source.UTF8String, @"probe.txt");+ (void)expectThrows("fs.read('/no/such/file/at/all')");+ (void)expectThrows("fs.ls('/no/such/directory')");++ expectValue("proc.run('/bin/echo', ['hello']).stdout", @"hello\n");+ expectValue("proc.run('/bin/echo', ['hello']).status", @"0");+ expectValue("proc.run('/bin/sh', ['-c', 'exit 3']).status", @"3");+ expectValue("proc.run('/bin/cat', [], 'through stdin').stdout", @"through stdin");+ expectValue("proc.run('/bin/sh', ['-c', 'echo oops >&2']).stderr", @"oops\n");+ (void)expectThrows("proc.run('/no/such/program')");+ // The argument vector is a stack array, so its size is the bridge's to+ // decide and not the script's.+ expectThrowsContaining("proc.run('/bin/echo', new Array(2000).fill('x'))",+ @"at most 1024 arguments");++ vp_js_capture_output(false);+ [[NSFileManager defaultManager] removeItemAtPath:directory error:nil];+}++static char *answerAPI(const char *request) {+ if (strstr(request, "\"method\":\"boom\"")) {+ return strdup("{\"type\":\"response\",\"error\":{\"code\":\"invalid_operation\",\"message\":\"no\"}}");+ }+ if (strstr(request, "\"method\":\"echo\"")) {+ return strdup("{\"type\":\"response\",\"result\":{\"saw\":\"echo\"}}");+ }+ return strdup("{\"type\":\"response\",\"result\":null}");+}++static void guestAPI(void) {+ expectThrowsContaining("api('device.snapshot')", @"no API handler");+ vp_js_set_api_handler(answerAPI);+ expectValue("api('echo').saw", @"echo");+ expectValue("api('echo', {with: 1}).saw", @"echo");+ expectThrowsContaining("api('boom')", @"invalid_operation");+ expectValue("api('other')", @"null");+ vp_js_set_api_handler(NULL);+}++// MARK: - Source Completeness++static void sourceCompleteness(void) {+ expect(!vp_js_source_is_incomplete("1 + 1"), "a statement is complete");+ expect(!vp_js_source_is_incomplete(""), "nothing is complete");+ expect(vp_js_source_is_incomplete("function f() {"), "an open brace continues");+ expect(!vp_js_source_is_incomplete("function f() {}"), "a closed brace does not");+ expect(vp_js_source_is_incomplete("[1, 2,"), "an open bracket continues");+ expect(vp_js_source_is_incomplete("f("), "an open call continues");+ expect(!vp_js_source_is_incomplete("'a {'"), "a brace inside a string is text");+ expect(!vp_js_source_is_incomplete("\"}\""), "and so is one in double quotes");+ expect(vp_js_source_is_incomplete("`line"), "a template literal spans lines");+ expect(!vp_js_source_is_incomplete("`line`"), "a closed one does not");+ expect(!vp_js_source_is_incomplete("1 // {"), "a line comment ends at the newline");+ expect(vp_js_source_is_incomplete("1 /* {"), "a block comment continues");+ expect(!vp_js_source_is_incomplete("1 /* { */"), "a closed block comment does not");+ expect(!vp_js_source_is_incomplete("'it\\'s'"), "an escaped quote stays inside the string");+ expect(!vp_js_source_is_incomplete("}"), "a stray close brace is left to the parser");+ expect(!vp_js_source_is_incomplete("/\\{/.test('{')"),+ "a brace inside a regular expression is not an open one");+ expect(!vp_js_source_is_incomplete("var r = /['\"]/;"),+ "nor is a quote inside one the start of a string");+ expect(!vp_js_source_is_incomplete("return /\\{/.test(s)"),+ "a regular expression may follow a keyword");+ expect(!vp_js_source_is_incomplete("a / b / c"), "division is not a regular expression");+ expect(vp_js_source_is_incomplete("var x = (a / b"),+ "an open call continues past a division");+ expect(vp_js_source_is_incomplete("var r = /[{/"),+ "an unterminated regular expression is read as a division");+}++// MARK: - Descriptor Accounting++/// How many descriptors this process holds. A session's pipes and terminal+/// belong to the worker, which is long-lived: one left behind for every+/// script that timed out ends in a daemon that can no longer accept a+/// connection.+static int openDescriptors(void) {+ int count = 0;+ for (int descriptor = 0; descriptor < 256; descriptor++) {+ if (fcntl(descriptor, F_GETFD) != -1) count++;+ }+ return count;+}++static void descriptorAccounting(void) {+ int status = -1;+ // One first, so what follows counts the descriptors a session opens and+ // not whatever the runtime opens once on its way up.+ free(vp_session_evaluate("1", 20, &status));++ int before = openDescriptors();+ for (int round = 0; round < 3; round++) {+ free(vp_session_evaluate("1 + 1", 20, &status));+ }+ expect(openDescriptors() == before, "an answered script leaves no descriptor behind");++ for (int round = 0; round < 3; round++) {+ char *reply = vp_session_evaluate("for (;;) {}", 0.3, &status);+ expect(reply == NULL, "a script that outran its timeout has no answer");+ free(reply);+ }+ expect(openDescriptors() == before, "nor does one that timed out");++ const char *argv[] = {"/bin/echo", "ok", NULL};+ for (int round = 0; round < 3; round++) {+ char *output = NULL;+ char *errors = NULL;+ vp_spawn_collect("/bin/echo", argv, NULL, &status, &output, &errors);+ free(output);+ free(errors);+ }+ expect(openDescriptors() == before, "nor does a program a script ran");++ pid_t session = -1;+ int master = vp_session_open(NULL, 80, 24, &session);+ expect(master >= 0, "a terminal session opened: %s", master >= 0 ? "yes" : strerror(errno));+ if (master >= 0) {+ vp_session_close(master, session, 2);+ expect(openDescriptors() == before, "nor does an interactive session that has ended");+ }+}++// MARK: - Session Processes++/// What `descriptor` has to say, up to `timeout` seconds of silence to begin+/// with and a quarter of a second once something has arrived. A terminal is+/// never closed by the side that is still talking, so quiet is the only end+/// of a reply there is.+static NSString *drain(int descriptor, double timeout) {+ NSMutableData *collected = [NSMutableData data];+ for (;;) {+ int wait_ms = collected.length ? 250 : (int)(timeout * 1000);+ struct pollfd watched = {.fd = descriptor, .events = POLLIN};+ int ready = poll(&watched, 1, wait_ms);+ if (ready < 0 && errno == EINTR) continue;+ if (ready <= 0) break;+ char bytes[4096];+ ssize_t count = read(descriptor, bytes, sizeof(bytes));+ if (count > 0) {+ [collected appendBytes:bytes length:(NSUInteger)count];+ continue;+ }+ // A pseudo-terminal whose child has gone reports EIO, not end of file.+ if (count < 0 && errno == EINTR) continue;+ break;+ }+ return [[NSString alloc] initWithData:collected encoding:NSUTF8StringEncoding] ?: @"";+}++static void oneShotEvaluation(void) {+ int status = -1;+ char *reply = vp_session_evaluate("1 + 1", 20, &status);+ expect(reply != NULL, "the session answered: %s", reply ? "yes" : strerror(errno));+ if (reply) {+ NSData *data = [@(reply) dataUsingEncoding:NSUTF8StringEncoding];+ NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ expect([object isKindOfClass:[NSDictionary class]], "the reply is a JSON object: %s", reply);+ expect([object[@"ok"] boolValue], "the evaluation succeeded: %s", reply);+ expect([object[@"result"] isEqualToString:@"2"], "1 + 1 is 2: %s", reply);+ expect([object[@"output"] isEqualToString:@""], "nothing was printed: %s", reply);+ expect(WIFEXITED(status) && WEXITSTATUS(status) == 0, "the session exited cleanly");+ free(reply);+ }++ reply = vp_session_evaluate("console.log('printed'); 'value'", 20, &status);+ expect(reply != NULL, "the session answered a printing script");+ if (reply) {+ NSDictionary *object = [NSJSONSerialization JSONObjectWithData:+ [@(reply) dataUsingEncoding:NSUTF8StringEncoding]+ options:0 error:nil];+ expect([object[@"result"] isEqualToString:@"value"], "the value came back: %s", reply);+ expect([object[@"output"] isEqualToString:@"printed\n"], "so did the output: %s", reply);+ free(reply);+ }++ reply = vp_session_evaluate("throw new Error('from a session')", 20, &status);+ if (reply) {+ NSDictionary *object = [NSJSONSerialization JSONObjectWithData:+ [@(reply) dataUsingEncoding:NSUTF8StringEncoding]+ options:0 error:nil];+ expect(![object[@"ok"] boolValue], "a throwing script is not ok: %s", reply);+ expect([object[@"error"] containsString:@"from a session"], "the error came back: %s", reply);+ free(reply);+ }++ // The reason a session is its own process: this one dies on a signal, and+ // the parent reports it rather than going down with it.+ reply = vp_session_evaluate(+ "var pid = ObjC.use('NSProcessInfo').processInfo().processIdentifier();"+ "proc.run('/bin/sh', ['-c', 'kill -ABRT ' + pid]); 'never reached'",+ 20, &status);+ expect(WIFSIGNALED(status) && WTERMSIG(status) == SIGABRT,+ "the session died on the signal, status %d", status);+ expect(!reply || strstr(reply, "never reached") == NULL, "and answered nothing");+ free(reply);++ // A script that never returns is killed, and the timeout is reported.+ double started = (double)time(NULL);+ reply = vp_session_evaluate("for (;;) {}", 2, &status);+ expect(reply == NULL && errno == ETIMEDOUT, "a runaway script times out");+ expect((double)time(NULL) - started < 10, "and is killed near its deadline");+ free(reply);+}++static void interactiveSession(void) {+ pid_t child = -1;+ int master = vp_session_open(NULL, 100, 40, &child);+ expect(master >= 0, "the REPL opened: %s", master >= 0 ? "yes" : strerror(errno));+ if (master < 0) return;++ NSString *banner = drain(master, 10);+ expect([banner containsString:@"vphoned session"], "the REPL announced itself: %s", banner.UTF8String);++ const char *script = "1 + 41\n";+ expect(write(master, script, strlen(script)) > 0, "the REPL took a line");+ NSString *answer = drain(master, 5);+ expect([answer containsString:@"42"], "and answered it: %s", answer.UTF8String);++ // A statement spread over two lines is held until it is complete.+ const char *split = "function twice(n) {\nreturn n * 2;\n}\ntwice(21)\n";+ write(master, split, strlen(split));+ answer = drain(master, 5);+ expect([answer containsString:@"42"], "a multi-line function was held and run: %s", answer.UTF8String);++ const char *help = ".help\n";+ write(master, help, strlen(help));+ answer = drain(master, 5);+ expect([answer containsString:@"ObjC.use"], ".help described the session: %s", answer.UTF8String);++ vp_session_resize(master, 120, 50);+ const char *columns = "ObjC.use('NSProcessInfo').processInfo().processName()\n";+ write(master, columns, strlen(columns));+ answer = drain(master, 5);+ expect([answer containsString:@"session-tests"], "the bridge works in a session: %s", answer.UTF8String);++ int status = vp_session_close(master, child, 3);+ expect(status != -1, "the session was reaped");+ expect(waitpid(child, NULL, WNOHANG) < 0, "and nothing is left of it");+}++static void executedProgram(void) {+ pid_t child = -1;+ int master = vp_session_open("/bin/sh", 80, 24, &child);+ expect(master >= 0, "a program opened on the terminal: %s", master >= 0 ? "yes" : strerror(errno));+ if (master < 0) return;++ const char *script = "echo from-the-shell\nexit\n";+ write(master, script, strlen(script));+ NSString *output = drain(master, 10);+ expect([output containsString:@"from-the-shell"], "the shell ran on the terminal: %s", output.UTF8String);+ vp_session_close(master, child, 3);+}++static void collectedProgram(void) {+ const char *argv[] = {"/bin/cat", NULL};+ int status = -1;+ char *output = NULL;+ char *errors = NULL;+ int failure = vp_spawn_collect("/bin/cat", argv, "piped in", &status, &output, &errors);+ expect(failure == 0, "cat ran: %s", strerror(failure));+ expect(output && strcmp(output, "piped in") == 0, "it echoed stdin: %s", output ?: "(none)");+ expect(errors && strcmp(errors, "") == 0, "with nothing on stderr");+ expect(WIFEXITED(status) && WEXITSTATUS(status) == 0, "and exited cleanly");+ free(output);+ free(errors);++ const char *missing[] = {"/no/such/program", NULL};+ failure = vp_spawn_collect("/no/such/program", missing, NULL, &status, &output, &errors);+ expect(failure == ENOENT, "a missing program is reported, not spawned: %s", strerror(failure));+ free(output);+ free(errors);+}++// MARK: - Entry++int main(void) {+ // vphoned's worker spawns its own executable to open a session. This test+ // stands in for it, so the spawning paths run against a real child.+ if (vp_native_process_mode() == 2) return vp_native_run_session();++ signal(SIGPIPE, SIG_IGN);+ runtimeBasics();+ outputCapture();+ bridgeBasics();+ bridgeRefusals();+ filesAndPrograms();+ guestAPI();+ sourceCompleteness();+ collectedProgram();+ oneShotEvaluation();+ descriptorAccounting();+ interactiveSession();+ executedProgram();+ printf("%d checks, %d failures\n", checks, failures);+ return failures == 0 ? 0 : 1;+}diff --git a/VPhoneDaemon/Tests/run-session-tests.sh b/VPhoneDaemon/Tests/run-session-tests.shnew file mode 100755index 00000000..7cb1fa2c--- /dev/null+++ b/VPhoneDaemon/Tests/run-session-tests.sh@@ -0,0 +1,28 @@+#!/bin/zsh+set -euo pipefail++# Builds the scripting session's native sources with SessionTests.m for the+# Mac and runs them: the JavaScript runtime, the ObjC bridge, the session+# process modes, and the pseudo-terminal the worker opens for an interactive+# session. The test binary answers `--session` the way vphoned does, so the+# spawning paths run against a real child. No guest is needed.+#+# JavaScriptCore is linked weakly here for the same reason vphoned links it+# weakly: watchOS has no copy, and the daemon has to start anyway.++daemon="${0:a:h:h}"+temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-session-tests.XXXXXX")"+trap '/bin/rm -rf "$temporary"' EXIT++/usr/bin/xcrun --sdk macosx clang -std=gnu11 -fobjc-arc -Wall -Wextra -Werror \+ -I "$daemon/Native" -I "$daemon/Native/Include" \+ -framework Foundation -weak_framework JavaScriptCore \+ "$daemon/Native/vphoned_proxy.c" \+ "$daemon/Native/vphoned_pty.c" \+ "$daemon/Native/vphoned_session.m" \+ "$daemon/Native/vphoned_jsbridge.m" \+ "$daemon/Native/vphoned_jscontext.m" \+ "$daemon/Tests/SessionTests.m" \+ -o "$temporary/session-tests"++"$temporary/session-tests"diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxprojindex abb20a7e..177c495f 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj@@ -263,6 +263,8 @@"-lVPhoneSign","-weak_framework",Vision,+ "-weak_framework",+ JavaScriptCore,);PRODUCT_NAME = "$(TARGET_NAME)";SDKROOT = iphoneos;@@ -284,6 +286,8 @@"-lVPhoneSign","-weak_framework",Vision,+ "-weak_framework",+ JavaScriptCore,);PRODUCT_NAME = "$(TARGET_NAME)";SDKROOT = iphoneos;diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 22a623b5..5928ee8e 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -64,6 +64,12 @@ fi/bin/rm -rf "$frameworks/VPhonePatchKit.framework"/bin/cp -R "$command_products/VPhonePatchKit.framework" "$frameworks/VPhonePatchKit.framework"/bin/cp "$TARGET_BUILD_DIR/vphone-vm" "$macos/vphone-vm"+# The terminal window's resources. libghostty is a static library, so nothing+# is embedded for it, but GhosttyTerminal reads its Ghostty directory and its+# compiled terminfo through Bundle.module, which looks beside the executable.+# Without this the window traps the moment a session is opened.+/bin/cp -R "$TARGET_BUILD_DIR/GhosttyKit_GhosttyTerminal.bundle" \+ "$macos/GhosttyKit_GhosttyTerminal.bundle"/bin/cp "$command_products/vphone-cli" "$macos/vphone-cli"/bin/cp "$amfi_products/vphone-escalator" "$macos/vphone-escalator"/bin/cp "$daemon_products/vphoned" "$guest/vphoned"@@ -187,6 +193,10 @@ compatibility_library="$(/usr/bin/xcrun swift-stdlib-tool --print \/bin/rm -f "$frameworks/libswiftCompatibilitySpan.dylib"/usr/bin/codesign --force --sign - "$frameworks/VPhonePatchKit.framework"+# A nested bundle is a subcomponent of the outer seal whether or not it holds+# any code, so this one is signed too; without it the bundle cannot be sealed+# at all.+/usr/bin/codesign --force --sign - "$macos/GhosttyKit_GhosttyTerminal.bundle"/usr/bin/codesign --force --sign - "$macos/vphone-cli"/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$guest/vphoned"/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$guest/vphoned-tvos"diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex 0592a7ec..a51e1406 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -42,6 +42,16 @@ for name in vphone-vm vphone-cli vphone-escalator libswiftCompatibilitySpan.vphorequire_signed_macho "$macos/$name"donerequire_signed_macho "$frameworks/VPhonePatchKit.framework/Versions/A/VPhonePatchKit"+# The terminal reads these through Bundle.module, which searches beside the+# executable and traps when it finds nothing. A missing resource bundle is+# therefore not a degraded terminal but a crash on opening one, and it carries+# no Mach-O, so no other check here would notice it had gone.+for name in Ghostty terminfo; do+ [[ -d "$macos/GhosttyKit_GhosttyTerminal.bundle/Contents/Resources/$name" ]] || {+ print -u2 "The Ghostty resource bundle beside vphone-vm has no $name directory"+ exit 1+ }+donerequire_signed_macho "$location_helper"/usr/bin/codesign --verify --strict "$location_app"# One requirement for every build, so locationd keeps one grant for all of@@ -169,6 +179,19 @@ daemon_rpaths="$(/usr/bin/otool -l "$guest/vphoned" | /usr/bin/awk 'print -u2 "vphoned does not use the bundled Span compatibility library"exit 1}+# The scripting session runs on JavaScriptCore, which watchOS does not ship.+# All three daemons are the same build, so a strong reference would leave the+# watch guest without a daemon at all.+for daemon in vphoned vphoned-tvos vphoned-watchos; do+ javascriptcore_loads="$(/usr/bin/otool -l "$guest/$daemon" | /usr/bin/awk '+ $1 == "cmd" { command = $2 }+ $1 == "name" && $2 ~ /JavaScriptCore/ { print command }+ ' | /usr/bin/sort -u)"+ [[ "$javascriptcore_loads" == "LC_LOAD_WEAK_DYLIB" ]] || {+ print -u2 "$daemon must load JavaScriptCore weakly, not as ${javascriptcore_loads:-nothing}"+ exit 1+ }+donefor name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist com.vphone.homepod-setup.plist; do[[ -f "$guest/$name" ]] || { print -u2 "Missing guest configuration: $name"; exit 1; }donediff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 80b94a33..743e4938 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -1003,6 +1003,20 @@ final class VPhoneGuestControl {return components.string ?? ""}+ /// A VSOCK connection of its own for a route that streams for as long as+ /// it is open, rather than answering once. The caller owns it from here:+ /// every other request sets a read timeout and closes when its reply is+ /// complete, neither of which suits a terminal that is idle most of the+ /// time. `VPhoneGuestShellChannel` is the only caller.+ func openGuestStream() async throws -> VPhoneGuestStream {+ guard let device else { throw ControlError.notConnected }+ let socket = await withCheckedContinuation {+ (continuation: CheckedContinuation<VPhoneSocketResult, Never>) in+ device.connect(toPort: 1339) { continuation.resume(returning: VPhoneSocketResult($0)) }+ }+ return VPhoneGuestStream(connection: try socket.result.get())+ }+private func httpError(_ response: VPhoneHTTPResponse) throws -> ControlError {let body = try JSONSerialization.jsonObject(with: response.body) as? [String: Any]let error = body?["error"] as? [String: Any]diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestShellChannel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestShellChannel.swiftnew file mode 100644index 00000000..49968323--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestShellChannel.swift@@ -0,0 +1,391 @@+import CryptoKit+import Foundation+import Virtualization++/// A VSOCK connection on its way off the main actor. `VZVirtioSocketConnection`+/// is not Sendable and the guest control is main-actor isolated, so a stream+/// crosses to its reader the way every other connection in this file does:+/// wrapped, and handed over exactly once.+struct VPhoneGuestStream: @unchecked Sendable {+ let connection: VZVirtioSocketConnection+}++/// A client for vphoned's `/v1/shell`: one WebSocket over a VSOCK connection+/// of its own, carrying a pseudo-terminal's byte stream both ways.+///+/// The VM process speaks vphoned's own request/response protocol everywhere+/// else, so this is the only WebSocket it opens, and it is deliberately the+/// smallest one that route needs. The guest sends binary frames of terminal+/// output and one text frame saying how the session ended; this side sends+/// binary frames of input and the occasional control message. Frames from a+/// client must be masked, which is the one piece of the protocol a server+/// implementation does not already cover.+///+/// `onOutput` and `onEnd` arrive on the channel's reader thread, and `onEnd`+/// exactly once. The reader owns the connection: it is the only thing that+/// closes it, so a late write can never reach a descriptor the guest has+/// handed to something else.+final class VPhoneGuestShellChannel: @unchecked Sendable {+ /// What a session runs, and how large its terminal starts out.+ struct Options: Sendable {+ /// Nil for vphoned's own JavaScript session; a bare name resolved+ /// from the bootstrap, or an absolute path, for a program.+ var program: String?+ var columns: Int+ var rows: Int++ init(program: String? = nil, columns: Int = 80, rows: Int = 24) {+ self.program = program+ self.columns = columns+ self.rows = rows+ }+ }++ /// How a session finished, as the guest's last text frame reported it.+ enum Ending: Sendable {+ case exited(Int)+ case signalled(Int)+ /// The session could not be opened, or the connection broke first.+ case failed(String)+ }++ enum ChannelError: Error, CustomStringConvertible {+ case handshakeFailed(String)+ case refused(String)++ var description: String {+ switch self {+ case let .handshakeFailed(detail): "The guest would not open a shell session: \(detail)"+ case let .refused(message): message+ }+ }+ }++ private let connection: VZVirtioSocketConnection+ private let descriptor: Int32+ private let onOutput: @Sendable (Data) -> Void+ private let onEnd: @Sendable (Ending) -> Void++ /// Guards writing and the one-shot teardown. Writes are short, so holding+ /// it across one is cheaper than reasoning about a half-written frame.+ private let lock = NSLock()+ private var closing = false+ private var finished = false++ private init(+ connection: VZVirtioSocketConnection,+ onOutput: @escaping @Sendable (Data) -> Void,+ onEnd: @escaping @Sendable (Ending) -> Void,+ ) {+ self.connection = connection+ descriptor = connection.fileDescriptor+ self.onOutput = onOutput+ self.onEnd = onEnd+ }++ // MARK: - Opening++ /// Opens a session and starts reading it. Throws when the guest refused+ /// the upgrade, in which case nothing was started and `onEnd` never runs.+ static func open(+ control: VPhoneGuestControl,+ options: Options,+ onOutput: @escaping @Sendable (Data) -> Void,+ onEnd: @escaping @Sendable (Ending) -> Void,+ ) async throws -> VPhoneGuestShellChannel {+ let connection = try await control.openGuestStream().connection+ let channel = VPhoneGuestShellChannel(connection: connection, onOutput: onOutput, onEnd: onEnd)+ do {+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in+ DispatchQueue.global(qos: .userInitiated).async {+ do {+ try channel.handshake(options: options)+ continuation.resume()+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }+ } catch {+ connection.close()+ throw error+ }+ let reader = Thread { channel.readFrames() }+ reader.name = "vphone.guest.shell.reader"+ reader.stackSize = 512 * 1024+ reader.start()+ return channel+ }++ private func handshake(options: Options) throws {+ // The guest never sends this side a signal it cannot handle, but a+ // write to a session that just ended would otherwise end the VM.+ guard fcntl(descriptor, F_SETNOSIGPIPE, 1) != -1 else {+ throw ChannelError.handshakeFailed("the connection was refused")+ }+ // No receive timeout on purpose: a terminal waiting for someone to+ // type is the normal state, and every other route's 120 seconds would+ // read as a broken session.+ var key = Data(count: 16)+ key.withUnsafeMutableBytes { buffer in+ if let base = buffer.bindMemory(to: UInt8.self).baseAddress {+ for index in 0 ..< buffer.count { base[index] = UInt8.random(in: 0 ... 255) }+ }+ }+ let nonce = key.base64EncodedString()++ var query = ["cols=\(max(1, min(options.columns, 9999)))", "rows=\(max(1, min(options.rows, 9999)))"]+ if let program = options.program, !program.isEmpty {+ let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~/"))+ query.insert("program=\(program.addingPercentEncoding(withAllowedCharacters: allowed) ?? program)", at: 0)+ }+ // `Host` has to be a name vphoned reads as local, and no `Origin`:+ // together they are what tells it this is not a web page. Over VSOCK+ // there is no token, which is the host proxy's concern alone.+ let request = """+ GET /v1/shell?\(query.joined(separator: "&")) HTTP/1.1\r+ Host: vphoned\r+ Upgrade: websocket\r+ Connection: Upgrade\r+ Sec-WebSocket-Key: \(nonce)\r+ Sec-WebSocket-Version: 13\r+ \r++ """+ try writeAll(Data(request.utf8))++ var head = Data()+ while head.range(of: Data("\r\n\r\n".utf8)) == nil {+ guard head.count < 16384, let more = readSome() else {+ throw ChannelError.handshakeFailed("it closed the connection without answering")+ }+ head.append(more)+ }+ guard let separator = head.range(of: Data("\r\n\r\n".utf8)),+ let text = String(data: head[head.startIndex ..< separator.lowerBound], encoding: .utf8)+ else {+ throw ChannelError.handshakeFailed("its answer was not a readable HTTP response")+ }+ let lines = text.components(separatedBy: "\r\n")+ guard let status = lines.first, status.contains(" 101 ") else {+ throw ChannelError.handshakeFailed(lines.first ?? "it sent no status line")+ }+ let expected = Data(Insecure.SHA1.hash(+ data: Data((nonce + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").utf8),+ )).base64EncodedString()+ let accepted = lines.contains { line in+ let parts = line.split(separator: ":", maxSplits: 1)+ guard parts.count == 2, parts[0].lowercased() == "sec-websocket-accept" else { return false }+ return parts[1].trimmingCharacters(in: .whitespaces) == expected+ }+ guard accepted else {+ throw ChannelError.handshakeFailed("its Sec-WebSocket-Accept did not match this request")+ }+ // Whatever arrived with the response head is already session output.+ pending = Data(head[separator.upperBound...])+ }++ // MARK: - Reading++ /// Bytes read past the end of the handshake, and past the end of a frame.+ /// Only the reader touches this after `open` returns.+ private var pending = Data()++ private func readSome() -> Data? {+ var bytes = [UInt8](repeating: 0, count: 16384)+ while true {+ let count = Darwin.read(descriptor, &bytes, bytes.count)+ if count > 0 { return Data(bytes[0 ..< count]) }+ if count < 0, errno == EINTR { continue }+ return nil+ }+ }++ /// Exactly `count` bytes, or nil once the connection ends.+ private func readExactly(_ count: Int) -> Data? {+ while pending.count < count {+ guard let more = readSome() else { return nil }+ pending.append(more)+ }+ let taken = Data(pending.prefix(count))+ pending = Data(pending.dropFirst(count))+ return taken+ }++ private func readFrames() {+ var ending: Ending = .failed("The session ended before it said how")+ var message = Data()+ var messageOpcode: UInt8 = 0++ frames: while true {+ guard let header = readExactly(2) else { break }+ let first = header[header.startIndex]+ let second = header[header.startIndex + 1]+ let isFinal = first & 0x80 != 0+ let opcode = first & 0x0F+ let masked = second & 0x80 != 0+ var length = Int(second & 0x7F)+ if length == 126 {+ guard let extended = readExactly(2) else { break }+ length = Int(extended[extended.startIndex]) << 8 | Int(extended[extended.startIndex + 1])+ } else if length == 127 {+ guard let extended = readExactly(8) else { break }+ length = 0+ for byte in extended {+ // A frame this side could not hold is a protocol error+ // rather than something to try to buffer.+ guard length < Int.max >> 8 else { break frames }+ length = length << 8 | Int(byte)+ }+ }+ guard length <= 8 << 20 else { break }+ var mask = Data()+ if masked {+ guard let read = readExactly(4) else { break }+ mask = read+ }+ guard var body = length > 0 ? readExactly(length) : Data() else { break }+ if masked, !mask.isEmpty {+ for index in 0 ..< body.count {+ body[body.startIndex + index] ^= mask[mask.startIndex + index % 4]+ }+ }++ switch opcode {+ case 0x0:+ message.append(body)+ case 0x1, 0x2:+ message = body+ messageOpcode = opcode+ case 0x8:+ break frames+ case 0x9:+ write(opcode: 0xA, payload: body)+ continue+ case 0xA:+ continue+ default:+ break frames+ }+ guard isFinal else { continue }+ if messageOpcode == 0x2 {+ if !message.isEmpty { onOutput(message) }+ } else if let described = Self.ending(from: message) {+ ending = described+ }+ message = Data()+ }++ finish(ending)+ }++ /// The guest's last text frame: `{"exit": n}`, `{"signal": n}`, or+ /// `{"error": message}` when it could not open a session at all.+ private static func ending(from payload: Data) -> Ending? {+ guard let object = try? JSONSerialization.jsonObject(with: payload) as? [String: Any] else { return nil }+ if let message = object["error"] as? String { return .failed(message) }+ if let signal = (object["signal"] as? NSNumber)?.intValue { return .signalled(signal) }+ if let status = (object["exit"] as? NSNumber)?.intValue { return .exited(status) }+ return nil+ }++ // MARK: - Writing++ func send(_ data: Data) {+ guard !data.isEmpty else { return }+ write(opcode: 0x2, payload: data)+ }++ func resize(columns: Int, rows: Int) {+ guard columns > 0, rows > 0 else { return }+ control(["resize": [min(columns, 9999), min(rows, 9999)]])+ }++ func signal(_ name: String) {+ control(["signal": name])+ }++ private func control(_ message: [String: Any]) {+ guard let encoded = try? JSONSerialization.data(withJSONObject: message) else { return }+ write(opcode: 0x1, payload: encoded)+ }++ private func write(opcode: UInt8, payload: Data) {+ lock.lock()+ defer { lock.unlock() }+ guard !closing, !finished else { return }+ try? writeAll(Self.frame(opcode: opcode, payload: payload))+ }++ /// One frame, masked as a client's frames must be.+ private static func frame(opcode: UInt8, payload: Data) -> Data {+ var out = Data([0x80 | opcode])+ let count = payload.count+ if count < 126 {+ out.append(0x80 | UInt8(count))+ } else if count <= 0xFFFF {+ out.append(0x80 | 126)+ out.append(UInt8(count >> 8))+ out.append(UInt8(count & 0xFF))+ } else {+ out.append(0x80 | 127)+ for shift in stride(from: 56, through: 0, by: -8) {+ out.append(UInt8((count >> shift) & 0xFF))+ }+ }+ var mask = [UInt8](repeating: 0, count: 4)+ for index in 0 ..< 4 { mask[index] = UInt8.random(in: 0 ... 255) }+ out.append(contentsOf: mask)+ var masked = payload+ for index in 0 ..< masked.count {+ masked[masked.startIndex + index] ^= mask[index % 4]+ }+ out.append(masked)+ return out+ }++ private func writeAll(_ data: Data) throws {+ var sent = 0+ try data.withUnsafeBytes { buffer in+ guard let base = buffer.baseAddress else { return }+ while sent < buffer.count {+ let count = Darwin.write(descriptor, base.advanced(by: sent), buffer.count - sent)+ if count > 0 {+ sent += count+ continue+ }+ if count < 0, errno == EINTR { continue }+ throw ChannelError.handshakeFailed(String(cString: strerror(errno)))+ }+ }+ }++ // MARK: - Ending++ /// Asks the session to end. The reader sees the connection close and+ /// reports the ending; nothing here closes the connection itself.+ func close() {+ lock.lock()+ let alreadyClosing = closing || finished+ closing = true+ lock.unlock()+ guard !alreadyClosing else { return }+ // A close frame is the polite half; the shutdown is what ends a guest+ // that would otherwise keep the terminal open.+ try? writeAll(Self.frame(opcode: 0x8, payload: Data([0x03, 0xE8])))+ shutdown(descriptor, SHUT_WR)+ }++ /// Runs once, on the reader thread, after the frames have stopped.+ private func finish(_ ending: Ending) {+ lock.lock()+ if finished {+ lock.unlock()+ return+ }+ finished = true+ lock.unlock()+ connection.close()+ onEnd(ending)+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneHostShellRelay.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneHostShellRelay.swiftnew file mode 100644index 00000000..cbb8dc3e--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneHostShellRelay.swift@@ -0,0 +1,176 @@+import Foundation++/// One `{"t":"shell"}` connection on `vphone.sock`: the local socket on one+/// side, the guest's terminal on the other.+///+/// The client's input ending is not the client leaving. `nc` and most pipes+/// shut their sending half as soon as their input runs out and still want+/// everything the session prints, so the end of input reaches the terminal+/// as a ^D, the way a keyboard ends it, and the session runs on. Only a+/// client that is gone altogether hangs it up. A socket shows that on its+/// sending side alone, so that is what the relay watches once input has ended.+///+/// The descriptor is closed exactly once, after both the input pump has+/// stopped and the session has ended, by whichever comes second: the pump is+/// the only thread that can still be inside `read` or waiting on `watch`.+final class VPhoneHostShellRelay: @unchecked Sendable {+ private let descriptor: Int32+ /// A kqueue that wakes the pump when the client goes, or when `end`+ /// triggers its user event because the session went first.+ private let watch: Int32+ /// Serializes writing with closing, so a write can never reach a+ /// descriptor the system has already handed to something else.+ private let lock = NSLock()+ private var closed = false+ private var pumping = false+ private var ended = false++ init(descriptor: Int32) {+ self.descriptor = descriptor+ watch = kqueue()+ var events = [+ kevent(ident: UInt(descriptor), filter: Int16(EVFILT_WRITE), flags: UInt16(EV_ADD | EV_CLEAR), fflags: 0, data: 0, udata: nil),+ kevent(ident: 0, filter: Int16(EVFILT_USER), flags: UInt16(EV_ADD | EV_CLEAR), fflags: 0, data: 0, udata: nil),+ ]+ if watch >= 0 { _ = kevent(watch, &events, Int32(events.count), nil, 0, nil) }+ }++ // MARK: - Starting++ func attach(_ channel: VPhoneGuestShellChannel, typedAhead: Data) {+ lock.lock()+ let gone = closed+ pumping = !gone+ lock.unlock()+ guard !gone else {+ channel.close()+ return+ }+ if !typedAhead.isEmpty { channel.send(typedAhead) }+ let pump = Thread { [self] in input(to: channel) }+ pump.name = "vphone.hostctl.shell"+ pump.stackSize = 512 * 1024+ pump.start()+ }++ /// Whatever the client types; once its input ends, a ^D for the terminal+ /// and a wait for the client to go, which hangs the session up.+ private func input(to channel: VPhoneGuestShellChannel) {+ var bytes = [UInt8](repeating: 0, count: 8192)+ var failed = false+ while true {+ let count = Darwin.read(descriptor, &bytes, bytes.count)+ if count > 0 {+ channel.send(Data(bytes[0 ..< count]))+ continue+ }+ if count < 0, errno == EINTR { continue }+ failed = count < 0+ break+ }++ lock.lock()+ let over = ended+ lock.unlock()+ if !over, !failed {+ // VEOF: a shell or the REPL reads end of input and finishes by+ // itself, and what it prints on the way out still arrives.+ channel.send(Data([0x04]))+ awaitDeparture()+ }++ lock.lock()+ pumping = false+ let finished = ended+ lock.unlock()+ if finished {+ closeDescriptor()+ } else {+ channel.close()+ }+ }++ /// Returns once the client can no longer be written to, or the session+ /// has ended. A half-closed client only ever shows up as writable.+ private func awaitDeparture() {+ var event = kevent()+ while true {+ let count = kevent(watch, nil, 0, &event, 1, nil)+ if count < 0, errno == EINTR { continue }+ guard count > 0 else { return }+ if event.filter == Int16(EVFILT_USER) { return }+ if event.flags & UInt16(EV_EOF) != 0 { return }+ }+ }++ // MARK: - From the Guest++ func deliver(_ data: Data) {+ write(data)+ }++ /// The last thing a client reads: how the session finished, on one line,+ /// the way every other command on this socket answers.+ func end(_ ending: VPhoneGuestShellChannel.Ending) {+ switch ending {+ case let .exited(status): writeLine(["ok": true, "exit": status])+ case let .signalled(number): writeLine(["ok": true, "signal": number])+ case let .failed(message): writeLine(["ok": false, "error": message])+ }+ lock.lock()+ ended = true+ let waiting = pumping+ if waiting {+ // Unblocks the pump wherever it is, and it then does the closing.+ shutdown(descriptor, SHUT_RDWR)+ var trigger = kevent(ident: 0, filter: Int16(EVFILT_USER), flags: 0, fflags: UInt32(NOTE_TRIGGER), data: 0, udata: nil)+ _ = kevent(watch, &trigger, 1, nil, 0, nil)+ }+ lock.unlock()+ if !waiting { closeDescriptor() }+ }++ /// A session that could not be opened at all: the reason, and no terminal.+ func refuse(_ message: String) {+ writeLine(["ok": false, "error": message])+ closeDescriptor()+ }++ // MARK: - Socket++ private func writeLine(_ object: [String: Any]) {+ guard var data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else { return }+ data.append(0x0A)+ write(data)+ }++ private func write(_ data: Data) {+ guard !data.isEmpty else { return }+ lock.lock()+ defer { lock.unlock() }+ guard !closed else { return }+ data.withUnsafeBytes { buffer in+ guard let base = buffer.baseAddress else { return }+ var sent = 0+ while sent < buffer.count {+ let count = Darwin.write(descriptor, base.advanced(by: sent), buffer.count - sent)+ if count > 0 {+ sent += count+ continue+ }+ if count < 0, errno == EINTR { continue }+ break+ }+ }+ }++ private func closeDescriptor() {+ lock.lock()+ let already = closed+ closed = true+ lock.unlock()+ guard !already else { return }+ close(descriptor)+ if watch >= 0 { close(watch) }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Shell/VPhoneShellTerminalView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Shell/VPhoneShellTerminalView.swiftnew file mode 100644index 00000000..fe07e5fb--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Shell/VPhoneShellTerminalView.swift@@ -0,0 +1,153 @@+import Foundation+import GhosttyTerminal+import SwiftUI++// MARK: - Theme++/// The terminal's look. Both sides of the theme are the same dark palette:+/// this is a research instrument whose window sits beside the guest's screen,+/// not a document that should follow the system appearance.+enum VPhoneShellTerminalTheme {+ static let configuration = TerminalConfiguration {+ $0.withCursorStyle(.block)+ $0.withCursorStyleBlink(true)+ $0.withFontSize(11)+ $0.withCustom("window-padding-color", "extend")+ }++ static let theme = TerminalTheme(light: palette(), dark: palette())++ private static func palette() -> TerminalConfiguration {+ TerminalConfiguration {+ $0.withBackground("1a1a1a")+ $0.withForeground("ffffff")+ $0.withCursorColor("98989d")+ $0.withCursorText("1a1a1a")+ $0.withSelectionBackground("333333")+ $0.withSelectionForeground("ffffff")+ let colors = [+ "#1a1a1a", "#cc372e", "#26a439", "#cdac08", "#0869cb", "#9647bf", "#479ec2", "#98989d",+ "#464646", "#ff453a", "#32d74b", "#e5bc00", "#0a84ff", "#bf5af2", "#69c9f2", "#ffffff",+ ]+ for (index, color) in colors.enumerated() {+ $0.withPalette(index, color: color)+ }+ }+ }+}++// MARK: - The Session++/// Holds the terminal and the guest channel together.+///+/// Neither can be built first: the terminal needs somewhere to send what is+/// typed before a channel exists, and the channel needs the terminal to+/// deliver what the guest says. The box is what breaks that, and it is also+/// where the channel goes when the session ends, so a keystroke after the+/// fact reaches nothing instead of a closed connection.+final class VPhoneShellTerminalLink: @unchecked Sendable {+ let session: InMemoryTerminalSession++ private final class Box: @unchecked Sendable {+ private let lock = NSLock()+ private var channel: VPhoneGuestShellChannel?++ func current() -> VPhoneGuestShellChannel? {+ lock.lock()+ defer { lock.unlock() }+ return channel+ }++ func set(_ channel: VPhoneGuestShellChannel?) {+ lock.lock()+ let previous = self.channel+ self.channel = channel+ lock.unlock()+ if channel == nil { previous?.close() }+ }+ }++ private let box = Box()+ private let opened = Date()++ init() {+ let box = self.box+ session = InMemoryTerminalSession(+ write: { data in box.current()?.send(data) },+ resize: { viewport in+ box.current()?.resize(columns: Int(viewport.columns), rows: Int(viewport.rows))+ },+ )+ }++ /// Opens a session in the guest. A refusal is written into the terminal+ /// rather than thrown: the window is already on screen, and the reason is+ /// the only thing it has to show.+ func connect(control: VPhoneGuestControl, program: String?) async {+ do {+ let channel = try await VPhoneGuestShellChannel.open(+ control: control,+ options: VPhoneGuestShellChannel.Options(program: program),+ onOutput: { [session] data in session.receive(data) },+ onEnd: { [weak self] ending in self?.finish(ending) },+ )+ box.set(channel)+ } catch {+ session.receive("\r\n\(error)\r\n")+ session.finish(exitCode: 1, runtimeMilliseconds: elapsed())+ }+ }++ /// Closing the window ends the session; the guest hangs its terminal up+ /// and anything the script started goes with it.+ func disconnect() {+ box.current()?.close()+ }++ private func finish(_ ending: VPhoneGuestShellChannel.Ending) {+ let code: UInt32+ switch ending {+ case let .exited(status):+ session.receive("\r\n[session exited with status \(status)]\r\n")+ code = UInt32(truncatingIfNeeded: status)+ case let .signalled(number):+ session.receive("\r\n[session ended on signal \(number)]\r\n")+ code = UInt32(128 + number)+ case let .failed(message):+ session.receive("\r\n[\(message)]\r\n")+ code = 1+ }+ box.set(nil)+ session.finish(exitCode: code, runtimeMilliseconds: elapsed())+ }++ private func elapsed() -> UInt64 {+ UInt64(max(0, Date().timeIntervalSince(opened)) * 1000)+ }+}++// MARK: - The View++/// A terminal in the guest. `program` is nil for vphoned's own JavaScript+/// session, which needs nothing installed, or the name of a program from the+/// bootstrap.+struct VPhoneShellTerminalView: View {+ let control: VPhoneGuestControl+ let program: String?++ @StateObject private var terminal = TerminalViewState(+ theme: VPhoneShellTerminalTheme.theme,+ terminalConfiguration: VPhoneShellTerminalTheme.configuration,+ )+ @State private var link = VPhoneShellTerminalLink()++ var body: some View {+ TerminalSurfaceView(context: terminal)+ .background(Color(red: 0x1A / 255, green: 0x1A / 255, blue: 0x1A / 255))+ .task {+ terminal.configuration = TerminalSurfaceOptions(backend: .inMemory(link.session))+ await link.connect(control: control, program: program)+ }+ .onDisappear { link.disconnect() }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Shell/VPhoneShellWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Shell/VPhoneShellWindowController.swiftnew file mode 100644index 00000000..096cc8f7--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Shell/VPhoneShellWindowController.swift@@ -0,0 +1,67 @@+import AppKit+import SwiftUI++/// The guest's terminal, in a window of its own beside the VM's screen.+///+/// A guest has no shell and the tvos preset has no debugger, so without this+/// the only way in is an RPC at a time. One window holds one session: closing+/// it ends the session, and opening it again starts a new one.+@MainActor+final class VPhoneShellWindowController {+ private var window: NSWindow?++ /// `program` is nil for vphoned's own JavaScript session, which needs+ /// nothing installed in the guest, or the name of a program from the+ /// bootstrap such as `bash`.+ func showWindow(control: VPhoneGuestControl, program: String? = nil) {+ if let window {+ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)+ return+ }++ let view = VPhoneShellTerminalView(control: control, program: program)+ let window = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 760, height: 460),+ styleMask: [.titled, .closable, .resizable, .miniaturizable],+ backing: .buffered,+ defer: false,+ )+ window.title = VPhoneLocalization.text(program == nil ? "Session" : "Terminal")+ window.subtitle = program ?? "vphoned"+ window.contentViewController = NSHostingController(rootView: view)+ window.contentMinSize = NSSize(width: 420, height: 240)+ window.setContentSize(NSSize(width: 760, height: 460))+ window.center()+ window.isReleasedWhenClosed = false+ window.level = .normal+ window.delegate = closeObserver++ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)+ self.window = window+ }++ /// The session ends with the window, and the next open starts a fresh+ /// one: a terminal whose guest has gone is not worth keeping around.+ private lazy var closeObserver: VPhoneShellWindowObserver = .init { [weak self] in+ self?.window = nil+ }+}++/// Clears the controller's window reference when the window closes. The+/// window itself is not released on close, as every programmatically created+/// window here must not be, so something has to let go of it.+@MainActor+final class VPhoneShellWindowObserver: NSObject, NSWindowDelegate {+ private let onClose: () -> Void++ init(onClose: @escaping () -> Void) {+ self.onClose = onClose+ super.init()+ }++ func windowWillClose(_: Notification) {+ onClose()+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swiftindex ee26e019..2dcf34d4 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift@@ -42,10 +42,12 @@ class VPhoneMenuController {/// Saves the Sync Host Location setting to this machine's config.plist.var onHostLocationSyncChange: ((Bool) throws -> Void)?+ var onSessionPressed: (() -> Void)?var onFilesPressed: (() -> Void)?var onKeychainPressed: (() -> Void)?var onFindPressed: (() -> Void)?var onAppsPressed: (() -> Void)?+ var connectSessionItem: NSMenuItem?var connectFileBrowserItem: NSMenuItem?var connectKeychainBrowserItem: NSMenuItem?var connectDevModeStatusItem: NSMenuItem?diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuData.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuData.swiftindex 03edb607..fe503f0f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuData.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuData.swift@@ -90,6 +90,7 @@ extension VPhoneMenuController {}func updateConnectAvailability(available: Bool) {+ connectSessionItem?.isEnabled = availableconnectFileBrowserItem?.isEnabled = availableconnectKeychainBrowserItem?.isEnabled = availableconnectDevModeStatusItem?.isEnabled = available@@ -102,6 +103,10 @@ extension VPhoneMenuController {clipboardSetItem?.isEnabled = available}+ @objc func openSession() {+ onSessionPressed?()+ }+@objc func openFiles() {onFilesPressed?()}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swiftindex 0b2c8a15..55eea8bb 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift@@ -18,6 +18,20 @@ extension VPhoneMenuController {menu.addItem(makePanelItem(.crashLogs, "Crash Logs", keyEquivalent: "c", symbol: "exclamationmark.triangle"))menu.addItem(NSMenuItem.separator())+ // A guest has no shell of its own, and the tvos preset has no+ // debugger: this window is the only place to run code inside one.+ let session = makeItem(+ "Session",+ action: #selector(openSession),+ keyEquivalent: "t",+ modifiers: [.command, .option],+ symbol: "apple.terminal",+ )+ session.isEnabled = false+ connectSessionItem = session+ menu.addItem(session)+ menu.addItem(NSMenuItem.separator())+let devModeStatus = makeItem("Developer Mode Status",action: #selector(devModeStatus),diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swiftindex 717787a7..8cf74615 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift@@ -513,10 +513,16 @@ class VPhoneHostAutomationServer {/// command itself runs on the main actor, where it awaits without/// holding a thread.private nonisolated static func serveClient(_ fd: Int32, controller: VPhoneHostAutomationServer?) {- guard let line = readLine(from: fd) else {+ guard let (line, typedAhead) = readCommand(from: fd) else {close(fd)return}+ // A shell has no reply: the connection becomes the terminal, so it+ // leaves the one-line protocol here and never comes back to it.+ if let request = shellRequest(in: line) {+ relayShell(fd, request: request, typedAhead: typedAhead, controller: controller)+ return+ }Task { @MainActor inlet response = await controller?.respond(to: line)?? reply(ok: false, error: "host control stopped")@@ -529,7 +535,10 @@ class VPhoneHostAutomationServer {// MARK: - Socket I/O- private nonisolated static func readLine(from fd: Int32) -> String? {+ /// The command line, and whatever arrived behind it. Only a shell has+ /// anything behind it: its client starts typing without waiting for a+ /// reply, and those keystrokes are already the session's input.+ private nonisolated static func readCommand(from fd: Int32) -> (line: String, rest: Data)? {var buffer = [UInt8](repeating: 0, count: 4096)var accumulated = Data()@@ -543,9 +552,69 @@ class VPhoneHostAutomationServer {}if let nlRange = accumulated.firstIndex(of: 0x0A) {- return String(data: accumulated[..<nlRange], encoding: .utf8)+ guard let line = String(data: accumulated[..<nlRange], encoding: .utf8) else { return nil }+ return (line, Data(accumulated[accumulated.index(after: nlRange)...]))+ }+ guard !accumulated.isEmpty, let line = String(data: accumulated, encoding: .utf8) else { return nil }+ return (line, Data())+ }++ // MARK: - Interactive Shell++ /// The parsed command when it is `{"t":"shell"}`, or nil for everything+ /// else, which the one-line protocol answers as it always has.+ private nonisolated static func shellRequest(in line: String) -> [String: Any]? {+ guard let data = line.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ json["t"] as? String == "shell"+ else { return nil }+ return json+ }++ /// `{"t":"shell"}` hands the connection to the guest's terminal: every+ /// byte after the command line is input, everything the session writes+ /// comes back, and one JSON line at the end says how it finished. So+ /// `nc -U .../vphone.sock` is a shell in the guest, and the terminal+ /// window opens the same route.+ ///+ /// `program` picks what runs (unset for vphoned's own JavaScript session,+ /// a bare name from the bootstrap, or an absolute path); `cols` and `rows`+ /// set the initial terminal size.+ private nonisolated static func relayShell(+ _ fd: Int32,+ request: [String: Any],+ typedAhead: Data,+ controller: VPhoneHostAutomationServer?,+ ) {+ // A terminal with nobody typing at it is the normal state, so the+ // read timeout the line protocol wants would end a healthy session.+ // The send timeout stays: a client that stops reading must not hold+ // the session's output thread for good.+ var none = timeval(tv_sec: 0, tv_usec: 0)+ _ = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &none, socklen_t(MemoryLayout<timeval>.size))+ var send = timeval(tv_sec: 30, tv_usec: 0)+ _ = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &send, socklen_t(MemoryLayout<timeval>.size))++ let relay = VPhoneHostShellRelay(descriptor: fd)+ let options = VPhoneGuestShellChannel.Options(+ program: request["program"] as? String,+ columns: (request["cols"] as? NSNumber)?.intValue ?? 80,+ rows: (request["rows"] as? NSNumber)?.intValue ?? 24,+ )+ Task { @MainActor in+ do {+ guard let controller else { throw HostControlError.guestNotConnected }+ let channel = try await VPhoneGuestShellChannel.open(+ control: try controller.connectedControl(),+ options: options,+ onOutput: { relay.deliver($0) },+ onEnd: { relay.end($0) },+ )+ relay.attach(channel, typedAhead: typedAhead)+ } catch {+ relay.refuse(String(describing: error))+ }}- return accumulated.isEmpty ? nil : String(data: accumulated, encoding: .utf8)}/// One JSON line, ready to write.diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 60db9723..fd2ca9c9 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -10,6 +10,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {private var windowController: VPhoneVirtualMachineWindowController?private var homePodDisplayTask: Task<Void, Never>?private var menuController: VPhoneMenuController?+ private var shellWindowController: VPhoneShellWindowController?private var fileWindowController: VPhoneFileWindowController?private var keychainWindowController: VPhoneKeychainWindowController?private var appWindowController: VPhoneAppWindowController?@@ -217,6 +218,9 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {}}+ let shellWC = VPhoneShellWindowController()+ shellWindowController = shellWC+let fileWC = VPhoneFileWindowController()fileWindowController = fileWC@@ -254,6 +258,10 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {mc.showsTVControls = options.isTVGuestmc.showsWatchControls = options.isWatchGuestmc.touchIDMonitor = wc.touchIDMonitor+ mc.onSessionPressed = { [weak shellWC, weak control] in+ guard let shellWC, let control else { return }+ shellWC.showWindow(control: control)+ }mc.onFilesPressed = { [weak fileWC, weak control] inguard let fileWC, let control else { return }fileWC.showWindow(control: control)diff --git a/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.pbxproj b/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.pbxprojindex dbed8f56..add68c7e 100644--- a/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.pbxproj+++ b/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.pbxproj@@ -150,6 +150,7 @@DD0000000000000000000204 /* NIOPosix */,DD0000000000000000000205 /* NIOHTTP1 */,DD0000000000000000000206 /* NIOWebSocket */,+ DD0000000000000000000207 /* GhosttyTerminal */,);productName = VPhoneVirtualMachineKit;productReference = DD0000000000000000000032 /* libVPhoneVirtualMachineKit.a */;@@ -219,6 +220,7 @@DD0000000000000000000171 /* XCRemoteSwiftPackageReference "swift-argument-parser" */,DD0000000000000000000172 /* XCRemoteSwiftPackageReference "Dynamic" */,DD0000000000000000000173 /* XCRemoteSwiftPackageReference "swift-nio" */,+ DD0000000000000000000174 /* XCRemoteSwiftPackageReference "libghostty-spm" */,);projectDirPath = "";projectRoot = "";@@ -558,6 +560,14 @@version = 2.83.0;};};+ DD0000000000000000000174 /* XCRemoteSwiftPackageReference "libghostty-spm" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/Lakr233/libghostty-spm.git";+ requirement = {+ kind = upToNextMajorVersion;+ minimumVersion = 1.6.20260928;+ };+ };/* End XCRemoteSwiftPackageReference section *//* Begin XCSwiftPackageProductDependency section */@@ -591,6 +601,11 @@package = DD0000000000000000000173 /* XCRemoteSwiftPackageReference "swift-nio" */;productName = NIOWebSocket;};+ DD0000000000000000000207 /* GhosttyTerminal */ = {+ isa = XCSwiftPackageProductDependency;+ package = DD0000000000000000000174 /* XCRemoteSwiftPackageReference "libghostty-spm" */;+ productName = GhosttyTerminal;+ };/* End XCSwiftPackageProductDependency section */};rootObject = DD0000000000000000000001 /* Project object */;diff --git a/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 99c087cc..087e11ef 100644--- a/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "38f16f31de01e807bb4da4be0f929664277a0435bca947a4bb7d6b6e69270a4c",+ "originHash" : "3fb756d4e10942659c4e6c6bba4ec1553cb455e8ef613a3b500a86789793ba8c","pins" : [{"identity" : "dynamic",@@ -10,6 +10,24 @@"version" : "1.2.0"}},+ {+ "identity" : "libghostty-spm",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/libghostty-spm.git",+ "state" : {+ "revision" : "5a025555f0a85ee51da7eb306c35f660d116e879",+ "version" : "1.6.20260928"+ }+ },+ {+ "identity" : "msdisplaylink",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/MSDisplayLink.git",+ "state" : {+ "revision" : "87eb0af130744c8cbe2e31b6e1a5bcd659f1c220",+ "version" : "2.2.0"+ }+ },{"identity" : "swift-argument-parser","kind" : "remoteSourceControl",