Run a virtual iPhone on an Apple Silicon Mac.
Swift
Run vphoned's scripting session on IcliKit's probe
git7f55bebdcbed
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex e0abf23a..bb6e7554 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -291,9 +291,13 @@ finish before closing the opposite socket, with a five-second drain limit.A guest has no shell, and the `tvos` preset has neither debugserver nor anyFrida 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+reach what the guest keeps to itself. The engine is IcliKit's probe (icli+0.10.0): its JavaScriptCore context, ObjC reflection bridge and REPL, run+inside the session process. vphoned adds only what icli leaves to the process+hosting the probe: `api()` answers with this catalog, and `proc.run` runs a+program. IcliKit opens JavaScriptCore at run time instead of linking it,+because iOS and tvOS ship it and watchOS does not, and vphoned reports+`script_js` in `capabilities` only where it can be loaded. `shell` is reportedeverywhere, because the interactive route also runs a program from thebootstrap.@@ -322,7 +326,7 @@ this guest's bootstrap actually has.For an interactive session, upgrade `GET /v1/shell` to WebSocket. Admissionis the same as `/v1/events`: no `Origin`, a loopback `Host`, and the hostproxy'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+for the probe's REPL (prompt `probe>`), 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'sbyte stream in either direction, so `^C` is simply byte 3 and the terminal@@ -357,8 +361,8 @@ either limit is refused outright — `{"error": …}` and close 1011 for`/v1/shell`, `operation_failed` for `script.eval` — rather than answeredslowly with everything else queued behind it.-The session's globals are `ObjC`, `api`, `fs`, `proc`, `console`, `print`,-`sleep` and `exit`. `ObjC.use('NSProcessInfo')` and+The session's globals are `ObjC`, `api`, `fs`, `proc`, `console`, `print`+and `sleep`. `ObjC.use('NSProcessInfo')` and`ObjC.classes.NSProcessInfo` both give a class, and methods are called byname: an underscore stands for a colon (`setValue_forKey_(v, k)`), a barename takes one colon per argument, and a name written with colons is used as@@ -379,11 +383,16 @@ an object and never as a value, because an allocated `NSString` is aplaceholder 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`,+process and returns its result, raising `code: message` 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`.+the terminal, or into `output` for `script.eval`. `proc.run` is vphoned's,+not icli's: the probe launches nothing itself, so the session defines `proc`+over `api('proc.run', {path, args, input})`, which only a session answers.+There is no `exit()`; `.exit` leaves the REPL. In the REPL, `^C` abandons a+half-finished statement while a line is being read; while a statement runs,+it ends the session, which the WebSocket reports as `{"signal": 2}`.This opens no privilege the API did not already have: the same connection canalready write any file as root and load a launch daemon. What it does changediff --git a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex b3e0bb6f..0255836c 100644--- a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "a6866c860e660ef27df596c0ba8795342d386b1b265f3a7cc212d640cd67c649",+ "originHash" : "205a9c9c5f188171fc901d3eb8077faf89b548744c0307a4f382e74b3f278a54","pins" : [{"identity" : "applemobiledevicelibrary",@@ -24,8 +24,8 @@"kind" : "remoteSourceControl","location" : "https://github.com/owngoal-dev/icli.git","state" : {- "revision" : "217dc37e55ef44bf6a0739358f2486e660b05d40",- "version" : "0.9.2"+ "revision" : "2fbdb5ee61d8c320732deb9768b22506f5e3d411",+ "version" : "0.10.0"}},{diff --git a/VPhoneDaemon/Daemon/GuestAPI+Script.swift b/VPhoneDaemon/Daemon/GuestAPI+Script.swiftindex 98329135..a7b2a50d 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Script.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Script.swift@@ -1,5 +1,6 @@import Darwinimport Foundation+import IcliKitimport VphonedNative// MARK: - Scripting@@ -29,7 +30,7 @@ extension GuestAPI {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"]+ probeAvailable() ? ["shell", "script_js"] : ["shell"]}/// Long enough for a script that waits on a system service, short enough@@ -41,7 +42,7 @@ extension GuestAPI {}private static func evaluateScript(source: String, timeout: Double) throws -> [String: Any] {- guard vp_js_available() else {+ guard probeAvailable() else {throw GuestAPIError.operationFailed("This guest has no JavaScriptCore, so it cannot run a script")}guard GuestSessionLimit.evaluations.acquire() else {@@ -91,9 +92,9 @@ extension GuestAPI {}}return [- "available": vp_js_available(),+ "available": probeAvailable(),"engine": "JavaScriptCore",- "globals": ["ObjC", "api", "fs", "proc", "console", "print", "sleep", "exit"],+ "globals": ["ObjC", "api", "fs", "proc", "console", "print", "sleep"],"programs": programs,]}diff --git a/VPhoneDaemon/Daemon/GuestScriptSession.swift b/VPhoneDaemon/Daemon/GuestScriptSession.swiftnew file mode 100644index 00000000..8d448286--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestScriptSession.swift@@ -0,0 +1,144 @@+import Darwin+import Foundation+import IcliKit+import VphonedNative++// MARK: - Session Process++/// The `--session` process the worker spawns for one script (`eval`), one+/// interactive session (`repl`) or one program on a terminal (`exec`).+/// Nothing of the worker's startup has run 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.+///+/// The engine is IcliKit's probe, which runs inline in this process. vphoned+/// adds what icli leaves to the process hosting it: `api()` answers with the+/// guest API instead of icli's read-only set, and `proc.run` runs a program.+enum GuestScriptSession {+ static func run() -> Int32 {+ let arguments = CommandLine.arguments+ switch arguments.count > 2 ? arguments[2] : "" {+ case "eval": return evaluate()+ case "repl": return interact()+ case "exec": return vp_session_exec()+ default: return 64+ }+ }++ // MARK: - One Script++ /// Evaluate what the worker writes to stdin and answer with one JSON line,+ /// `{ok, result | error, output}`; stdout carries nothing else.+ private static func evaluate() -> Int32 {+ // 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()+ let source = readSource()+ _ = installProcess()+ let probe = evaluateProbe(source, api: answer)+ var reply: [String: Any] = ["ok": probe.ok, "output": probe.output]+ reply["result"] = probe.result+ reply["error"] = probe.error+ let encoded = (try? JSONSerialization.data(withJSONObject: reply))+ ?? Data(#"{"ok":false,"error":"The reply could not be encoded","output":""}"#.utf8)+ FileHandle.standardOutput.write(encoded + Data("\n".utf8))+ return probe.ok ? 0 : 65+ }++ /// Everything on stdin, which the worker closes once it has sent the source.+ private static func readSource() -> String {+ var collected = Data()+ var bytes = [UInt8](repeating: 0, count: 16384)+ while true {+ let count = read(STDIN_FILENO, &bytes, bytes.count)+ if count > 0 {+ if collected.count < 4 << 20 { collected.append(bytes, count: count) }+ continue+ }+ if count < 0, errno == EINTR { continue }+ break+ }+ return String(decoding: collected, as: UTF8.self)+ }++ // MARK: - Interactive++ /// The probe's REPL on the session's terminal, until end of input or `.exit`.+ private static func interact() -> Int32 {+ vp_session_detach()+ let started = installProcess()+ guard started.ok else {+ fputs("\(started.error ?? "The session could not start")\n", stderr)+ return 70+ }+ print("vphoned session: api() reaches the guest API; proc.run(path, [args], input) runs a program.")+ return runProbeREPL(api: answer)+ }++ // MARK: - What vphoned Adds++ /// `proc.run` over `api('proc.run')`, under the name scripts already use.+ /// The probe keeps one context per process, so this outlives the call.+ private static func installProcess() -> ProbeResult {+ evaluateProbe("""+ (function (global) {+ global.proc = {+ run: function (path, args, input) {+ return api('proc.run', {path: path, args: args || [], input: input === undefined ? null : input});+ },+ };+ })(this);+ """)+ }++ /// A script's `api(method, params)`: `proc.run`, or any guest API method,+ /// answered in this process.+ private static func answer(_ method: String, _ params: [String: Any]) throws -> Any {+ if method == "proc.run" { return try runProgram(params) }+ do {+ return try GuestAPI.execute(method: method, params: params)+ } catch let error as IcliError {+ throw error+ } catch let error as GuestAPIError {+ throw ProbeAPIError(code: error.code, message: error.description)+ } catch {+ throw ProbeAPIError(code: "operation_failed", message: String(describing: error))+ }+ }++ /// One program, run to its end: `{status, signal, stdout, stderr}`.+ private static func runProgram(_ params: [String: Any]) throws -> [String: Any] {+ guard let path = params["path"] as? String, !path.isEmpty else {+ throw ProbeAPIError(code: "invalid_request", message: "proc.run needs a program path")+ }+ let words = [path] + (params["args"] as? [Any] ?? []).map { String(describing: $0) }+ var argv: [UnsafePointer<CChar>?] = words.map { UnsafePointer(strdup($0)) } + [nil]+ defer { argv.forEach { free(UnsafeMutablePointer(mutating: $0)) } }+ var status: Int32 = 0+ var output: UnsafeMutablePointer<CChar>?+ var errors: UnsafeMutablePointer<CChar>?+ defer {+ free(output)+ free(errors)+ }+ func spawn(_ input: UnsafePointer<CChar>?) -> Int32 {+ vp_spawn_collect(path, &argv, input, &status, &output, &errors)+ }+ let failure = if let input = params["input"] as? String {+ input.withCString { spawn($0) }+ } else {+ spawn(nil)+ }+ guard failure == 0 else {+ throw ProbeAPIError(code: "operation_failed", message: "\(path): \(String(cString: strerror(failure)))")+ }+ let signal = status & 0x7F+ return [+ "status": signal == 0 ? (status >> 8) & 0xFF : -1,+ "signal": signal != 0 && signal != 0x7F ? signal : NSNull(),+ "stdout": output.map { String(cString: $0) } ?? "",+ "stderr": errors.map { String(cString: $0) } ?? "",+ ]+ }+}diff --git a/VPhoneDaemon/Daemon/GuestShellSessionHandler.swift b/VPhoneDaemon/Daemon/GuestShellSessionHandler.swiftindex 45ff74e5..eb7ce6c2 100644--- a/VPhoneDaemon/Daemon/GuestShellSessionHandler.swift+++ b/VPhoneDaemon/Daemon/GuestShellSessionHandler.swift@@ -1,5 +1,6 @@import Darwinimport Foundation+import IcliKitimport NIOCoreimport NIOWebSocketimport VphonedNative@@ -162,7 +163,7 @@ final class GuestShellSessionHandler: ChannelInboundHandler, @unchecked Sendablerefuse(String(describing: error), on: channel)return}- if program == nil, !vp_js_available() {+ if program == nil, !probeAvailable() {GuestSessionLimit.interactive.release()refuse("This guest has no JavaScriptCore, so there is no session to open.", on: channel)returndiff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex a4db30de..5301511b 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -5,27 +5,12 @@ 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())+ // interactive session. None of the startup below belongs here; see+ // GuestScriptSession.+ exit(GuestScriptSession.run())}if mode != 1 {guard mode == 0 else { exit(64) }diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex ddda7312..350d9736 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -22,19 +22,21 @@ 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));+/// Lead a process group of the session's own, and take its terminal, when it+/// has one, as the controlling terminal. A `--session` process calls this+/// before anything else runs: the worker ends a session by its group.+void vp_session_detach(void);++/// Replace this `--session exec <program>` process with the program, on the+/// session's terminal. Returns only when that fails, with the exit status.+int vp_session_exec(void);++/// Run one program and collect what it writes, for a script's `proc.run`.+/// `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 * _Nonnull path, const char * _Nullable const * _Nonnull argv,+ const char * _Nullable input, int * _Nonnull status,+ char * _Nullable * _Nonnull output, char * _Nullable * _Nonnull errors);/// 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` isdiff --git a/VPhoneDaemon/Native/vphoned_jsbridge.h b/VPhoneDaemon/Native/vphoned_jsbridge.hdeleted file mode 100644index a36cf143..00000000--- a/VPhoneDaemon/Native/vphoned_jsbridge.h+++ /dev/null@@ -1,22 +0,0 @@-#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.mdeleted file mode 100644index 8cb35286..00000000--- a/VPhoneDaemon/Native/vphoned_jsbridge.m+++ /dev/null@@ -1,340 +0,0 @@-#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.mdeleted file mode 100644index a97d0bce..00000000--- a/VPhoneDaemon/Native/vphoned_jscontext.m+++ /dev/null@@ -1,381 +0,0 @@-#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_session.h b/VPhoneDaemon/Native/vphoned_session.hindex cc41cf4c..b8d1990c 100644--- a/VPhoneDaemon/Native/vphoned_session.h+++ b/VPhoneDaemon/Native/vphoned_session.h@@ -2,42 +2,13 @@#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.+// code with vphoned's identity inside a guest. The script itself runs in+// IcliKit's probe (GuestScriptSession.swift); what the `--session` process+// settles natively, and the worker side, are 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.mindex 27d5fa5e..4a0ae417 100644--- a/VPhoneDaemon/Native/vphoned_session.m+++ b/VPhoneDaemon/Native/vphoned_session.m@@ -1,27 +1,16 @@#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;-}+// A script runs in IcliKit's probe, driven from GuestScriptSession.swift; this+// file keeps what the process has to settle natively before it does.// MARK: - Arguments@@ -43,332 +32,26 @@ bool vp_session_arguments_present(void) {// 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) {+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);-}+// MARK: - Running a Program-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) {+int vp_session_exec(void) {+ int argc = 0;+ char **argv = NULL;+ const char *kind = vp_session_kind(&argc, &argv);+ if (!kind || strcmp(kind, "exec") != 0 || argc < 4) {fputs("vphoned --session exec needs a program\n", stderr);return 64;}@@ -377,15 +60,3 @@ static int vp_session_exec(int argc, char **argv) {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.mindex 4feff4db..bc1d3b37 100644--- a/VPhoneDaemon/Tests/SessionTests.m+++ b/VPhoneDaemon/Tests/SessionTests.m@@ -9,14 +9,18 @@#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <sys/ioctl.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.+// Checks the worker's side of a scripting session on the Mac: the one-shot+// and interactive session processes, their timeouts and terminals, and the+// one program a script's proc.run collects. 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. The script engine is+// IcliKit's probe, which builds only for iOS and tvOS and is tested in icli,+// so a stand-in session answers here in its place. `run-session-tests.sh`+// builds it.static int checks;static int failures;@@ -33,254 +37,43 @@ static void expect(bool condition, const char *format, ...) {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\"}}");+// MARK: - The Stand-In Session++/// vphoned's GuestScriptSession, reduced to what the worker can observe.+/// `eval` answers its source back as one JSON line, except that `abort` dies+/// on a signal and `hang` never answers; `repl` echoes each line and reports+/// its terminal's size for `size`; `exec` is vphoned's own.+static int standInSession(void) {+ NSString *kind = NSProcessInfo.processInfo.arguments[2];+ if ([kind isEqualToString:@"exec"]) return vp_session_exec();+ vp_session_detach();+ if ([kind isEqualToString:@"eval"]) {+ NSData *input = [[NSFileHandle fileHandleWithStandardInput] readDataToEndOfFile];+ NSString *source = [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding] ?: @"";+ if ([source isEqualToString:@"abort"]) abort();+ if ([source isEqualToString:@"hang"]) {+ for (;;) pause();+ }+ NSData *reply = [NSJSONSerialization dataWithJSONObject:@{@"ok": @YES, @"result": source, @"output": @""}+ options:0 error:nil];+ fwrite(reply.bytes, 1, reply.length, stdout);+ fputc('\n', stdout);+ return 0;}- if (strstr(request, "\"method\":\"echo\"")) {- return strdup("{\"type\":\"response\",\"result\":{\"saw\":\"echo\"}}");+ printf("stand-in session\n");+ fflush(stdout);+ char line[4096];+ while (fgets(line, sizeof(line), stdin)) {+ if (strncmp(line, "size", 4) == 0) {+ struct winsize size = {0};+ ioctl(STDIN_FILENO, TIOCGWINSZ, &size);+ printf("%dx%d\n", size.ws_col, size.ws_row);+ } else {+ printf("said: %s", line);+ }+ fflush(stdout);}- 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");+ return 0;}// MARK: - Descriptor Accounting@@ -310,7 +103,7 @@ static void descriptorAccounting(void) {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);+ char *reply = vp_session_evaluate("hang", 0.3, &status);expect(reply == NULL, "a script that outran its timeout has no answer");free(reply);}@@ -371,47 +164,22 @@ static void oneShotEvaluation(void) {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([object[@"result"] isEqualToString:@"1 + 1"], "the source reached the session: %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);+ reply = vp_session_evaluate("abort", 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");+ expect(!reply || !*reply, "and answered nothing");free(reply);- // A script that never returns is killed, and the timeout is reported.+ // A session that never answers is killed, and the timeout is reported.double started = (double)time(NULL);- reply = vp_session_evaluate("for (;;) {}", 2, &status);+ reply = vp_session_evaluate("hang", 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);@@ -424,29 +192,18 @@ static void interactiveSession(void) {if (master < 0) return;NSString *banner = drain(master, 10);- expect([banner containsString:@"vphoned session"], "the REPL announced itself: %s", banner.UTF8String);+ expect([banner containsString:@"stand-in session"], "the session started: %s", banner.UTF8String);- const char *script = "1 + 41\n";- expect(write(master, script, strlen(script)) > 0, "the REPL took a line");+ const char *line = "hello\n";+ expect(write(master, line, strlen(line)) > 0, "the session 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);+ expect([answer containsString:@"said: hello"], "and answered it: %s", answer.UTF8String);vp_session_resize(master, 120, 50);- const char *columns = "ObjC.use('NSProcessInfo').processInfo().processName()\n";- write(master, columns, strlen(columns));+ const char *size = "size\n";+ write(master, size, strlen(size));answer = drain(master, 5);- expect([answer containsString:@"session-tests"], "the bridge works in a session: %s", answer.UTF8String);+ expect([answer containsString:@"120x50"], "the terminal took its new size: %s", answer.UTF8String);int status = vp_session_close(master, child, 3);expect(status != -1, "the session was reaped");@@ -466,6 +223,8 @@ static void executedProgram(void) {vp_session_close(master, child, 3);}+// MARK: - Running One Program+static void collectedProgram(void) {const char *argv[] = {"/bin/cat", NULL};int status = -1;@@ -479,6 +238,14 @@ static void collectedProgram(void) {free(output);free(errors);+ const char *failing[] = {"/bin/sh", "-c", "echo oops >&2; exit 3", NULL};+ failure = vp_spawn_collect("/bin/sh", failing, NULL, &status, &output, &errors);+ expect(failure == 0, "sh ran: %s", strerror(failure));+ expect(errors && strcmp(errors, "oops\n") == 0, "its stderr was collected: %s", errors ?: "(none)");+ expect(WIFEXITED(status) && WEXITSTATUS(status) == 3, "with its exit status");+ 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));@@ -491,16 +258,9 @@ static void collectedProgram(void) {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();+ if (vp_native_process_mode() == 2) return standInSession();signal(SIGPIPE, SIG_IGN);- runtimeBasics();- outputCapture();- bridgeBasics();- bridgeRefusals();- filesAndPrograms();- guestAPI();- sourceCompleteness();collectedProgram();oneShotEvaluation();descriptorAccounting();diff --git a/VPhoneDaemon/Tests/run-session-tests.sh b/VPhoneDaemon/Tests/run-session-tests.shindex 7cb1fa2c..1b093642 100755--- a/VPhoneDaemon/Tests/run-session-tests.sh+++ b/VPhoneDaemon/Tests/run-session-tests.sh@@ -2,13 +2,11 @@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.+# Mac and runs them: the session process modes, their timeouts, the+# pseudo-terminal the worker opens for an interactive session, and the one+# program a script's proc.run collects. The test binary answers `--session`+# the way vphoned does, so the spawning paths run against a real child. No+# guest is needed. The script engine is IcliKit's probe, tested in icli.daemon="${0:a:h:h}"temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-session-tests.XXXXXX")"@@ -16,12 +14,10 @@ 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 \+ -framework Foundation \"$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"diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxprojindex 177c495f..efd8f2aa 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj@@ -263,8 +263,6 @@"-lVPhoneSign","-weak_framework",Vision,- "-weak_framework",- JavaScriptCore,);PRODUCT_NAME = "$(TARGET_NAME)";SDKROOT = iphoneos;@@ -286,8 +284,6 @@"-lVPhoneSign","-weak_framework",Vision,- "-weak_framework",- JavaScriptCore,);PRODUCT_NAME = "$(TARGET_NAME)";SDKROOT = iphoneos;@@ -357,7 +353,7 @@repositoryURL = "https://github.com/owngoal-dev/icli.git";requirement = {kind = upToNextMajorVersion;- minimumVersion = 0.9.2;+ minimumVersion = 0.10.0;};};C10000000000000000000072 /* XCRemoteSwiftPackageReference "swift-nio" */ = {diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex cd9f11e3..2078a7ca 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -6,8 +6,8 @@"kind" : "remoteSourceControl","location" : "https://github.com/owngoal-dev/icli.git","state" : {- "revision" : "217dc37e55ef44bf6a0739358f2486e660b05d40",- "version" : "0.9.2"+ "revision" : "2fbdb5ee61d8c320732deb9768b22506f5e3d411",+ "version" : "0.10.0"}},{diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex 579a001b..7d946fba 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -181,15 +181,15 @@ daemon_rpaths="$(/usr/bin/otool -l "$guest/vphoned" | /usr/bin/awk '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.+# IcliKit's probe opens it at run time, so the daemon names no JavaScriptCore+# symbol; a reference would leave the watch guest without a daemon at all.for daemon in vphoned vphoned-tvos vphoned-watchos; dojavascriptcore_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}"+ [[ -z "$javascriptcore_loads" ]] || {+ print -u2 "$daemon must not link JavaScriptCore, which the probe opens at run time: $javascriptcore_loads"exit 1}done