From 71c4e4c437e6c6daf3e3980a608f606a768f716c Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Sat, 17 Oct 2026 22:50:09 +0300 Subject: [PATCH 01/16] Add isolated extension workers for native shell panes --- README.md | 10 + ShellWorkers/Host.swift | 98 +++ ShellWorkers/NativePane.h | 45 + ShellWorkers/NativePane.m | 799 +++++++++++++++++ ShellWorkers/PaneWire.h | 15 + ShellWorkers/RemotePane.m | 175 ++++ ShellWorkers/Worker.m | 178 ++++ ShellWorkers/Worker.swift | 28 + ShellWorkers/Worker.xcconfig | 22 + ShellWorkers/resources.sh | 14 + a-Shell-mini-Info.plist | 2 + a-Shell.xcodeproj/project.pbxproj | 1334 +++++++++++++++++++++++++++++ tests/worker-pool.m | 226 +++++ tests/worker-pool.md | 19 + 14 files changed, 2965 insertions(+) create mode 100644 ShellWorkers/Host.swift create mode 100644 ShellWorkers/NativePane.h create mode 100644 ShellWorkers/NativePane.m create mode 100644 ShellWorkers/PaneWire.h create mode 100644 ShellWorkers/RemotePane.m create mode 100644 ShellWorkers/Worker.m create mode 100644 ShellWorkers/Worker.swift create mode 100644 ShellWorkers/Worker.xcconfig create mode 100644 ShellWorkers/resources.sh create mode 100644 tests/worker-pool.m create mode 100644 tests/worker-pool.md diff --git a/README.md b/README.md index 156cb785..ce15a868 100644 --- a/README.md +++ b/README.md @@ -89,3 +89,13 @@ TeX files are not installed by default. Type any TeX command and the system will ## VoiceOver If you enable VoiceOver in Settings, a-Shell will work with VoiceOver: reading commands as you type them, reading the result, letting you read the screen with your finger... + +## Independent shell workers + +On iOS 26 and later, the mini target includes ten dedicated Generic Non-UI extensions, `ShellWorkerA` through `ShellWorkerJ`. Each worker owns one native command and its ios_system state. The original Intents and IntentsUI targets remain separate. Consumers call `ashell_pane_spawn` from a background thread, read the returned full-duplex descriptor, poll completion and release the opaque handle. The API and stream ownership rules are in `ShellWorkers/NativePane.h`. + +The host retains each `AppExtensionProcess` and XPC connection until release or interruption. A full pool returns `ENOSPC`; earlier iOS versions return `ENOTSUP`. Cancel and release terminate the dedicated worker through XPC before freeing its reservation; releasing an ExtensionFoundation assertion alone permits process reuse. Commands that ignore EOF therefore cannot retain a released slot. A lost worker reports status 137 while the host and other workers remain available. Directory access uses security-scoped bookmarks and is checked with actual file operations in the worker. + +Workers share the host's command libraries. Build with ios_system changes #179–#184 and dash_iOS#1–#2, including the matched libedit dependency described there. The build derives each worker's catalogue and executable markers from `Resources_mini/commandDictionary.plist`; it generates the ExtensionFoundation binding from `PRODUCT_BUNDLE_PREFIX`. Keep worker versions in `ShellWorkers/Worker.xcconfig` aligned with the containing app. The mini bundle suffixes are `.ShellWorkerA` through `.ShellWorkerJ`; each requires its own App ID and profile for a device build. + +`tests/worker-pool.m` is a real app-command consumer for Simulator qualification. Device memory limits, background execution without other host background modes, and App Store acceptance require separate validation. Retaining the process handle provides no promise of unlimited background execution. diff --git a/ShellWorkers/Host.swift b/ShellWorkers/Host.swift new file mode 100644 index 00000000..9028e57e --- /dev/null +++ b/ShellWorkers/Host.swift @@ -0,0 +1,98 @@ +import ExtensionFoundation +import Foundation + +@available(iOS 26.0, *) +extension AppExtensionPoint { + @Definition + static var shellWorker: AppExtensionPoint { Name("ShellWorker") } +} + +// Process lifetime and discovery belong to MainActor. Blocking C ABI calls wait +// only on the calling runner thread, never on the UI actor. +@available(iOS 26.0, *) +@MainActor +final class ShellWorkerPool { + static let shared = ShellWorkerPool() + private enum Slot { + case launching(UUID) + case connected(UUID, AppExtensionProcess, NSXPCConnection) + + var generation: UUID { + switch self { + case .launching(let generation), .connected(let generation, _, _): generation + } + } + } + private var slots: [String: Slot] = [:] + + func connect() async throws -> NSXPCConnection { + guard Bundle.main.object(forInfoDictionaryKey: "ShellWorkerCount") != nil else { + throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENOTSUP)) + } + let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: .shellWorker) + for _ in 0..<100 { + let configured = Bundle.main.object(forInfoDictionaryKey: "ShellWorkerCount") + let capacity = (configured as? NSNumber)?.intValue ?? Int(configured as? String ?? "") ?? 0 + if capacity > 0 && slots.count >= capacity { + throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENOSPC), userInfo: [NSLocalizedDescriptionKey: "All shell workers are in use. Close a pane before opening another."]) + } + if let identity = monitor.identities.sorted(by: { $0.bundleIdentifier < $1.bundleIdentifier }).first(where: { slots[$0.bundleIdentifier] == nil }) { + let key = identity.bundleIdentifier + let generation = UUID() + slots[key] = .launching(generation) + do { + let process = try await AppExtensionProcess(configuration: .init(appExtensionIdentity: identity, onInterruption: { + Task { @MainActor in + guard self.slots[key]?.generation == generation else { return } + self.slots.removeValue(forKey: key) + } + })) + guard slots[key]?.generation == generation else { + process.invalidate() + throw CancellationError() + } + let connection = try process.makeXPCConnection() + slots[key] = .connected(generation, process, connection) + return connection + } catch { + if slots[key]?.generation == generation { slots.removeValue(forKey: key) } + throw error + } + } + try await Task.sleep(for: .milliseconds(100)) + } + throw NSError(domain: NSPOSIXErrorDomain, code: Int(ETIMEDOUT), userInfo: [NSLocalizedDescriptionKey: "shell worker discovery timed out"]) + } + + func disconnect(_ connection: NSXPCConnection) { + for (key, slot) in slots { + guard case .connected(_, let process, let stored) = slot, stored === connection else { continue } + // Explicit invalidation does not guarantee an interruption callback. + // Release the reservation in this MainActor transaction; generation + // checks keep a late callback from removing a replacement process. + connection.invalidate() + process.invalidate() + slots.removeValue(forKey: key) + return + } + } +} + +@_cdecl("ashell_extension_disconnect") +func shellExtensionDisconnect(_ connection: NSXPCConnection) { + if #available(iOS 26.0, *) { + Task { @MainActor in ShellWorkerPool.shared.disconnect(connection) } + } +} + +@_cdecl("ashell_extension_connect") +func shellExtensionConnect(_ callback: @escaping @convention(block) (NSXPCConnection?, NSError?) -> Void) { + guard #available(iOS 26.0, *) else { + callback(nil, NSError(domain: NSPOSIXErrorDomain, code: Int(ENOTSUP))) + return + } + Task { @MainActor in + do { callback(try await ShellWorkerPool.shared.connect(), nil) } + catch { callback(nil, error as NSError) } + } +} diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h new file mode 100644 index 00000000..0249cf84 --- /dev/null +++ b/ShellWorkers/NativePane.h @@ -0,0 +1,45 @@ +#ifndef ASHELL_NATIVE_PANE_H +#define ASHELL_NATIVE_PANE_H + +#ifdef __cplusplus +extern "C" { +#endif + +// command/cwd must be nonempty UTF-8; cwd must be an absolute accessible directory. +// envp is NULL or a NULL-terminated list of UTF-8 key=value overrides, copied before return. +// Dimensions are 1..9999. Returns 0 or positive errno; failure sets outputs to -1/NULL. +// Success transfers the full-duplex fd to the caller; stderr shares stdout. +// Host handles use independent extension processes and socket streams. Each worker +// accepts one native pane. Stock ios_system globals stay private to that process. +// The caller may set O_NONBLOCK on its returned descriptor. +int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, + unsigned rows, const char *const *envp, int *fd_out, void **job_out); + +// Returns 0 running, 1 exited (writes final command status), or -errno. +// Repeated polling after exit preserves status. Drain the returned fd to EOF independently. +// A cleanup/restore error returns -errno after completion instead of hiding the failure. +int ashell_pane_poll(void *job, int *status_out); + +// These operations return 0 or POSITIVE errno, unlike poll. +// Resize updates the worker command dimensions through ios_setWindowSize. +int ashell_pane_resize(void *job, unsigned cols, unsigned rows); +// Half-close socket stdin while keeping output open. Repeated calls are harmless. +int ashell_pane_close_stdin(void *job); +// Host cancellation terminates the entire worker process. The worker-local +// adapter returns ENOTSUP while running; interrupt targets only its foreground command. +int ashell_pane_cancel(void *job); +// Interrupt a cooked foreground command; ENOTSUP means forward ETX to the TUI/editor. +int ashell_pane_interrupt(void *job); + +// Release the host connection and worker process, then drop the caller reference. +// The worker-local adapter retains live runners and their streams through cleanup. +// Caller must invalidate its pointer and release exactly once. No concurrent release +// with another call: serialize calls on each handle. +// Close the returned fd separately. +// The handle is opaque and is NOT an OS pid: never pass it to kill/waitpid/process APIs. +void ashell_pane_release(void *job); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m new file mode 100644 index 00000000..29db5b84 --- /dev/null +++ b/ShellWorkers/NativePane.m @@ -0,0 +1,799 @@ +#import +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#import "ios_system/ios_system.h" +#include "NativePane.h" + +// Each extension process owns one active native pane. +static _Atomic int pane_in_flight; +// Stock explicit-PID setter avoids the libc setenv fallback for the parent PID. +extern int ios_setenv_pid(const char *, const char *, int, int); + +typedef struct { + pthread_mutex_t mutex; + pthread_cond_t ready; + unsigned refs; + int initialized, startup_error, done, status, completion_error; + int peer_control, input_closed, is_pty; + unsigned char eof_key; + FILE *streams[3]; + void *registration; + char key[64]; + char *command, *cwd, *previous_cwd; + char **env; + unsigned cols, rows; + struct pane_input_relay *input_relay; +} pane_job; + +// One pane owns this process. Dash's optional evaluation hook borrows a fresh +// stdin pipe, while the relay keeps the editor pipe and socket alive. +static _Atomic(pane_job *) foreground_pane; +// Dash publishes the synthetic child PID before dispatch and restores its +// parent's PID after waiting. lastThreadId instead names the first descendant, +// which can be a shell blocked in ios_waitpid rather than the running command. +static _Atomic int foreground_command_pid; + +__attribute__((used)) int ashell_pane_exchange_foreground_pid(int pid) { + return atomic_exchange(&foreground_command_pid, pid); +} + +typedef struct { + unsigned char bytes[262144]; + size_t length; +} input_queue; + +typedef struct command_input { + FILE *reader; + pane_job *job; + int writer; + void *registration; + struct pane_input_relay *relay; +} command_input; + +typedef struct pane_input_relay { + pthread_mutex_t mutex; + pthread_cond_t changed; + pthread_t thread; + int socket, editor_reader, editor_writer, wake[2], editor_events; + int running, stop, error, input_eof, command_eof; + int request, request_done, request_error; + command_input *command, *requested_command; + input_queue editor_queue, command_queue; + int (*interactive)(void); +} pane_input_relay; + +enum { INPUT_BEGIN = 1, INPUT_END, INPUT_RETIRE }; + +static int append_input(input_queue *queue, const void *bytes, size_t length) { + if (length > sizeof(queue->bytes) - queue->length) return EOVERFLOW; + memcpy(queue->bytes + queue->length, bytes, length); + queue->length += length; + return 0; +} + +static int drain_input(int fd, input_queue *queue) { + unsigned char bytes[4096]; + struct pollfd available = {.fd = fd, .events = POLLIN}; + for (;;) { + int count = poll(&available, 1, 0); + if (count < 0) { if (errno == EINTR) continue; return errno; } + if (!count) return 0; + ssize_t length = read(fd, bytes, sizeof(bytes)); + if (length < 0) { if (errno == EINTR) continue; return errno; } + if (!length) return 0; + int error = append_input(queue, bytes, (size_t)length); + if (error) return error; + } +} + +static void close_input_writer(int *writer) { + if (*writer >= 0) close(*writer); + *writer = -1; +} + +static int flush_input(int fd, input_queue *queue) { + ssize_t count = write(fd, queue->bytes, queue->length); + if (count < 0) return errno == EINTR || errno == EAGAIN ? 0 : errno; + if (count) { + queue->length -= (size_t)count; + memmove(queue->bytes, queue->bytes + count, queue->length); + } + return 0; +} + +static int route_input(pane_input_relay *relay, const unsigned char *bytes, size_t length) { + for (size_t i = 0; i < length; i++) { + unsigned char byte = bytes[i]; + int foreground = relay->command && !relay->command_eof; + int raw = foreground && relay->interactive && relay->interactive(); + if (foreground && !raw && byte == 4) { + relay->command_eof = 1; + continue; + } + if (foreground && !raw && byte == '\r') byte = '\n'; + int error = append_input(foreground ? &relay->command_queue : + &relay->editor_queue, &byte, 1); + if (error) return error; + } + return 0; +} + +static int change_input(pane_input_relay *relay) { + command_input *command = relay->requested_command; + if (relay->request == INPUT_BEGIN) { + if (relay->command) return EBUSY; + // Bytes already forwarded to libedit belong to the next foreground + // reader once its command line has been consumed. Preserve their order. + input_queue *typeahead = calloc(1, sizeof(*typeahead)); + if (!typeahead) return ENOMEM; + int error = drain_input(relay->editor_reader, typeahead); + if (!error) error = append_input(typeahead, + relay->editor_queue.bytes, relay->editor_queue.length); + if (!error) { + relay->editor_queue.length = 0; + relay->command = command; + relay->command_eof = 0; + error = route_input(relay, typeahead->bytes, typeahead->length); + } + free(typeahead); + if (error) return error; + } else if (relay->request == INPUT_END) { + if (relay->command != command) return EINVAL; + close_input_writer(&command->writer); + relay->command_eof = 1; + } else if (relay->request == INPUT_RETIRE) { + if (relay->command != command) return EINVAL; + input_queue *remaining = calloc(1, sizeof(*remaining)); + if (!remaining) return ENOMEM; + // No borrower remains at this point. Unconsumed typeahead goes back to + // the editor before bytes typed after Ctrl-D; it must not be discarded. + int error = drain_input(fileno(command->reader), remaining); + if (!error) error = append_input(remaining, + relay->command_queue.bytes, relay->command_queue.length); + if (!error) error = append_input(remaining, + relay->editor_queue.bytes, relay->editor_queue.length); + if (!error) relay->editor_queue = *remaining; + free(remaining); + if (error) return error; + relay->command_queue.length = 0; + relay->command = NULL; + } + return 0; +} + +static void *relay_input(void *cookie) { + pane_input_relay *relay = cookie; + pthread_mutex_lock(&relay->mutex); + while (!relay->stop && !relay->error) { + if (relay->request) { + relay->request_error = change_input(relay); + relay->request = 0; + relay->request_done = 1; + pthread_cond_broadcast(&relay->changed); + if (relay->request_error) { relay->error = relay->request_error; break; } + } + if (relay->command && (relay->command_eof || relay->input_eof) && + !relay->command_queue.length) + close_input_writer(&relay->command->writer); + if (relay->input_eof && !relay->editor_queue.length) + close_input_writer(&relay->editor_writer); + // Backpressure bounds queued input. Each pipe also has its kernel + // buffer; transition queues have room to drain that existing typeahead. + int can_read = !relay->input_eof && relay->editor_queue.length < 61440 && + relay->command_queue.length < 61440; + struct pollfd fds[4] = { + {.fd = can_read ? relay->socket : -1, .events = POLLIN}, + {.fd = relay->wake[0], .events = POLLIN}, + {.fd = !relay->command && relay->editor_queue.length ? relay->editor_writer : -1, .events = POLLOUT}, + {.fd = relay->command && relay->command_queue.length ? relay->command->writer : -1, + .events = POLLOUT} + }; + pthread_mutex_unlock(&relay->mutex); + int result = poll(fds, 4, -1); + int poll_error = errno; + pthread_mutex_lock(&relay->mutex); + if (result < 0) { + if (poll_error == EINTR) continue; + relay->error = poll_error; + break; + } + if (fds[1].revents) { + unsigned char wake; + (void)read(relay->wake[0], &wake, 1); + continue; // Apply the requested boundary before consuming more input. + } + if (fds[2].revents && relay->editor_queue.length) + relay->error = flush_input(relay->editor_writer, &relay->editor_queue); + if (!relay->error && fds[3].revents && relay->command_queue.length) + relay->error = flush_input(relay->command->writer, &relay->command_queue); + if (!relay->error && fds[0].revents) { + unsigned char bytes[4096]; + ssize_t length = read(relay->socket, bytes, sizeof(bytes)); + if (length < 0) { + if (errno != EINTR && errno != EAGAIN) relay->error = errno; + } else if (!length) { + relay->input_eof = 1; + } else { + relay->error = route_input(relay, bytes, (size_t)length); + } + } + } + close_input_writer(&relay->editor_writer); + if (relay->command) close_input_writer(&relay->command->writer); + relay->running = 0; + pthread_cond_broadcast(&relay->changed); + pthread_mutex_unlock(&relay->mutex); + return NULL; +} + +static int request_input(pane_input_relay *relay, int request, command_input *command) { + pthread_mutex_lock(&relay->mutex); + int error = relay->running ? 0 : relay->error ? relay->error : EPIPE; + if (!error) { + relay->request = request; + relay->requested_command = command; + relay->request_done = 0; + unsigned char wake = 1; + ssize_t count; + do { count = write(relay->wake[1], &wake, 1); } while (count < 0 && errno == EINTR); + if (count != 1) error = errno ? errno : EIO; + while (!error && !relay->request_done && relay->running) + pthread_cond_wait(&relay->changed, &relay->mutex); + if (!error) error = relay->request_done ? relay->request_error : relay->error ? relay->error : EPIPE; + } + pthread_mutex_unlock(&relay->mutex); + return error; +} + +static int stop_input_relay(pane_job *job) { + pane_input_relay *relay = job->input_relay; + if (!relay) return 0; + pthread_mutex_lock(&relay->mutex); + relay->stop = 1; + unsigned char wake = 1; + (void)write(relay->wake[1], &wake, 1); + pthread_mutex_unlock(&relay->mutex); + pthread_join(relay->thread, NULL); + int error = relay->error; + // pthread_cancel can bypass Dash's shell-exception handler. The outer + // runner has already waited for the root tree; retire any abandoned lease + // only after every registered stdin borrower has completed cleanup. + if (relay->command) { + command_input *command = relay->command; + ashell_wait_owned_streams(command->registration); + ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + ios_settty(job->streams[0]); + ashell_unregister_owned_streams(&command->registration); + if (fclose(command->reader) && !error) error = errno; + free(command); + relay->command = NULL; + } + close(relay->socket); + close(relay->editor_reader); + close(relay->wake[0]); + close(relay->wake[1]); + close(relay->editor_events); + pthread_cond_destroy(&relay->changed); + pthread_mutex_destroy(&relay->mutex); + free(relay); + job->input_relay = NULL; + return error; +} + +static int prepare_input_relay(pane_job *job) { + int input[2], wake[2]; + if (pipe(input)) return errno; + if (pipe(wake)) { int error = errno; close(input[0]); close(input[1]); return error; } + FILE *reader = fdopen(input[0], "r"); + if (!reader) { int error = errno; close(input[0]); close(input[1]); close(wake[0]); close(wake[1]); return error; } + pane_input_relay *relay = calloc(1, sizeof(*relay)); + if (!relay) { fclose(reader); close(input[1]); close(wake[0]); close(wake[1]); return ENOMEM; } + relay->socket = dup(fileno(job->streams[0])); + relay->editor_reader = dup(input[0]); + relay->editor_writer = input[1]; + relay->wake[0] = wake[0]; relay->wake[1] = wake[1]; + relay->editor_events = kqueue(); + relay->interactive = dlsym(RTLD_DEFAULT, "storeInteractive"); + int error = relay->socket < 0 || relay->editor_reader < 0 || relay->editor_events < 0 ? errno : 0; + if (!error && setvbuf(reader, NULL, _IONBF, 0)) error = EIO; + int descriptors[] = {relay->socket, input[0], input[1], relay->editor_reader, wake[0], wake[1], relay->editor_events}; + for (unsigned i = 0; !error && i < sizeof(descriptors) / sizeof(descriptors[0]); i++) + if (fcntl(descriptors[i], F_SETFD, FD_CLOEXEC)) error = errno; + if (!error && (fcntl(input[1], F_SETFL, O_NONBLOCK) || + fcntl(input[1], F_SETNOSIGPIPE, 1))) error = errno; + if (!error) { + struct kevent events[2]; + EV_SET(&events[0], input[0], EVFILT_READ, EV_ADD, 0, 0, NULL); + EV_SET(&events[1], 1, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, NULL); + if (kevent(relay->editor_events, events, 2, NULL, 0, NULL)) error = errno; + } + int mutex_ready = 0, condition_ready = 0; + if (!error) { error = pthread_mutex_init(&relay->mutex, NULL); mutex_ready = !error; } + if (!error) { error = pthread_cond_init(&relay->changed, NULL); condition_ready = !error; } + if (!error) { + relay->running = 1; + error = pthread_create(&relay->thread, NULL, relay_input, relay); + } + if (error) { + if (condition_ready) pthread_cond_destroy(&relay->changed); + if (mutex_ready) pthread_mutex_destroy(&relay->mutex); + if (relay->socket >= 0) close(relay->socket); + if (relay->editor_reader >= 0) close(relay->editor_reader); + if (relay->editor_events >= 0) close(relay->editor_events); + fclose(reader); close(input[1]); close(wake[0]); close(wake[1]); free(relay); + return error; + } + fclose(job->streams[0]); + job->streams[0] = reader; + job->input_relay = relay; + return 0; +} + +// Wait on the editor's real input and resize event without changing process +// signal handlers or inserting synthetic keys into the command stream. +// Return 0 for an unrelated reader, 1 for input, 2 for resize, or -errno. +__attribute__((used)) int ashell_pane_wait_editor_input(FILE *input) { + pane_job *job = atomic_load(&foreground_pane); + if (!job || !job->input_relay || input != job->streams[0]) return 0; + struct kevent event; + int count; + do { + count = kevent(job->input_relay->editor_events, NULL, 0, &event, 1, NULL); + } while (count < 0 && errno == EINTR); + if (count < 0) return -errno; + if (event.flags & EV_ERROR) return -(int)event.data; + return event.filter == EVFILT_USER ? 2 : 1; +} + +__attribute__((used)) int ashell_pane_begin_foreground_input(FILE **input, void **token) { + if (!input || !token || *token) return EINVAL; + pane_job *job = atomic_load(&foreground_pane); + if (!job || !job->input_relay || *input != job->streams[0]) return 0; + // Neither a condition wait nor cancellation during allocation may strand + // the relay mutex or an unregistered pipe. The relay owns the lease before + // cancellation is restored, so outer cleanup can recover it. + int cancellation; + int error = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancellation); + if (error) return error; + int descriptors[2]; + if (pipe(descriptors)) { + error = errno; + pthread_setcancelstate(cancellation, NULL); + return error; + } + command_input *command = calloc(1, sizeof(*command)); + if (!command) { + close(descriptors[0]); close(descriptors[1]); + pthread_setcancelstate(cancellation, NULL); + return ENOMEM; + } + command->writer = descriptors[1]; + command->reader = fdopen(descriptors[0], "r"); + command->job = job; + command->relay = job->input_relay; + error = command->reader ? 0 : errno; + if (!error && (fcntl(descriptors[0], F_SETFD, FD_CLOEXEC) || + fcntl(descriptors[1], F_SETFD, FD_CLOEXEC) || + fcntl(descriptors[1], F_SETFL, O_NONBLOCK) || + fcntl(descriptors[1], F_SETNOSIGPIPE, 1))) error = errno; + if (!error && setvbuf(command->reader, NULL, _IONBF, 0)) error = EIO; + if (!error) error = ashell_register_command_input(command->reader, &command->registration); + if (!error) error = request_input(command->relay, INPUT_BEGIN, command); + if (error) { + pthread_mutex_lock(&command->relay->mutex); + if (!command->relay->running && command->relay->command == command) + command->relay->command = NULL; + pthread_mutex_unlock(&command->relay->mutex); + ashell_unregister_owned_streams(&command->registration); + if (command->reader) fclose(command->reader); else close(descriptors[0]); + close(command->writer); free(command); + pthread_setcancelstate(cancellation, NULL); + return error; + } + *input = command->reader; + *token = command; + // Stock tty detection compares command streams against the session streams. + // Keep baseline outputs so explicit redirects remain non-terminal streams. + ios_setStreams(command->reader, job->streams[1], job->streams[2]); + // Stock ios_opentty borrowers must receive this command's input as well. + ios_settty(command->reader); + pthread_setcancelstate(cancellation, NULL); + return 0; +} + +__attribute__((used)) int ashell_pane_end_foreground_input(void *token) { + command_input *command = token; + if (!command) return EINVAL; + int cancellation; + int error = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancellation); + if (error) return error; + error = request_input(command->relay, INPUT_END, command); + // Closing this command's writer unblocks cooked readers without touching + // Dash. Borrow counts include asynchronous children through their cleanup. + ashell_wait_owned_streams(command->registration); + pane_job *job = command->job; + ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + ios_settty(job->streams[0]); + int retired = request_input(command->relay, INPUT_RETIRE, command); + if (!error) error = retired; + pthread_mutex_lock(&command->relay->mutex); + if (!command->relay->running && command->relay->command == command) + command->relay->command = NULL; + pthread_mutex_unlock(&command->relay->mutex); + ashell_unregister_owned_streams(&command->registration); + if (fclose(command->reader) && !error) error = errno; + free(command); + pthread_setcancelstate(cancellation, NULL); + return error; +} + +static void drop_reference(pane_job *job) { + pthread_mutex_lock(&job->mutex); + int destroy = --job->refs == 0; + pthread_mutex_unlock(&job->mutex); + if (!destroy) return; + if (job->peer_control >= 0) close(job->peer_control); + if (job->env) { + for (size_t i = 0; job->env[i]; i++) free(job->env[i]); + free(job->env); + } + free(job->command); + free(job->cwd); + free(job->previous_cwd); + pthread_cond_destroy(&job->ready); + pthread_mutex_destroy(&job->mutex); + free(job); +} + +static int close_streams(pane_job *job) { + int error = stop_input_relay(job); + ashell_unregister_owned_streams(&job->registration); + for (int i = 0; i < 3; i++) { + if (job->streams[i] && fclose(job->streams[i]) && !error) error = errno; + job->streams[i] = NULL; + } + return error; +} + +static int socket_options(int fd) { + int one = 1; + if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one))) return errno; + if (fcntl(fd, F_SETFD, FD_CLOEXEC)) return errno; + return 0; +} + +static void *run_pane(void *cookie) { + pane_job *job = cookie; + @autoreleasepool { + NSLog(@"Shell pane lifecycle: start key=%s cols=%u rows=%u", job->key, job->cols, job->rows); + // This runner is new: no parent session or TLS streams are switched or overwritten. + ios_switchSession(job->key); + ios_setContext(job->key); + ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + ios_settty(job->streams[0]); + thread_stdin = job->streams[0]; + thread_stdout = job->streams[1]; + thread_stderr = job->streams[2]; + thread_context = job->key; + ios_setDirectoryURL([NSURL fileURLWithPath:@(job->cwd) isDirectory:YES]); + // The stock setter has no error return; confirm its actual process directory. + char observed[PATH_MAX]; + int error = 0; + struct stat wanted, actual; + if (!getcwd(observed, sizeof(observed))) error = errno; + else if (stat(job->cwd, &wanted) || stat(observed, &actual)) error = errno; + else if (wanted.st_dev != actual.st_dev || wanted.st_ino != actual.st_ino) error = EACCES; + if (!error) { + ios_setWindowSize((int)job->cols, (int)job->rows, job->key); + pid_t pid = ios_fork(); + // ios_fork allocates a private environment and holds stock pid_mtx until + // command registration. Do not abort between allocation and ios_system. + for (size_t i = 0; job->env && job->env[i]; i++) { + char *equals = strchr(job->env[i], '='); + *equals = 0; + if (ios_setenv_pid(job->env[i], equals + 1, 1, pid)) error = EINVAL; + *equals = '='; + } + pthread_mutex_lock(&job->mutex); + job->initialized = 1; + pthread_cond_signal(&job->ready); + pthread_mutex_unlock(&job->mutex); + NSLog(@"Shell pane lifecycle: ready key=%s pid=%d pty=%d", job->key, pid, job->is_pty); + atomic_store(&foreground_pane, job); + ios_system(job->command); + // ios_system may return before detached children finish when the app sets + // joinMainThread=false. Stock wait understands allocated-but-not-started IDs. + ios_waitpid(pid); + ashell_wait_owned_streams(job->registration); + atomic_store(&foreground_pane, NULL); + job->status = ios_getCommandStatus(); + ios_releaseThreadId(pid); + } + pthread_mutex_lock(&job->mutex); + int stream_error = close_streams(job); + if (!error) error = stream_error; + // Restore the extension process cwd before publishing completion. + ios_setDirectoryURL([NSURL fileURLWithPath:@(job->previous_cwd) isDirectory:YES]); + struct stat before, restored; + if (!getcwd(observed, sizeof(observed))) { + if (!error) error = errno; + } else if (stat(job->previous_cwd, &before) || stat(observed, &restored)) { + if (!error) error = errno; + } else if (before.st_dev != restored.st_dev || before.st_ino != restored.st_ino) { + if (!error) error = EIO; + } + // Stock ios_closeSession removes its dictionary entry, but does not free stock + // session allocations. Do not invent a private layout/free across the framework ABI. + ios_closeSession(job->key); + job->startup_error = job->initialized ? 0 : error; + job->completion_error = error; + job->initialized = 1; + job->done = 1; + NSLog(@"Shell pane lifecycle: exit key=%s status=%d error=%d", job->key, job->status, error); + // Close the retained peer before announcing exit so output EOF is observable. + if (job->peer_control >= 0) close(job->peer_control); + job->peer_control = -1; + atomic_store(&pane_in_flight, 0); + pthread_cond_signal(&job->ready); + pthread_mutex_unlock(&job->mutex); + } + drop_reference(job); + return NULL; +} + +int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, + unsigned rows, const char *const *envp, int *fd_out, void **job_out) { + if (fd_out) *fd_out = -1; + if (job_out) *job_out = NULL; + if (!fd_out || !job_out || !command || !*command || !cwd || cwd[0] != '/' || + !cols || cols > 9999 || !rows || rows > 9999) return EINVAL; + @autoreleasepool { + if (![@(command) length] || ![@(cwd) length]) return EILSEQ; + if (strlen(cwd) >= PATH_MAX) return ENAMETOOLONG; + struct stat directory; + if (stat(cwd, &directory)) return errno; + if (!S_ISDIR(directory.st_mode)) return ENOTDIR; + if (access(cwd, R_OK | X_OK)) return errno; + size_t env_count = 0; + if (envp) for (; envp[env_count]; env_count++) { + const char *equals = strchr(envp[env_count], '='); + if (!equals || equals == envp[env_count]) return EINVAL; + if (![@(envp[env_count]) length]) return EILSEQ; + } + int expected = 0; + if (!atomic_compare_exchange_strong(&pane_in_flight, &expected, 1)) return EBUSY; + int error = ENOMEM, peer = -1; + pane_job *job = calloc(1, sizeof(*job)); + if (!job) { atomic_store(&pane_in_flight, 0); return ENOMEM; } + job->peer_control = -1; + error = pthread_mutex_init(&job->mutex, NULL); + if (error) { free(job); atomic_store(&pane_in_flight, 0); return error; } + error = pthread_cond_init(&job->ready, NULL); + if (error) { + pthread_mutex_destroy(&job->mutex); + free(job); + atomic_store(&pane_in_flight, 0); + return error; + } + job->refs = 1; + job->cols = cols; + job->rows = rows; + snprintf(job->key, sizeof(job->key), "shell-pane-%s", NSUUID.UUID.UUIDString.UTF8String); + job->command = strdup(command); + job->cwd = strdup(cwd); + job->previous_cwd = getcwd(NULL, 0); + job->env = calloc(env_count + 1, sizeof(char *)); + error = ENOMEM; + if (!job->command || !job->cwd || !job->env) goto failed; + if (!job->previous_cwd) { error = errno; goto failed; } + for (size_t i = 0; i < env_count; i++) { + job->env[i] = strdup(envp[i]); + if (!job->env[i]) goto failed; + } + int fds[2]; + int wants_pty = 0; + for (size_t i = 0; i < env_count; i++) + if (!strcmp(envp[i], "ASHELL_IOS_PTY=1")) wants_pty = 1; + if (wants_pty) { + struct winsize size = {.ws_col = (unsigned short)cols, .ws_row = (unsigned short)rows}; + if (openpty(&fds[0], &fds[1], NULL, NULL, &size)) { + error = errno; + NSLog(@"Shell pane: openpty failed errno=%d (%s)", error, strerror(error)); + if (error != EPERM) goto failed; + // Sandboxed devices may deny PTYs. Keep the existing socket transport + // explicit and let Dash print its non-TTY prompt; never claim PTY semantics. + wants_pty = 0; + for (size_t i = 0; i < env_count; i++) + if (!strcmp(job->env[i], "ASHELL_IOS_PTY=1")) + memcpy(job->env[i], "ASHELL_IOS_PTY=0", sizeof("ASHELL_IOS_PTY=0")); + NSLog(@"Shell pane: using socket transport; kernel PTY signals and ioctls unavailable"); + } else job->is_pty = 1; + } + if (!wants_pty && socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) { error = errno; goto failed; } + peer = fds[0]; + int child = fds[1]; + if (job->is_pty) { + struct termios settings; + if (tcgetattr(child, &settings)) { error = errno; close(child); goto failed; } + if (settings.c_cc[VEOF] == _POSIX_VDISABLE) { error = ENOTSUP; close(child); goto failed; } + job->eof_key = settings.c_cc[VEOF]; + // Commands share an application process: never enable kernel process-group signals. + settings.c_lflag &= ~ISIG; + settings.c_iflag |= ICRNL; + settings.c_oflag |= OPOST | ONLCR; + error = tcsetattr(child, TCSANOW, &settings) ? errno : 0; + } else { + error = socket_options(peer); + if (!error) error = socket_options(child); + } + if (error) { close(child); goto failed; } + job->peer_control = dup(peer); + if (job->peer_control < 0) { error = errno; close(child); goto failed; } + error = job->is_pty ? (fcntl(job->peer_control, F_SETFD, FD_CLOEXEC) ? errno : 0) : socket_options(job->peer_control); + if (!error && job->is_pty && fcntl(peer, F_SETFD, FD_CLOEXEC)) error = errno; + if (error) { close(child); goto failed; } + for (int i = 0; i < 3; i++) { + int fd = i == 0 ? child : dup(child); + if (fd < 0) { error = errno; goto failed; } + job->streams[i] = fdopen(fd, i == 0 ? "r" : "w"); + if (!job->streams[i]) { error = errno; close(fd); goto failed; } + if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { error = errno; goto failed; } + /* Match terminal stdout: libedit flushes each completed redraw. */ + int buffering = !job->is_pty && i == 1 ? _IOLBF : _IONBF; + if (setvbuf(job->streams[i], NULL, buffering, 0)) { error = EIO; goto failed; } + } + if (!job->is_pty) error = prepare_input_relay(job); + if (!error) error = ashell_register_owned_streams(job->streams[0], job->streams[1], job->streams[2], &job->registration); + if (error) goto failed; + pthread_attr_t attributes; + error = pthread_attr_init(&attributes); + if (error) goto failed; + error = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); + pthread_t thread; + job->refs = 2; + if (!error) error = pthread_create(&thread, &attributes, run_pane, job); + pthread_attr_destroy(&attributes); + if (error) { job->refs = 1; goto failed; } + pthread_mutex_lock(&job->mutex); + while (!job->initialized) pthread_cond_wait(&job->ready, &job->mutex); + error = job->startup_error; + pthread_mutex_unlock(&job->mutex); + if (error) { close(peer); drop_reference(job); return error; } + *fd_out = peer; + *job_out = job; + return 0; +failed: + close_streams(job); + if (peer >= 0) close(peer); + drop_reference(job); + atomic_store(&pane_in_flight, 0); + return error; + } +} + +int ashell_pane_poll(void *handle, int *status_out) { + if (!handle || !status_out) return -EINVAL; + pane_job *job = handle; + pthread_mutex_lock(&job->mutex); + int result = job->completion_error ? -job->completion_error : job->done; + if (job->done) *status_out = job->status; + pthread_mutex_unlock(&job->mutex); + return result; +} + +int ashell_pane_resize(void *handle, unsigned cols, unsigned rows) { + if (!handle || !cols || cols > 9999 || !rows || rows > 9999) return EINVAL; + pane_job *job = handle; + pthread_mutex_lock(&job->mutex); + int error = job->done ? ESRCH : 0; + NSLog(@"Shell pane lifecycle: resize key=%s cols=%u rows=%u error=%d", job->key, cols, rows, error); + if (!error && job->is_pty) { + struct winsize size = {.ws_col = (unsigned short)cols, .ws_row = (unsigned short)rows}; + if (ioctl(job->peer_control, TIOCSWINSZ, &size)) error = errno; + } + if (!error) { + job->cols = cols; + job->rows = rows; + ios_setWindowSize((int)cols, (int)rows, job->key); + if (job->input_relay) { + struct kevent event; + EV_SET(&event, 1, EVFILT_USER, 0, NOTE_TRIGGER, 0, NULL); + if (kevent(job->input_relay->editor_events, &event, 1, NULL, 0, NULL)) error = errno; + } + } + pthread_mutex_unlock(&job->mutex); + return error; +} + +int ashell_pane_close_stdin(void *handle) { + if (!handle) return EINVAL; + pane_job *job = handle; + pthread_mutex_lock(&job->mutex); + int error = 0; + if (!job->done && !job->input_closed) { + if (job->is_pty) { + // PTYs have no half-close. Request EOF through the terminal's configured key; + // canonical readers and libedit handle it, arbitrary raw readers may not. + // libedit temporarily disables VEOF in raw mode; retain the initial key + // that its line editor binds, rather than injecting _POSIX_VDISABLE. + unsigned char eof[2] = {job->eof_key, job->eof_key}; + size_t sent = 0; + while (sent < sizeof(eof)) { + ssize_t n = write(job->peer_control, eof + sent, sizeof(eof) - sent); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) { error = n < 0 ? errno : EIO; break; } + sent += (size_t)n; + } + } else if (shutdown(job->peer_control, SHUT_WR)) error = errno; + if (!error) job->input_closed = 1; + } + pthread_mutex_unlock(&job->mutex); + return error; +} + +int ashell_pane_interrupt(void *handle) { + if (!handle) return EINVAL; + pane_job *job = handle; + pthread_mutex_lock(&job->mutex); + int error = job->done ? ESRCH : 0; + pthread_t foreground = 0; + struct termios settings; + if (!error && job->is_pty) { + if (tcgetattr(job->peer_control, &settings)) error = errno; + // Raw readers (libedit, Codex, Helix) own their Ctrl-C binding. + else if (!(settings.c_lflag & ICANON)) error = ENOTSUP; + } + if (!error) { + ios_switchSession(job->key); + const char *name = ios_progname(); + if (!name || !strcmp(name, "dash") || !strcmp(name, "sh")) error = ENOTSUP; + else { + int pid = atomic_load(&foreground_command_pid); + foreground = pid > 0 ? ios_getThreadId(pid) : NULL; + if (!foreground || foreground == (pthread_t)-1) error = ESRCH; + } + } + pthread_mutex_unlock(&job->mutex); + if (error) return error; + // Never cancel a shell waiter: cancellation of pthread_cond_wait can leave + // the stock completion mutex locked. Raw TUIs already use the ETX path. + return pthread_equal(foreground, pthread_self()) ? ESRCH : pthread_cancel(foreground); +} + +int ashell_pane_cancel(void *handle) { + if (!handle) return EINVAL; + pane_job *job = handle; + pthread_mutex_lock(&job->mutex); + int error = job->done ? ESRCH : ENOTSUP; + pthread_mutex_unlock(&job->mutex); + return error; +} + +void ashell_pane_release(void *handle) { + if (!handle) return; + ashell_pane_close_stdin(handle); + pane_job *job = handle; + pthread_mutex_lock(&job->mutex); + NSLog(@"Shell pane lifecycle: release key=%s done=%d", job->key, job->done); + // Do not keep a hidden reader alive after the consumer closes its own fd: + // abandoned output must reach EPIPE, rather than filling an unread socket forever. + if (job->peer_control >= 0) close(job->peer_control); + job->peer_control = -1; + pthread_mutex_unlock(&job->mutex); + drop_reference(handle); +} diff --git a/ShellWorkers/PaneWire.h b/ShellWorkers/PaneWire.h new file mode 100644 index 00000000..a1b80a9c --- /dev/null +++ b/ShellWorkers/PaneWire.h @@ -0,0 +1,15 @@ +#import + +// One connection owns one real process and one existing native pane handle. +@protocol AShellPaneWire +- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int, NSFileHandle *, int))reply; +- (void)poll:(void (^)(int, int))reply; +- (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply; +- (void)closeInput:(void (^)(int))reply; +- (void)interrupt:(void (^)(int))reply; +- (void)releasePane; +// The worker exits instead of replying; synchronous callers observe XPC loss. +- (void)terminate:(void (^)(void))reply; +@end + +NSObject *ashell_worker_service(void); diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m new file mode 100644 index 00000000..09929eb1 --- /dev/null +++ b/ShellWorkers/RemotePane.m @@ -0,0 +1,175 @@ +#import "PaneWire.h" +#include "NativePane.h" +#include +#include +#include +#include +#include + +extern void ashell_extension_connect(void (^)(NSXPCConnection *, NSError *)); +extern void ashell_extension_disconnect(NSXPCConnection *); + +static void log_host_library(const char *phase) { + int saved = errno; + NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"]; + DIR *directory = opendir(path.fileSystemRepresentation); + int error = directory ? 0 : errno; + if (directory && closedir(directory)) error = errno; + NSLog(@"Shell host Library capability: phase=%s path=%@ read_error=%d", phase, path, error); + errno = saved; +} + +@interface RemotePane : NSObject +@property(nonatomic, strong) NSXPCConnection *connection; +@property(nonatomic, strong) id proxy; +@property(atomic) BOOL interrupted; +@property(nonatomic, strong) NSMutableArray *directories; +@property(nonatomic, copy) NSString *probeDirectory; +@end +@implementation RemotePane +- (void)dealloc { + // Only remove our empty disposable directory, never a project tree. + if (_probeDirectory) rmdir(_probeDirectory.fileSystemRepresentation); + log_host_library("before_scope_release"); + for (NSURL *url in _directories) { + [url stopAccessingSecurityScopedResource]; + NSLog(@"Shell host directory scope: phase=release url=%@", url.path); + } + log_host_library("after_scope_release"); +} +@end + +int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { + if (fd_out) *fd_out = -1; + if (job_out) *job_out = NULL; + if (!command || !cwd || !fd_out || !job_out || !cols || !rows) return EINVAL; + if (NSThread.isMainThread) return EDEADLK; + @autoreleasepool { + NSString *home = NSHomeDirectory(); + for (size_t i = 0; envp && envp[i]; i++) + if (!strncmp(envp[i], "HOME=", 5)) home = @(envp[i] + 5); + RemotePane *pane = [RemotePane new]; + pane.directories = [NSMutableArray array]; + NSURL *homeURL = [NSURL fileURLWithPath:home isDirectory:YES]; + NSURL *documentsURL = [homeURL URLByAppendingPathComponent:@"Documents" isDirectory:YES]; + NSURL *cwdURL = [NSURL fileURLWithPath:@(cwd) isDirectory:YES]; + log_host_library("before_scope_acquire"); + NSString *container = NSHomeDirectory().stringByResolvingSymlinksInPath; + NSString *containerPrefix = [container stringByAppendingString:@"/"]; + for (NSURL *url in @[homeURL, documentsURL, cwdURL]) { + NSString *path = url.path.stringByResolvingSymlinksInPath; + // The host's own container needs no dynamic grant. Only external + // bookmarked folders belong to this pane's scope lifetime. + BOOL owned = [path isEqualToString:container] || [path hasPrefix:containerPrefix]; + BOOL acquired = !owned && [url startAccessingSecurityScopedResource]; + if (acquired) [pane.directories addObject:url]; + NSLog(@"Shell host directory scope: phase=acquire url=%@ own_container=%d acquired=%d", path, owned, acquired); + } + log_host_library("after_scope_acquire"); + NSError *bookmarkFailure = nil; + // Default bookmarks carry Foundation's implicit ephemeral sandbox scope. + // A pathname alone grants no access to the containing app's private files. + NSData *cwdBookmark = [cwdURL + bookmarkDataWithOptions:0 includingResourceValuesForKeys:nil relativeToURL:nil error:&bookmarkFailure]; + NSData *homeBookmark = cwdBookmark ? [homeURL + bookmarkDataWithOptions:0 includingResourceValuesForKeys:nil relativeToURL:nil error:&bookmarkFailure] : nil; + NSData *documentsBookmark = homeBookmark ? [documentsURL + bookmarkDataWithOptions:0 includingResourceValuesForKeys:nil relativeToURL:nil error:&bookmarkFailure] : nil; + if (!cwdBookmark || !homeBookmark || !documentsBookmark) { + NSLog(@"Shell pane directory bookmark failed: %@", bookmarkFailure); + return [bookmarkFailure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)bookmarkFailure.code : EIO; + } + // A real create/read/unlink in this host-owned disposable directory proves + // the worker capability; bookmark resolution or access(W_OK) alone does not. + NSString *template = [documentsURL.path stringByAppendingPathComponent:@".ashell-worker-access.XXXXXX"]; + char *probe = strdup(template.fileSystemRepresentation); + if (!probe) return ENOMEM; + if (!mkdtemp(probe)) { int code = errno; free(probe); return code; } + pane.probeDirectory = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:probe length:strlen(probe)]; + free(probe); + NSTimeInterval started = NSProcessInfo.processInfo.systemUptime; + dispatch_semaphore_t ready = dispatch_semaphore_create(0); + __block int error = 0; + ashell_extension_connect(^(NSXPCConnection *connection, NSError *failure) { + pane.connection = connection; + // ExtensionFoundation and Cocoa error numbers are not POSIX errno. + // In particular, framework code 1 must not masquerade as EPERM. + error = failure ? ([failure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)failure.code : EIO) : 0; + if (failure) NSLog(@"Shell extension launch failed: %@", failure); + dispatch_semaphore_signal(ready); + }); + dispatch_semaphore_wait(ready, DISPATCH_TIME_FOREVER); + if (error) return error; + __weak RemotePane *weak = pane; + pane.connection.interruptionHandler = ^{ weak.interrupted = YES; }; + pane.connection.invalidationHandler = ^{ weak.interrupted = YES; }; + pane.connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(AShellPaneWire)]; + [pane.connection resume]; + pane.proxy = [pane.connection synchronousRemoteObjectProxyWithErrorHandler:^(NSError *failure) { error = EPIPE; }]; + NSMutableArray *env = [NSMutableArray array]; + for (size_t i = 0; envp && envp[i]; i++) [env addObject:@(envp[i])]; + __block int fd = -1; + [pane.proxy spawn:@(command) cwd:cwdBookmark home:homeBookmark documents:documentsBookmark probe:pane.probeDirectory env:env cols:cols rows:rows reply:^(int code, NSFileHandle *handle, int pid) { + error = code; + if (!code && !handle) error = EPROTO; + if (!error) { + fd = dup(handle.fileDescriptor); + if (fd < 0) error = errno; + else if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { error = errno; close(fd); fd = -1; } + } + NSLog(@"Shell extension spawn: real_pid=%d error=%d startup_ms=%.3f", pid, error, (NSProcessInfo.processInfo.systemUptime - started) * 1000); + }]; + if (rmdir(pane.probeDirectory.fileSystemRepresentation) == 0) pane.probeDirectory = nil; + if (!error && fd < 0) error = EPROTO; + if (error) { ashell_extension_disconnect(pane.connection); return error; } + *fd_out = fd; + *job_out = (__bridge_retained void *)pane; + return 0; + } +} +int ashell_pane_poll(void *job, int *status_out) { + RemotePane *pane = (__bridge RemotePane *)job; + if (!pane || !status_out) return -EINVAL; + // 137 is this backend's lost-worker status, not a recovered waitpid status. + if (pane.interrupted) { *status_out = 137; return 1; } + __block int result = -EPIPE; + [pane.proxy poll:^(int value, int status) { result = value; *status_out = status; }]; + if (result == -EPIPE) { pane.interrupted = YES; *status_out = 137; return 1; } + return result; +} +int ashell_pane_resize(void *job, unsigned cols, unsigned rows) { + RemotePane *pane = (__bridge RemotePane *)job; + if (!pane || pane.interrupted) return ESRCH; + __block int result = EPIPE; + [pane.proxy resize:cols rows:rows reply:^(int error) { result = error; }]; + return result; +} +int ashell_pane_close_stdin(void *job) { + RemotePane *pane = (__bridge RemotePane *)job; + if (!pane || pane.interrupted) return ESRCH; + __block int result = EPIPE; + [pane.proxy closeInput:^(int error) { result = error; }]; + return result; +} +int ashell_pane_interrupt(void *job) { + RemotePane *pane = (__bridge RemotePane *)job; + if (!pane || pane.interrupted) return ESRCH; + __block int result = EPIPE; + [pane.proxy interrupt:^(int error) { result = error; }]; + return result; +} +int ashell_pane_cancel(void *job) { + RemotePane *pane = (__bridge RemotePane *)job; + if (!pane) return EINVAL; + pane.interrupted = YES; + [pane.proxy terminate:^{}]; + ashell_extension_disconnect(pane.connection); + return 0; +} +void ashell_pane_release(void *job) { + if (!job) return; + RemotePane *pane = (__bridge_transfer RemotePane *)job; + [pane.proxy releasePane]; + [pane.proxy terminate:^{}]; + ashell_extension_disconnect(pane.connection); +} diff --git a/ShellWorkers/Worker.m b/ShellWorkers/Worker.m new file mode 100644 index 00000000..e215311c --- /dev/null +++ b/ShellWorkers/Worker.m @@ -0,0 +1,178 @@ +#import "PaneWire.h" +#import "ios_system/ios_system.h" +#include "NativePane.h" +#include +#include +#include +#include +#include +#include +#include + +// ios_system discovers these stock host callbacks with dlsym. Each extension +// owns one shell; its socket already carries input directly to the command. +static atomic_bool interactive_input; +__attribute__((used)) void startInteractive(void) { atomic_store(&interactive_input, true); } +__attribute__((used)) void stopInteractive(void) { atomic_store(&interactive_input, false); } +__attribute__((used)) int storeInteractive(void) { return atomic_load(&interactive_input); } + +// The stock host clear command calls its UIKit delegate. Workers clear through +// the terminal stream, just like an external terminal command. +__attribute__((used)) int clear(int argc, char **argv) { + if (!thread_stdout) return 1; + return fputs("\033[H\033[2J", thread_stdout) == EOF || fflush(thread_stdout) == EOF ? 1 : 0; +} + +static int check_directory(NSURL *url) { + DIR *directory = opendir(url.fileSystemRepresentation); + if (!directory) return errno; + return closedir(directory) == 0 ? 0 : errno; +} + +static int check_documents_write(NSURL *documents, NSString *probe) { + NSString *parent = probe.stringByDeletingLastPathComponent.stringByResolvingSymlinksInPath; + if (![parent isEqualToString:documents.path.stringByResolvingSymlinksInPath] || + ![probe.lastPathComponent hasPrefix:@".ashell-worker-access."]) return EINVAL; + int directory = open(probe.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (directory < 0) return errno; + int fd = openat(directory, "capability", O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd < 0) { int code = errno; close(directory); return code; } + const char expected = 'H'; + char observed = 0; + int code = 0; + if (write(fd, &expected, 1) != 1) code = errno ? errno : EIO; + else if (lseek(fd, 0, SEEK_SET) < 0) code = errno; + else if (read(fd, &observed, 1) != 1) code = errno ? errno : EIO; + else if (observed != expected) code = EIO; + if (close(fd) && !code) code = errno; + if (unlinkat(directory, "capability", 0) && !code) code = errno; + if (close(directory) && !code) code = errno; + return code; +} + +@interface PaneService : NSObject +@end + +@implementation PaneService { + void *_pane; + NSMutableArray *_directories; +} +- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int, NSFileHandle *, int))reply { + if (_pane) { reply(EBUSY, nil, getpid()); return; } + if (!cwd || !home || !documents || !probe) { reply(EINVAL, nil, getpid()); return; } + // Resolve the host's ephemeral grants explicitly and retain them for this + // pane, including HOME for shared command configuration and authentication. + _directories = [NSMutableArray array]; + NSURL *directory = nil; + NSURL *documentsURL = nil; + NSMutableArray *resolved = [NSMutableArray array]; + unsigned index = 0; + NSLog(@"Shell worker sandbox: real_pid=%d own_home=%@", getpid(), NSHomeDirectory()); + for (NSData *bookmark in @[home, documents, cwd]) { + NSError *failure = nil; + BOOL stale = NO; + NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark + options:NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutImplicitStartAccessing + relativeToURL:nil bookmarkDataIsStale:&stale error:&failure]; + if (!url) { + NSLog(@"Shell worker directory bookmark failed: %@", failure); + [self releasePane]; + reply([failure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)failure.code : EIO, nil, getpid()); + return; + } + BOOL scoped = [url startAccessingSecurityScopedResource]; + if (scoped) [_directories addObject:url]; + NSLog(@"Shell worker directory: index=%u url=%@ stale=%d scoped=%d", index, url.path, stale, scoped); + [resolved addObject:url]; + if (index == 1) documentsURL = url; + index++; + directory = url; + } + int readError = 0; + for (NSURL *url in resolved) { + int code = check_directory(url); + NSLog(@"Shell worker directory capability: url=%@ read_error=%d", url.path, code); + if (code && !readError) readError = code; + } + if (readError) { [self releasePane]; reply(readError, nil, getpid()); return; } + int capabilityError = check_documents_write(documentsURL, probe); + NSLog(@"Shell worker Documents capability: real_pid=%d read_write_error=%d", getpid(), capabilityError); + if (capabilityError) { [self releasePane]; reply(capabilityError, nil, getpid()); return; } + // ios_system globals are private to this extension. The adapter keeps its + // original dedicated pthread and stream ownership/cleanup barrier. + NSString *temporaryDirectory = NSTemporaryDirectory(); + if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, getpid()); return; } + // The host's directory bookmark does not grant its tmp directory. Keep the + // extension's stock Foundation/libc temp domain in both environment views. + NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 1]; + for (NSString *value in env) + if (![value hasPrefix:@"TMPDIR="]) [environment addObject:value]; + [environment addObject:[@"TMPDIR=" stringByAppendingString:temporaryDirectory]]; + env = environment; + initializeEnvironment(); + replaceCommand(@"clear", @"clear", true); + // This process owns exactly one shell. Native Rust clients enumerate libc's + // environment as well as ios_system's forked command environment. + for (NSString *value in env) { + NSRange separator = [value rangeOfString:@"="]; + if (separator.location == NSNotFound || separator.location == 0) { [self releasePane]; reply(EINVAL, nil, getpid()); return; } + if (setenv([value substringToIndex:separator.location].UTF8String, + [value substringFromIndex:separator.location + 1].UTF8String, 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + } + // Match stock SceneDelegate before libedit decodes Unicode or measures it. + if (setenv("LC_CTYPE", "UTF-8", 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + const char *locale = setlocale(LC_CTYPE, "UTF-8"); + if (!locale) { [self releasePane]; reply(EINVAL, nil, getpid()); return; } + NSLog(@"Shell worker locale: real_pid=%d ctype=%s", getpid(), locale); + // The physical device has no kernel tty. Use the same socket-backed route + // on Simulator so its acceptance cannot pass through a desktop-only PTY. + if (setenv("ASHELL_IOS_PTY", "0", 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + const char **values = calloc(env.count + 4, sizeof(char *)); + if (!values) { [self releasePane]; reply(ENOMEM, nil, getpid()); return; } + for (NSUInteger i = 0; i < env.count; i++) + values[i] = [env[i] hasPrefix:@"ASHELL_IOS_PTY="] ? "ASHELL_IOS_PTY=0" : + [env[i] hasPrefix:@"LC_CTYPE="] ? "LC_CTYPE=UTF-8" : env[i].UTF8String; + NSString *identity = [NSString stringWithFormat:@"ASHELL_WORKER_PID=%d", getpid()]; + values[env.count] = identity.UTF8String; + values[env.count + 1] = "LC_CTYPE=UTF-8"; + values[env.count + 2] = "ASHELL_IOS_SOCKET_INPUT=1"; + int fd = -1; + int error = ashell_pane_spawn(command.UTF8String, directory.path.UTF8String, cols, rows, values, &fd, &_pane); + free(values); + if (error) [self releasePane]; + NSFileHandle *handle = error ? nil : [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES]; + reply(error, handle, getpid()); +} +- (void)poll:(void (^)(int, int))reply { + int status = 0; + int result = _pane ? ashell_pane_poll(_pane, &status) : -ESRCH; + reply(result, status); +} +- (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply { + reply(_pane ? ashell_pane_resize(_pane, cols, rows) : ESRCH); +} +- (void)closeInput:(void (^)(int))reply { reply(_pane ? ashell_pane_close_stdin(_pane) : ESRCH); } +- (void)interrupt:(void (^)(int))reply { + // Stream-backed TUIs have no kernel termios state. ENOTSUP sends the ETX + // byte through the existing host input path instead of cancelling a thread. + if (atomic_load(&interactive_input)) { reply(ENOTSUP); return; } + reply(_pane ? ashell_pane_interrupt(_pane) : ESRCH); +} +- (void)releasePane { + if (_pane) ashell_pane_release(_pane); + _pane = NULL; + for (NSURL *directory in _directories) [directory stopAccessingSecurityScopedResource]; + _directories = nil; +} +- (void)terminate:(void (^)(void))reply { + // AppExtensionProcess.invalidate releases the host's assertion but permits + // process reuse. End this dedicated worker even if its command ignores EOF. + // ios_system interposes exit/_exit; SIGKILL reaches the OS process directly. + // Do not acknowledge before death: the host's synchronous XPC call returns + // through its error handler only after the old worker can no longer run. + kill(getpid(), SIGKILL); +} +- (void)dealloc { [self releasePane]; } +@end + +NSObject *ashell_worker_service(void) { return [PaneService new]; } diff --git a/ShellWorkers/Worker.swift b/ShellWorkers/Worker.swift new file mode 100644 index 00000000..7b40748d --- /dev/null +++ b/ShellWorkers/Worker.swift @@ -0,0 +1,28 @@ +import ExtensionFoundation +import Foundation + +// Every extension identity compiles this same source and native pane adapter. +@main +final class PaneExtension: AppExtension { + required init() {} + + @AppExtensionPoint.Bind + var extensionPoint: AppExtensionPoint { + AppExtensionPoint.Identifier(host: "@ASHELL_WORKER_HOST_IDENTIFIER@", name: "ShellWorker") + } + + var configuration: some AppExtensionConfiguration { PaneConfiguration() } +} + +struct PaneConfiguration: AppExtensionConfiguration { + func accept(connection: NSXPCConnection) -> Bool { + connection.exportedInterface = NSXPCInterface(with: AShellPaneWire.self) + guard let service = ashell_worker_service() else { return false } + connection.exportedObject = service + // ios_system interposes exit/_exit as pthread_exit, which is invalid on + // this dispatch callback. Process lifetime belongs to ExtensionFoundation. + connection.invalidationHandler = { service.releasePane() } + connection.resume() + return true + } +} diff --git a/ShellWorkers/Worker.xcconfig b/ShellWorkers/Worker.xcconfig new file mode 100644 index 00000000..fda0cec8 --- /dev/null +++ b/ShellWorkers/Worker.xcconfig @@ -0,0 +1,22 @@ +// Dedicated Generic Non-UI worker targets share the stock host's command libraries. +SDKROOT = iphoneos +SUPPORTED_PLATFORMS = iphoneos iphonesimulator +IPHONEOS_DEPLOYMENT_TARGET = 26.0 +SWIFT_VERSION = 6.0 +SWIFT_STRICT_CONCURRENCY = complete +SWIFT_DEFAULT_ACTOR_ISOLATION = nonisolated +SWIFT_APPROACHABLE_CONCURRENCY = YES +CLANG_ENABLE_OBJC_ARC = YES +APPLICATION_EXTENSION_API_ONLY = YES +GENERATE_INFOPLIST_FILE = YES +EX_ENABLE_EXTENSION_POINT_GENERATION = YES +ASHELL_WORKER_HOST_IDENTIFIER = $(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini +SWIFT_OBJC_BRIDGING_HEADER = ShellWorkers/PaneWire.h +HEADER_SEARCH_PATHS = $(inherited) $(SRCROOT)/ShellWorkers +FRAMEWORK_SEARCH_PATHS = $(inherited) $(BUILT_PRODUCTS_DIR) +OTHER_LDFLAGS = $(inherited) -framework ios_system -framework Foundation -framework UIKit +LD_RUNPATH_SEARCH_PATHS = @executable_path/../../Frameworks @executable_path/Frameworks +SKIP_INSTALL = YES +CURRENT_PROJECT_VERSION = 589 +MARKETING_VERSION = 2.2.3 +CODE_SIGN_STYLE = Automatic diff --git a/ShellWorkers/resources.sh b/ShellWorkers/resources.sh new file mode 100644 index 00000000..6ddaa3b7 --- /dev/null +++ b/ShellWorkers/resources.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Reuse the host catalogue; workers locate shared libraries through their rpaths. +set -euo pipefail +source_dictionary="$SRCROOT/Resources_mini/commandDictionary.plist" +resources="$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH" +mkdir -p "$resources/bin" "$DERIVED_FILE_DIR" +# ExtensionFoundation requires a literal StaticString for its host binding. +/usr/bin/sed "s|@ASHELL_WORKER_HOST_IDENTIFIER@|$ASHELL_WORKER_HOST_IDENTIFIER|g" "$SRCROOT/ShellWorkers/Worker.swift" >"$DERIVED_FILE_DIR/Worker.swift" +/usr/bin/sed -E 's|([^<]*\.framework/[^<]*)|@rpath/\1|' "$source_dictionary" >"$resources/commandDictionary.plist" +# Dash discovers a command through PATH before asking ios_system to dispatch it. +/usr/bin/sed -n 's|.*\([^<]*\).*|\1|p' "$source_dictionary" | while IFS= read -r command; do + touch "$resources/bin/$command" + chmod 755 "$resources/bin/$command" +done diff --git a/a-Shell-mini-Info.plist b/a-Shell-mini-Info.plist index 664ab9df..b90289e6 100644 --- a/a-Shell-mini-Info.plist +++ b/a-Shell-mini-Info.plist @@ -212,5 +212,7 @@ AppGroupIdentifier group.$(APP_GROUP_PREFIX:default=AsheKube).a-Shell + ShellWorkerCount + 10 diff --git a/a-Shell.xcodeproj/project.pbxproj b/a-Shell.xcodeproj/project.pbxproj index de410812..8055ff92 100644 --- a/a-Shell.xcodeproj/project.pbxproj +++ b/a-Shell.xcodeproj/project.pbxproj @@ -982,6 +982,264 @@ 6BD9536F2BFFCC6400C2508F /* ExecuteCommandIntentHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BD9536D2BFFCC6400C2508F /* ExecuteCommandIntentHandler.swift */; }; 6BD953702BFFCC6400C2508F /* ExecuteCommandIntentHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BD9536D2BFFCC6400C2508F /* ExecuteCommandIntentHandler.swift */; }; 89483CE425CC48B2008EF012 /* ios_system.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = 228E13F225C95F2D0065D825 /* ios_system.xcframework */; }; + 7A025EB47CCEBDAA7E49CB3E = { + isa = "PBXBuildFile"; + fileRef = "D847238C57D48CADF264887A"; + }; + C608987E0D35D7D8C92CF091 = { + isa = "PBXBuildFile"; + fileRef = "11189940A2AF26A6542BDEAF"; + }; + A1C0F473B5B02A405758E45F = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 01254C24560A350B59662101 = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + 948BA9E69DBEE6BFD829414C = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + D2F30C91685F9DC284616312 = { + isa = "PBXBuildFile"; + fileRef = "3BA328FE78F02ED540EFB7DA"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 59144CB4855198131ED069B3 = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 188B14A9B070A4E709C1A447 = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + C27C502276A1F0301FBC2CBA = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + 7068DDDA75BCEA8A404C09AD = { + isa = "PBXBuildFile"; + fileRef = "295B641B253C35B85CBD0100"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 2A45EE5BE77CD575DD0ADEBE = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + DB9A503B8C8690B9298B35E3 = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + 8F4F306A0A771AF4667582BA = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + FD33E045D3FF5D175364CB7C = { + isa = "PBXBuildFile"; + fileRef = "1D81B2E2F18AE7821D05A7AD"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + F2D20BDE70DB7C92C03509DE = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 70E66D31CD0F42D23FBC3EFC = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + A85A41CEA814190D8404E105 = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + 27937DD7D9B079E79382E010 = { + isa = "PBXBuildFile"; + fileRef = "671E1D67938C7F8A1BF10D84"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + F1632FC1E103CFB4010F7006 = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 6C8E5746297C24B1080C03AF = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + 7407B0C9B5E07D5492D98053 = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + CDECC5E5A6CB9CC531134296 = { + isa = "PBXBuildFile"; + fileRef = "366758A2DEC0386D139D2234"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 8299DBD0E93022AAEACE5F54 = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + B70CFF8BCD5A858CCB5D600B = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + 084FF2541A50122906582CAC = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + BD336245D81BD967822E8805 = { + isa = "PBXBuildFile"; + fileRef = "A8EA5B4748F0CC00F65BA1A1"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + E357BFCCA00A4DD6EF1D0235 = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 60BA73F3EE45C345CD0C593D = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + 755E22C57BB293CDAD64CB41 = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + 632684F10ED929FB4713B2AE = { + isa = "PBXBuildFile"; + fileRef = "A490F7519B2E1597438D0853"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 556FE5F2A7285723350E4CAC = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 1C7B8B3BAEF7289AACBD231D = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + C3EEB3DED5B57200DA36F34E = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + B20620C6A9ADEC432BF25194 = { + isa = "PBXBuildFile"; + fileRef = "5A7F8536C04A2BAC1834B3E7"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 359DDEBBC7AB6E4D48032723 = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + E2CFAA905BF589905A69D32F = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + 4096B185162EAE2C4738E1C1 = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + 4E381ABD8DEE9DA436598879 = { + isa = "PBXBuildFile"; + fileRef = "1A10CFCE432C459F3DD1051D"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 5A652AAB3F21AD3EEE1DC9B1 = { + isa = "PBXBuildFile"; + fileRef = "070AE9F6D58955EE5B3B2FB9"; + }; + 72B403FFF4DA5BA1CEDD5717 = { + isa = "PBXBuildFile"; + fileRef = "BA7967007CF5D5AF7BEE03CE"; + }; + C14B2CCCCE38CFD39751A8F3 = { + isa = "PBXBuildFile"; + fileRef = "CBB6E958A8AF3B33B29AA4A8"; + }; + 96976D843556F3E024DE3B2F = { + isa = "PBXBuildFile"; + fileRef = "93314A863CABFBA3A5626312"; + settings = { + ATTRIBUTES = ( + "RemoveHeadersOnCopy", + ); + }; + }; + 1277856148B9DF5BCFB73A45 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 0673335401F0E6294B1D6A65 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 92590DF487A4D5B48CEE3C36 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 539578FA38E5117D4FFA6F13 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 210223C3B93B2D495C96B792 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 4C9CA710D4734D323992A80C = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 3AABA6ADD41BDE6C2C6BEC6E = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 5588CB35CBA255F519ECBB71 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 09D5DF2DB0BAEEB73DCFED25 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; + 6B4BFFDBD16619E32E8DA990 = { + isa = "PBXBuildFile"; + fileRef = "228E13F225C95F2D0065D825"; + }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -1899,6 +2157,26 @@ name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; + 612A319DA4E81CC5CF4B62F3 = { + isa = "PBXCopyFilesBuildPhase"; + buildActionMask = 2147483647; + dstPath = "$(EXTENSIONS_FOLDER_PATH)"; + dstSubfolderSpec = 16; + files = ( + "D2F30C91685F9DC284616312", + "7068DDDA75BCEA8A404C09AD", + "FD33E045D3FF5D175364CB7C", + "27937DD7D9B079E79382E010", + "CDECC5E5A6CB9CC531134296", + "BD336245D81BD967822E8805", + "632684F10ED929FB4713B2AE", + "B20620C6A9ADEC432BF25194", + "4E381ABD8DEE9DA436598879", + "96976D843556F3E024DE3B2F", + ); + name = "Embed Shell Workers"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -2751,6 +3029,106 @@ 8916088E2713056900CED1C9 /* KBWebViewBase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KBWebViewBase.m; sourceTree = ""; }; 8916088F2713056A00CED1C9 /* KBWebViewBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KBWebViewBase.h; sourceTree = ""; }; 898384A83061A39800A1E18D /* Build.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Build.xcconfig; sourceTree = ""; }; + D847238C57D48CADF264887A = { + isa = "PBXFileReference"; + path = "ShellWorkers/Host.swift"; + sourceTree = "SOURCE_ROOT"; + }; + 11189940A2AF26A6542BDEAF = { + isa = "PBXFileReference"; + path = "ShellWorkers/RemotePane.m"; + sourceTree = "SOURCE_ROOT"; + }; + 070AE9F6D58955EE5B3B2FB9 = { + isa = "PBXFileReference"; + path = "$(DERIVED_FILE_DIR)/Worker.swift"; + sourceTree = ""; + }; + BA7967007CF5D5AF7BEE03CE = { + isa = "PBXFileReference"; + path = "ShellWorkers/Worker.m"; + sourceTree = "SOURCE_ROOT"; + }; + CBB6E958A8AF3B33B29AA4A8 = { + isa = "PBXFileReference"; + path = "ShellWorkers/NativePane.m"; + sourceTree = "SOURCE_ROOT"; + }; + EBFE9D103C0EF60A16FFF4FE = { + isa = "PBXFileReference"; + path = "ShellWorkers/NativePane.h"; + sourceTree = "SOURCE_ROOT"; + }; + 829DEA185012AF6B325E7867 = { + isa = "PBXFileReference"; + path = "ShellWorkers/PaneWire.h"; + sourceTree = "SOURCE_ROOT"; + }; + 0893D186728BD261366E4BD1 = { + isa = "PBXFileReference"; + path = "ShellWorkers/Worker.xcconfig"; + sourceTree = "SOURCE_ROOT"; + }; + 3BA328FE78F02ED540EFB7DA = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerA.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 295B641B253C35B85CBD0100 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerB.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 1D81B2E2F18AE7821D05A7AD = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerC.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 671E1D67938C7F8A1BF10D84 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerD.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 366758A2DEC0386D139D2234 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerE.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + A8EA5B4748F0CC00F65BA1A1 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerF.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + A490F7519B2E1597438D0853 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerG.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 5A7F8536C04A2BAC1834B3E7 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerH.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 1A10CFCE432C459F3DD1051D = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerI.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; + 93314A863CABFBA3A5626312 = { + isa = "PBXFileReference"; + explicitFileType = "wrapper.app-extension"; + path = "ShellWorkerJ.appex"; + sourceTree = "BUILT_PRODUCTS_DIR"; + }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -2816,6 +3194,86 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 14FF53A4F006E7098AEAAE7F = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "1277856148B9DF5BCFB73A45", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DEAB4E94790E3EA7168A48C3 = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "0673335401F0E6294B1D6A65", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 258FF1E0CF03820F66E545A5 = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "92590DF487A4D5B48CEE3C36", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 82F519E40E8A8147E4355208 = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "539578FA38E5117D4FFA6F13", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B845E8A798AC3E84D1E78A6A = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "210223C3B93B2D495C96B792", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 546F48346B8E1E84B6C5218F = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "4C9CA710D4734D323992A80C", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3BAA79E324EBC4898A0D14A6 = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "3AABA6ADD41BDE6C2C6BEC6E", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5A1CAE50D727AC931A1AC17A = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "5588CB35CBA255F519ECBB71", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FCA3F3734E17EAA67DAFC01F = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "09D5DF2DB0BAEEB73DCFED25", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0FCC490857271C3EA8FD0560 = { + isa = "PBXFrameworksBuildPhase"; + buildActionMask = 2147483647; + files = ( + "6B4BFFDBD16619E32E8DA990", + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -3950,6 +4408,7 @@ isa = PBXNativeTarget; buildConfigurationList = 229D25A3257931E4004A78AC /* Build configuration list for PBXNativeTarget "a-Shell-mini" */; buildPhases = ( + 612A319DA4E81CC5CF4B62F3, 229D2476257931E4004A78AC /* Sources */, 229D2486257931E4004A78AC /* Frameworks */, 229D2488257931E4004A78AC /* Resources */, @@ -3959,6 +4418,16 @@ buildRules = ( ); dependencies = ( + E119072ED69DB93517DB130D, + AD01960A41E12D8546D60344, + 31A01BF362BE8594C88A7461, + 42442DC659794242C4C4F078, + 0AAC31F15A0DCCDD78983016, + A635836C211C3AB5C85C00A7, + 26F687795555A5D88B96304D, + BB6767147D3C4FEA4C3C952B, + C07B3F85C9AAEB628033EA61, + 88F36AC8C5832103CAA7195E, 22178F0B257BBBA6008EB2B4 /* PBXTargetDependency */, 22178F0E257BBBA6008EB2B4 /* PBXTargetDependency */, ); @@ -4006,6 +4475,186 @@ productReference = 22AD8721246EBFFB00F415DE /* a-Shell-IntentsUI.appex */; productType = "com.apple.product-type.app-extension"; }; + B80CAEC73DAE28A7664A2FE7 = { + isa = "PBXNativeTarget"; + buildConfigurationList = "AF05FF73FF3462482114110C"; + buildPhases = ( + 14FF53A4F006E7098AEAAE7F, + B6DFC70EFFFF8DF6433E72CB, + "718D17729DFE061A0416ECA4", + "EC1A1AC5948AC9AA36F4B087", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerA"; + productName = "ShellWorkerA"; + productReference = "3BA328FE78F02ED540EFB7DA"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + EE8FF11D18D32F6F9601FA0D = { + isa = "PBXNativeTarget"; + buildConfigurationList = "7B74F35F903EA73A5F1CC5CA"; + buildPhases = ( + DEAB4E94790E3EA7168A48C3, + B67A38D341342EF376079F91, + "95713C2B5DDEC29599BCB5F5", + "E9D1E579FDF61B49CE0FEC17", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerB"; + productName = "ShellWorkerB"; + productReference = "295B641B253C35B85CBD0100"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + F1BC0042128131FA3BB63FE6 = { + isa = "PBXNativeTarget"; + buildConfigurationList = "4E8FD56F38A3D6CA40A44BBA"; + buildPhases = ( + 258FF1E0CF03820F66E545A5, + 2D03C0D5AAA2F2256E34D090, + "2DC585EAE450FD4D0A61AFE3", + "F87943363674934C30AE6197", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerC"; + productName = "ShellWorkerC"; + productReference = "1D81B2E2F18AE7821D05A7AD"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + B1BF9CA28196AF7D11ED15C1 = { + isa = "PBXNativeTarget"; + buildConfigurationList = "C529F9BD8FC95FC69151E5D9"; + buildPhases = ( + 82F519E40E8A8147E4355208, + CD23A87555F8E9CB087A2CC3, + "6531237C17643573A10DC2A8", + "3A1724BD1DB4BAD26BEFB1A0", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerD"; + productName = "ShellWorkerD"; + productReference = "671E1D67938C7F8A1BF10D84"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + CE532D2E94C62529D2EAC80C = { + isa = "PBXNativeTarget"; + buildConfigurationList = "357D1EE97A1181CB2C69AE7B"; + buildPhases = ( + B845E8A798AC3E84D1E78A6A, + 0A54213A9F754AD98D50483E, + "FB4B4076C7B39F3D49510853", + "34CBB91233009C8ABD5A85B7", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerE"; + productName = "ShellWorkerE"; + productReference = "366758A2DEC0386D139D2234"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + E698830C007E12B930873C45 = { + isa = "PBXNativeTarget"; + buildConfigurationList = "63E3448BFC96684E006144BE"; + buildPhases = ( + 546F48346B8E1E84B6C5218F, + A8E67298AAEA82BF82D81A15, + "9E5D451B8CEF1EF743CC2B97", + "A3640D0AC75735AA97CA7E34", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerF"; + productName = "ShellWorkerF"; + productReference = "A8EA5B4748F0CC00F65BA1A1"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + 9C778EEDE9AFE25B17E919CD = { + isa = "PBXNativeTarget"; + buildConfigurationList = "01298A57963C7D7FC8A5E943"; + buildPhases = ( + 3BAA79E324EBC4898A0D14A6, + 9E2EF90743ED233D863DDABE, + "8565DB4F80836EA220237CA0", + "3C98BBDD25082B6A0ADD867E", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerG"; + productName = "ShellWorkerG"; + productReference = "A490F7519B2E1597438D0853"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + BDF38991DBFB316DAA737CDC = { + isa = "PBXNativeTarget"; + buildConfigurationList = "BFB21F5FBA41F45FB2CB4F2F"; + buildPhases = ( + 5A1CAE50D727AC931A1AC17A, + F47AB85C2E323C145A9C92C4, + "C9B665B86623DA45589D3DD5", + "BE93A368BA56F46061D5A30F", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerH"; + productName = "ShellWorkerH"; + productReference = "5A7F8536C04A2BAC1834B3E7"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + 980C38795331054C0AB04808 = { + isa = "PBXNativeTarget"; + buildConfigurationList = "5444CAFE71E28CDFEBA55CCD"; + buildPhases = ( + FCA3F3734E17EAA67DAFC01F, + 4FD09DF0A4CEF6A5C5CBDEB5, + "05343EBACA43E356190F5510", + "0DB04B227C827E3026826B08", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerI"; + productName = "ShellWorkerI"; + productReference = "1A10CFCE432C459F3DD1051D"; + productType = "com.apple.product-type.extensionkit-extension"; + }; + A614E13CB5ADC97DAC1C52AC = { + isa = "PBXNativeTarget"; + buildConfigurationList = "9094C1580181846504A7959E"; + buildPhases = ( + 0FCC490857271C3EA8FD0560, + 5BE30F6A540EDF0BD98793A1, + "5E23CF762C8E87A5C4F07026", + "81A62DB36AA951C12F501AA6", + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ShellWorkerJ"; + productName = "ShellWorkerJ"; + productReference = "93314A863CABFBA3A5626312"; + productType = "com.apple.product-type.extensionkit-extension"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -4057,6 +4706,16 @@ projectDirPath = ""; projectRoot = ""; targets = ( + B80CAEC73DAE28A7664A2FE7, + EE8FF11D18D32F6F9601FA0D, + F1BC0042128131FA3BB63FE6, + B1BF9CA28196AF7D11ED15C1, + CE532D2E94C62529D2EAC80C, + E698830C007E12B930873C45, + 9C778EEDE9AFE25B17E919CD, + BDF38991DBFB316DAA737CDC, + 980C38795331054C0AB04808, + A614E13CB5ADC97DAC1C52AC, 22984EE922C93DBC00069497 /* a-Shell */, 22AD8717246EBFFA00F415DE /* a-Shell-Intents */, 22AD8720246EBFFB00F415DE /* a-Shell-IntentsUI */, @@ -4210,8 +4869,271 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EC1A1AC5948AC9AA36F4B087 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E9D1E579FDF61B49CE0FEC17 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F87943363674934C30AE6197 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3A1724BD1DB4BAD26BEFB1A0 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 34CBB91233009C8ABD5A85B7 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3640D0AC75735AA97CA7E34 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3C98BBDD25082B6A0ADD867E = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BE93A368BA56F46061D5A30F = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0DB04B227C827E3026826B08 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 81A62DB36AA951C12F501AA6 = { + isa = "PBXResourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + B6DFC70EFFFF8DF6433E72CB = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + B67A38D341342EF376079F91 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + 2D03C0D5AAA2F2256E34D090 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + CD23A87555F8E9CB087A2CC3 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + 0A54213A9F754AD98D50483E = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + A8E67298AAEA82BF82D81A15 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + 9E2EF90743ED233D863DDABE = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + F47AB85C2E323C145A9C92C4 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + 4FD09DF0A4CEF6A5C5CBDEB5 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; + 5BE30F6A540EDF0BD98793A1 = { + isa = "PBXShellScriptBuildPhase"; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/Resources_mini/commandDictionary.plist", + "$(SRCROOT)/ShellWorkers/resources.sh", + "$(SRCROOT)/ShellWorkers/Worker.swift", + ); + name = "Prepare worker assets"; + outputPaths = ( + "$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/commandDictionary.plist", + "$(DERIVED_FILE_DIR)/Worker.swift", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = "/bin/bash"; + shellScript = "/bin/bash \"$SRCROOT/ShellWorkers/resources.sh\"\n"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 22178EF4257BBBA4008EB2B4 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -4289,6 +5211,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + C608987E0D35D7D8C92CF091, + 7A025EB47CCEBDAA7E49CB3E, 229D2477257931E4004A78AC /* ExtraCommands.swift in Sources */, 229D2478257931E4004A78AC /* AppDelegate.swift in Sources */, 223A1C1D2A5EDCA700B1B9AD /* Tips.swift in Sources */, @@ -4330,6 +5254,106 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 718D17729DFE061A0416ECA4 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "A1C0F473B5B02A405758E45F", + "01254C24560A350B59662101", + "948BA9E69DBEE6BFD829414C", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 95713C2B5DDEC29599BCB5F5 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "59144CB4855198131ED069B3", + "188B14A9B070A4E709C1A447", + "C27C502276A1F0301FBC2CBA", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2DC585EAE450FD4D0A61AFE3 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "2A45EE5BE77CD575DD0ADEBE", + "DB9A503B8C8690B9298B35E3", + "8F4F306A0A771AF4667582BA", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6531237C17643573A10DC2A8 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "F2D20BDE70DB7C92C03509DE", + "70E66D31CD0F42D23FBC3EFC", + "A85A41CEA814190D8404E105", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FB4B4076C7B39F3D49510853 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "F1632FC1E103CFB4010F7006", + "6C8E5746297C24B1080C03AF", + "7407B0C9B5E07D5492D98053", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9E5D451B8CEF1EF743CC2B97 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "8299DBD0E93022AAEACE5F54", + "B70CFF8BCD5A858CCB5D600B", + "084FF2541A50122906582CAC", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8565DB4F80836EA220237CA0 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "E357BFCCA00A4DD6EF1D0235", + "60BA73F3EE45C345CD0C593D", + "755E22C57BB293CDAD64CB41", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C9B665B86623DA45589D3DD5 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "556FE5F2A7285723350E4CAC", + "1C7B8B3BAEF7289AACBD231D", + "C3EEB3DED5B57200DA36F34E", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 05343EBACA43E356190F5510 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "359DDEBBC7AB6E4D48032723", + "E2CFAA905BF589905A69D32F", + "4096B185162EAE2C4738E1C1", + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5E23CF762C8E87A5C4F07026 = { + isa = "PBXSourcesBuildPhase"; + buildActionMask = 2147483647; + files = ( + "5A652AAB3F21AD3EEE1DC9B1", + "72B403FFF4DA5BA1CEDD5717", + "C14B2CCCCE38CFD39751A8F3", + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -4365,6 +5389,46 @@ target = 22AD8717246EBFFA00F415DE /* a-Shell-Intents */; targetProxy = 22AD872E246EBFFD00F415DE /* PBXContainerItemProxy */; }; + 88F36AC8C5832103CAA7195E = { + isa = "PBXTargetDependency"; + target = "B80CAEC73DAE28A7664A2FE7"; + }; + C07B3F85C9AAEB628033EA61 = { + isa = "PBXTargetDependency"; + target = "EE8FF11D18D32F6F9601FA0D"; + }; + BB6767147D3C4FEA4C3C952B = { + isa = "PBXTargetDependency"; + target = "F1BC0042128131FA3BB63FE6"; + }; + 26F687795555A5D88B96304D = { + isa = "PBXTargetDependency"; + target = "B1BF9CA28196AF7D11ED15C1"; + }; + A635836C211C3AB5C85C00A7 = { + isa = "PBXTargetDependency"; + target = "CE532D2E94C62529D2EAC80C"; + }; + 0AAC31F15A0DCCDD78983016 = { + isa = "PBXTargetDependency"; + target = "E698830C007E12B930873C45"; + }; + 42442DC659794242C4C4F078 = { + isa = "PBXTargetDependency"; + target = "9C778EEDE9AFE25B17E919CD"; + }; + 31A01BF362BE8594C88A7461 = { + isa = "PBXTargetDependency"; + target = "BDF38991DBFB316DAA737CDC"; + }; + AD01960A41E12D8546D60344 = { + isa = "PBXTargetDependency"; + target = "980C38795331054C0AB04808"; + }; + E119072ED69DB93517DB130D = { + isa = "PBXTargetDependency"; + target = "A614E13CB5ADC97DAC1C52AC"; + }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -5033,6 +6097,186 @@ }; name = Release; }; + DC87439DFACFBC5E6720ADF1 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerA"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerA"; + }; + name = "Debug"; + }; + BA1F3E3B5D416DFE86D9EE20 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerA"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerA"; + }; + name = "Release"; + }; + 49EECCB6CADB39D8B8693B1A = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerB"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerB"; + }; + name = "Debug"; + }; + 55B5C32D6ABB182F8415F3E8 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerB"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerB"; + }; + name = "Release"; + }; + 3D16C484D9FB67F9E4A967F1 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerC"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerC"; + }; + name = "Debug"; + }; + 389011DD426091393EAB6662 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerC"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerC"; + }; + name = "Release"; + }; + 88DB69305DE72BD245EEEF21 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerD"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerD"; + }; + name = "Debug"; + }; + EF65C555B0AF51766A1051B8 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerD"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerD"; + }; + name = "Release"; + }; + 201F025FCF49E73888B0B562 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerE"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerE"; + }; + name = "Debug"; + }; + 40CDA083E3E201CEEC579D2C = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerE"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerE"; + }; + name = "Release"; + }; + 4B6D89CD4EFC7D905940B09E = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerF"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerF"; + }; + name = "Debug"; + }; + D05AF64AC9567EE39EC70897 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerF"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerF"; + }; + name = "Release"; + }; + F9CACCCC7F5AA5543BB48468 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerG"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerG"; + }; + name = "Debug"; + }; + CB9596B242B3686F3D58FE8E = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerG"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerG"; + }; + name = "Release"; + }; + 472F5990568AF73F0DDA5984 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerH"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerH"; + }; + name = "Debug"; + }; + AF505CCF3483810C2864282F = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerH"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerH"; + }; + name = "Release"; + }; + 05813E7057E8747F469C45B5 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerI"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerI"; + }; + name = "Debug"; + }; + E408A607AE680275D025988F = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerI"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerI"; + }; + name = "Release"; + }; + 5A3E39E37904499071CED2F3 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerJ"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerJ"; + }; + name = "Debug"; + }; + 1572AF9E6C2EFC03C506A102 = { + isa = "XCBuildConfiguration"; + baseConfigurationReference = "0893D186728BD261366E4BD1"; + buildSettings = { + PRODUCT_NAME = "ShellWorkerJ"; + PRODUCT_BUNDLE_IDENTIFIER = "$(PRODUCT_BUNDLE_PREFIX:default=AsheKube.app).a-Shell-mini.ShellWorkerJ"; + }; + name = "Release"; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -5108,6 +6352,96 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + AF05FF73FF3462482114110C = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "DC87439DFACFBC5E6720ADF1", + "BA1F3E3B5D416DFE86D9EE20", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 7B74F35F903EA73A5F1CC5CA = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "49EECCB6CADB39D8B8693B1A", + "55B5C32D6ABB182F8415F3E8", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 4E8FD56F38A3D6CA40A44BBA = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "3D16C484D9FB67F9E4A967F1", + "389011DD426091393EAB6662", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + C529F9BD8FC95FC69151E5D9 = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "88DB69305DE72BD245EEEF21", + "EF65C555B0AF51766A1051B8", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 357D1EE97A1181CB2C69AE7B = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "201F025FCF49E73888B0B562", + "40CDA083E3E201CEEC579D2C", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 63E3448BFC96684E006144BE = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "4B6D89CD4EFC7D905940B09E", + "D05AF64AC9567EE39EC70897", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 01298A57963C7D7FC8A5E943 = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "F9CACCCC7F5AA5543BB48468", + "CB9596B242B3686F3D58FE8E", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + BFB21F5FBA41F45FB2CB4F2F = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "472F5990568AF73F0DDA5984", + "AF505CCF3483810C2864282F", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 5444CAFE71E28CDFEBA55CCD = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "05813E7057E8747F469C45B5", + "E408A607AE680275D025988F", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; + 9094C1580181846504A7959E = { + isa = "XCConfigurationList"; + buildConfigurations = ( + "5A3E39E37904499071CED2F3", + "1572AF9E6C2EFC03C506A102", + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = "Release"; + }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ diff --git a/tests/worker-pool.m b/tests/worker-pool.m new file mode 100644 index 00000000..64f32d16 --- /dev/null +++ b/tests/worker-pool.m @@ -0,0 +1,226 @@ +#import +#import +#include +#include +#include +#include +#include +#include + + +// Keep each command alive at its public stdin boundary while the other slots start. +static int capacity_check(void) { + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); + int (*pollJob)(void *, int *) = dlsym(RTLD_DEFAULT, "ashell_pane_poll"); + void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); + if (!spawn || !pollJob || !release) { fputs("worker pool unavailable: FAIL\n", thread_stdout); return 1; } + NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:[@"Documents/worker-pool-" stringByAppendingString:NSUUID.UUID.UUIDString]]; + void *jobs[10] = {0}; + int descriptors[10]; + char output[10][2048] = {{0}}; + size_t used[10] = {0}; + int pids[10] = {0}; + BOOL passed = YES; + for (int i = 0; i < 10; i++) descriptors[i] = -1; + for (int i = 0; i < 10; i++) { + NSString *directory = [root stringByAppendingPathComponent:[NSString stringWithFormat:@"slot-%d", i]]; + if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil]) { passed = NO; break; } + char value[32], command[256]; + snprintf(value, sizeof(value), "POOL_VALUE=slot-%d", i); + const char *environment[] = {value, NULL}; + snprintf(command, sizeof(command), "dash -c 'printf \"READY=%%s,%%s\\n\" \"$ASHELL_WORKER_PID\" \"$POOL_VALUE\"; pwd; read value; printf \"END=%%s\\n\" \"$value\"; exit %d'", i); + int error = spawn(command, directory.fileSystemRepresentation, 80, 24, environment, &descriptors[i], &jobs[i]); + if (error) { fprintf(thread_stdout, "slot=%d startup error=%d: FAIL\n", i, error); passed = NO; break; } + if (fcntl(descriptors[i], F_SETFL, O_NONBLOCK)) { passed = NO; break; } + } + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 10; + BOOL allReady = NO; + while (passed && NSProcessInfo.processInfo.systemUptime < deadline) { + allReady = YES; + for (int i = 0; i < 10; i++) { + ssize_t count = read(descriptors[i], output[i] + used[i], sizeof(output[i]) - used[i] - 1); + if (count > 0) used[i] += count; + if (!strchr(output[i], '\n') || !strchr(strchr(output[i], '\n') + 1, '\n')) allReady = NO; + int status; + if (pollJob(jobs[i], &status) != 0) { passed = NO; break; } + } + if (allReady) break; + usleep(10000); + } + if (!allReady) passed = NO; + for (int i = 0; passed && i < 10; i++) { + char value[32]; + if (sscanf(output[i], "READY=%d,%31[^\n]", &pids[i], value) != 2 || pids[i] <= 0) { passed = NO; break; } + char expectedValue[32]; + snprintf(expectedValue, sizeof(expectedValue), "slot-%d", i); + NSString *expectedDirectory = [[root stringByAppendingPathComponent:[NSString stringWithFormat:@"slot-%d", i]] stringByAppendingString:@"\n"]; + if (strcmp(value, expectedValue) || strcmp(strchr(output[i], '\n') + 1, expectedDirectory.fileSystemRepresentation)) passed = NO; + for (int j = 0; j < i; j++) if (pids[i] == pids[j]) passed = NO; + fprintf(thread_stdout, "slot=%d real_pid=%d cwd/env=%s\n", i, pids[i], passed ? "PASS" : "FAIL"); + } + if (passed) { + int descriptor = -1; + void *job = NULL; + int error = spawn("dash -c 'exit 0'", root.fileSystemRepresentation, 80, 24, NULL, &descriptor, &job); + BOOL full = error == ENOSPC && descriptor == -1 && job == NULL; + fprintf(thread_stdout, "eleventh worker error=%d: %s\n", error, full ? "PASS" : "FAIL"); + if (job) release(job); + if (descriptor >= 0) close(descriptor); + passed = full; + } + // The same open sessions must still accept input after more than five seconds. + if (passed) { + sleep(6); + for (int i = 0; i < 10; i++) if (write(descriptors[i], "continue\n", 9) != 9) passed = NO; + for (int i = 0; i < 10; i++) { + BOOL exited = NO, eof = NO; + int status = -1; + deadline = NSProcessInfo.processInfo.systemUptime + 10; + while (NSProcessInfo.processInfo.systemUptime < deadline && (!exited || !eof)) { + ssize_t count = read(descriptors[i], output[i] + used[i], sizeof(output[i]) - used[i] - 1); + if (count > 0) used[i] += count; + else if (count == 0) eof = YES; + int result = pollJob(jobs[i], &status); + if (result == 1) exited = YES; + else if (result < 0) break; + if (!exited || !eof) usleep(10000); + } + BOOL completed = exited && eof && status == i && strstr(output[i], "END=continue\n"); + fprintf(thread_stdout, "slot=%d delayed input/status=%d: %s\n", i, status, completed ? "PASS" : "FAIL"); + if (!completed) passed = NO; + } + } + for (int i = 0; i < 10; i++) { + if (jobs[i]) release(jobs[i]); + if (descriptors[i] >= 0) close(descriptors[i]); + } + [[NSFileManager defaultManager] removeItemAtPath:root error:nil]; + fprintf(thread_stdout, "ten-worker capacity: %s\n", passed ? "PASS" : "FAIL"); + return passed ? 0 : 1; +} + + +static int lifecycle_check(BOOL busy, BOOL closeOnly) { + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); + int (*pollJob)(void *, int *) = dlsym(RTLD_DEFAULT, "ashell_pane_poll"); + int (*cancel)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_cancel"); + void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); + if (!spawn || !pollJob || !cancel || !release) { fputs("worker pool unavailable: FAIL\n", thread_stdout); return 1; } + NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; + void *jobs[3] = {0}; + int descriptors[3] = {-1, -1, -1}, pids[3] = {0}; + BOOL passed = YES; + for (int i = 0; i < 3; i++) { + const char *command = busy && i == 0 ? "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; while :; do :; done'" : "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; read value; printf \"DONE=%s\\n\" \"$value\"; exit 7'"; + int error = spawn(command, directory.fileSystemRepresentation, 80, 24, NULL, &descriptors[i], &jobs[i]); + if (error) { fprintf(thread_stdout, "lifecycle slot=%d startup=%d: FAIL\n", i, error); passed = NO; break; } + struct pollfd ready = {.fd = descriptors[i], .events = POLLIN}; + char output[128] = {0}; + size_t used = 0; + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 5; + while (!strchr(output, '\n') && used < sizeof(output) - 1 && NSProcessInfo.processInfo.systemUptime < deadline) { + if (poll(&ready, 1, 100) > 0) { + ssize_t count = read(descriptors[i], output + used, sizeof(output) - used - 1); + if (count > 0) used += count; + else break; + } + } + if (sscanf(output, "READY=%d", &pids[i]) != 1 || pids[i] <= 0 || pids[i] == getpid()) { passed = NO; break; } + for (int j = 0; j < i; j++) if (pids[i] == pids[j]) passed = NO; + } + if (passed) { + int status = -1; + BOOL cancelled = YES; + if (!closeOnly) cancelled = cancel(jobs[0]) == 0 && pollJob(jobs[0], &status) == 1 && status == 137; + release(jobs[0]); jobs[0] = NULL; + fprintf(thread_stdout, "%s one worker: %s\n", closeOnly ? "close" : "cancel", cancelled ? "PASS" : "FAIL"); + passed = cancelled; + close(descriptors[0]); descriptors[0] = -1; + } + if (passed) { + // Inject OS process loss only after that process identified itself through + // its public output and was proved distinct from the consumer and peers. + BOOL lost = kill(pids[1], SIGKILL) == 0; + int status = -1, result = 0; + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 5; + while (lost && NSProcessInfo.processInfo.systemUptime < deadline) { + result = pollJob(jobs[1], &status); + if (result) break; + usleep(10000); + } + lost = lost && result == 1 && status == 137; + fprintf(thread_stdout, "lost worker status=%d: %s\n", status, lost ? "PASS" : "FAIL"); + passed = lost; + release(jobs[1]); jobs[1] = NULL; + close(descriptors[1]); descriptors[1] = -1; + } + if (passed) { + int status = -1; + BOOL alive = pollJob(jobs[2], &status) == 0 && write(descriptors[2], "survivor\n", 9) == 9; + char output[128] = {0}; size_t used = 0; + BOOL exited = NO, eof = NO; + fcntl(descriptors[2], F_SETFL, O_NONBLOCK); + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 5; + while (alive && NSProcessInfo.processInfo.systemUptime < deadline && (!exited || !eof)) { + ssize_t count = read(descriptors[2], output + used, sizeof(output) - used - 1); + if (count > 0) used += count; + else if (count == 0) eof = YES; + int result = pollJob(jobs[2], &status); + if (result == 1) exited = YES; + else if (result < 0) break; + if (!exited || !eof) usleep(10000); + } + alive = alive && exited && eof && status == 7 && !strcmp(output, "DONE=survivor\n"); + fprintf(thread_stdout, "peer input/output/status after loss: %s\n", alive ? "PASS" : "FAIL"); + passed = alive; + } + for (int i = 0; i < 3; i++) { if (jobs[i]) release(jobs[i]); if (descriptors[i] >= 0) close(descriptors[i]); } + // Re-enter the full public capacity check after asynchronous teardown. + if (passed) passed = capacity_check() == 0; + if (!passed && busy && pids[0] > 0 && pids[0] != getpid()) kill(pids[0], SIGKILL); + fprintf(thread_stdout, "worker lifecycle and full capacity reuse: %s\n", passed ? "PASS" : "FAIL"); + return passed ? 0 : 1; +} + +// Run as a real app command. The same consumer must fail on the stock app. +int worker_pool_check_main(int argc, char **argv) { + @autoreleasepool { + if (argc == 2 && !strcmp(argv[1], "capacity")) return capacity_check(); + if (argc == 2 && !strcmp(argv[1], "lifecycle")) return lifecycle_check(NO, NO); + if (argc == 2 && !strcmp(argv[1], "lifecycle-busy")) return lifecycle_check(YES, NO); + if (argc == 2 && !strcmp(argv[1], "lifecycle-close")) return lifecycle_check(YES, YES); + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); + int (*pollJob)(void *, int *) = dlsym(RTLD_DEFAULT, "ashell_pane_poll"); + void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); + if (!spawn || !pollJob || !release) { + fputs("worker pool unavailable: FAIL\n", thread_stdout); + return 1; + } + NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; + const char *environment[] = {"POOL_VALUE=isolated", NULL}; + int descriptor = -1; + void *job = NULL; + int error = spawn("dash -c 'printf \"WORKER=%s\\n\" \"$POOL_VALUE\"'", directory.fileSystemRepresentation, 80, 24, environment, &descriptor, &job); + if (error) { fprintf(thread_stdout, "worker startup error=%d: FAIL\n", error); return 1; } + char output[256] = {0}; + size_t used = 0; + BOOL completed = NO; + int status = -1; + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 20; + while (NSProcessInfo.processInfo.systemUptime < deadline) { + struct pollfd ready = {.fd = descriptor, .events = POLLIN}; + if (poll(&ready, 1, 100) > 0 && used < sizeof(output) - 1) { + ssize_t count = read(descriptor, output + used, sizeof(output) - used - 1); + if (count > 0) used += count; + } + int result = pollJob(job, &status); + if (result < 0) break; + if (result == 1) { completed = YES; break; } + } + release(job); + close(descriptor); + BOOL passed = completed && status == 0 && !strcmp(output, "WORKER=isolated\n"); + fprintf(thread_stdout, "worker stdout=%zu status=%d: %s\n", used, status, passed ? "PASS" : "FAIL"); + return passed ? 0 : 1; + } +} diff --git a/tests/worker-pool.md b/tests/worker-pool.md new file mode 100644 index 00000000..a362535d --- /dev/null +++ b/tests/worker-pool.md @@ -0,0 +1,19 @@ +# Extension worker pool consumer + +`worker-pool.m` is an app command that calls the public C interface in `ShellWorkers/NativePane.h` through `dlsym`. It uses real extensions, XPC, socket streams and Dash. It does not mock the pool or add a production test entry point. + +In a disposable a-Shell mini build, add this source to the host target and register `replaceCommand("worker-pool-check", "worker_pool_check_main", true)` after `initializeEnvironment()` in `AppDelegate.swift`. Build the host with the matched ios_system#179–#184 and dash_iOS#1–#2 frameworks and libedit patch. Run these commands in the app terminal: + +```sh +worker-pool-check +worker-pool-check capacity +worker-pool-check lifecycle +worker-pool-check lifecycle-busy +worker-pool-check lifecycle-close +``` + +Each command returns zero on success and prints its assertions to the command output stream. The capacity check keeps ten commands open, requires ten distinct real process IDs and independent cwd/environment, rejects the eleventh request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. The lifecycle checks cancel or close one worker, inject `SIGKILL` into another worker that identified itself through stdout, check the surviving worker's input/output/status, and repeat the full capacity check. The busy variants make the first command ignore EOF. Run them only in a disposable build: they deliberately terminate worker processes belonging to that build. + +For a baseline, register the same command in unmodified a-Shell mini. It must print `worker pool unavailable: FAIL` and return one. The final stock baseline and patched app were built with byte-identical consumer source (SHA-256 `6e9dd2d1bc22548c5932dbc173983a51bd423e0883bb9632bc63849532d35967`). The stock baseline returned the missing-API failure for `lifecycle-close`; the patched app completed the lifecycle and ten-slot checks. + +Verified on iOS 27 Simulator: the stock baseline failed at missing pool API; the patched app passed the single-command and ten-worker checks. A first busy-loop lifecycle run failed with `EBUSY` after invalidation; explicit worker termination made that same regression pass. Simulator does not qualify physical-device sandbox enforcement, memory limits, ten-worker device capacity, background lifetime or App Store acceptance. Keep those checks separate. From a3e8a228633da2469c48858b3a6053fed3905639 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:11:52 +0300 Subject: [PATCH 02/16] Embed pinned Herdr runtime in the mini app --- Herdr/LICENSE | 201 +++ Herdr/README.md | 28 + Herdr/build.sh | 52 + Herdr/native/entry.patch | 86 ++ Herdr/native/herdr_ios.h | 23 + Herdr/native/host_io.rs | 137 ++ Herdr/native/input-startup.patch | 183 +++ Herdr/native/ios_entry.rs | 334 ++++ Herdr/native/ios_ipc.rs | 120 ++ Herdr/native/ios_pty.rs | 236 +++ Herdr/native/platform.patch | 318 ++++ Herdr/native/runtime.patch | 1779 ++++++++++++++++++++++ Herdr/tests/three-panes.sh | 91 ++ README.md | 4 + a-Shell.xcodeproj/project.pbxproj | 32 + a-Shell/AppDelegate.swift | 3 + a-Shell/SceneDelegate+TerminalView.swift | 8 + 17 files changed, 3635 insertions(+) create mode 100644 Herdr/LICENSE create mode 100644 Herdr/README.md create mode 100755 Herdr/build.sh create mode 100644 Herdr/native/entry.patch create mode 100644 Herdr/native/herdr_ios.h create mode 100644 Herdr/native/host_io.rs create mode 100644 Herdr/native/input-startup.patch create mode 100644 Herdr/native/ios_entry.rs create mode 100644 Herdr/native/ios_ipc.rs create mode 100644 Herdr/native/ios_pty.rs create mode 100644 Herdr/native/platform.patch create mode 100644 Herdr/native/runtime.patch create mode 100755 Herdr/tests/three-panes.sh diff --git a/Herdr/LICENSE b/Herdr/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/Herdr/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Herdr/README.md b/Herdr/README.md new file mode 100644 index 00000000..57d6b23c --- /dev/null +++ b/Herdr/README.md @@ -0,0 +1,28 @@ +# Embedded Herdr + +The mini target embeds Herdr v0.9.3 (`7b116c05bfda646af39d2524c54e70c751f57ee8`). Its original Rust client, server, renderer and Ghostty terminal engine run inside the app. Each pane runs its shell in a Generic Non-UI extension worker through `ashell_pane_*`. + +Install Rust 1.96.1 with the appropriate iOS target, Zig 0.16.0, Git and Xcode. Build the static archive before building the mini app: + +```sh +rustup target add --toolchain 1.96.1 aarch64-apple-ios-sim +./Herdr/build.sh aarch64-apple-ios-sim +``` + +For a signed device build, select `aarch64-apple-ios` in both commands. The recipe downloads the pinned source, applies the adapter patches, builds with the locked dependencies and prints the archive checksum. `Herdr/build/` contains generated files and is ignored. Rerunning resets only the recipe's generated source checkout and preserves its build caches. Set `ZIG` to select a Zig executable or `ZIG_GLOBAL_CACHE_DIR` to use an existing package cache. + +The mini target selects the archive matching its SDK, retains `herdr_ios_main` for command lookup, registers `herdr`, forwards terminal resize events and includes Herdr's Apache 2.0 license in the app resources. The worker pool requires iOS 26 or later and its matching ios_system and Dash prerequisites. + +Run `herdr` in the app terminal. `herdr --version`, `--help`, `--skill` and `--default-config` write to the current command streams. Other desktop CLI operations return status 78. One embedded Herdr instance owns the host terminal at a time; another returns status 16. The client and server communicate through an in-process socket pair during that command. There is no detached background server or desktop IPC service. + +The adapter forwards pane input, output, geometry, exit status, interrupts and close to the pool. Cwd defaults to the current command directory and pane calls are serialized per worker handle. Restored container paths are relocated under the current app home. Worker capacity, termination and recovery follow the pool contract in `ShellWorkers/NativePane.h` and the root README. + +To check an installed disposable Simulator app, install AXe and jq, start with a fresh shell in a portrait iPhone Simulator and keep Herdr's default keybindings and tab-name prompts. Run: + +```sh +./Herdr/tests/three-panes.sh SIMULATOR_UDID APP_BUNDLE_ID URL_SCHEME +``` + +The harness enters commands through the public terminal UI with paced keystrokes, confirms each new tab's name, and checks that three panes produce distinct worker PIDs belonging to the installed app and remain alive together. It then detaches and checks `herdr --version` through the same app process. Receipt files stay in the app's Documents directory. Against an app without Herdr, the same harness fails on the first missing receipt. + +CPU overlap, pane isolation and cancellation, physical-device behavior, application backgrounding, saved-session migration and worker WASM routing require separate qualification. diff --git a/Herdr/build.sh b/Herdr/build.sh new file mode 100755 index 00000000..8d96fa62 --- /dev/null +++ b/Herdr/build.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Build the pinned embedded runtime; all generated files stay in Herdr/build. +set -euo pipefail +root=$(cd "$(dirname "$0")" && pwd) +source_root="$root/build/source" +target=${1:-aarch64-apple-ios-sim} +revision=7b116c05bfda646af39d2524c54e70c751f57ee8 +case "$target" in +aarch64-apple-ios-sim | aarch64-apple-ios) ;; +*) + echo "usage: $0 [aarch64-apple-ios-sim|aarch64-apple-ios]" >&2 + exit 2 + ;; +esac +command -v cargo >/dev/null +command -v git >/dev/null +command -v "${ZIG:-zig}" >/dev/null +if [ -L "$root/build" ] || [ -L "$source_root" ]; then + echo "Herdr build directories must not be symbolic links" >&2 + exit 2 +fi +mkdir -p "$root/build" +if [ ! -d "$source_root/.git" ]; then + git clone --depth 1 --branch v0.9.3 https://github.com/herdrdev/herdr.git "$source_root" +fi +if [ "$(git -C "$source_root" remote get-url origin)" != https://github.com/herdrdev/herdr.git ]; then + echo "unexpected origin in the generated Herdr checkout" >&2 + exit 2 +fi +if [ "$(git -C "$source_root" rev-parse HEAD)" != "$revision" ]; then + echo "Herdr v0.9.3 does not match the pinned source revision" >&2 + exit 2 +fi +# This checkout contains only generated build inputs. Keep user repositories out. +git -C "$source_root" reset --hard --quiet "$revision" +git -C "$source_root" clean -fdq +git -C "$source_root" apply "$root/native/platform.patch" +git -C "$source_root" apply "$root/native/entry.patch" +git -C "$source_root" apply --unidiff-zero "$root/native/runtime.patch" +git -C "$source_root" apply "$root/native/input-startup.patch" +cp "$root/native/ios_entry.rs" "$source_root/src/ios_entry.rs" +cp "$root/native/host_io.rs" "$source_root/src/host_io.rs" +cp "$root/native/ios_ipc.rs" "$source_root/src/ios_ipc.rs" +cp "$root/native/ios_pty.rs" "$source_root/src/pty/ios.rs" +export CARGO_TARGET_DIR="$root/build/target" +export ZIG_GLOBAL_CACHE_DIR="${ZIG_GLOBAL_CACHE_DIR:-$root/build/zig-cache}" +export LIBGHOSTTY_VT_SIMD=false LIBGHOSTTY_VT_OPTIMIZE=ReleaseSmall +( + cd "$source_root" + cargo +1.96.1 build --locked --release --lib --target "$target" +) +shasum -a 256 "$CARGO_TARGET_DIR/$target/release/libherdr_ios.a" diff --git a/Herdr/native/entry.patch b/Herdr/native/entry.patch new file mode 100644 index 00000000..11d1136a --- /dev/null +++ b/Herdr/native/entry.patch @@ -0,0 +1,86 @@ +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -19,6 +19,11 @@ + "LICENSE", + "Cargo.toml", + ] ++ ++[lib] ++name = "herdr_ios" ++path = "src/main.rs" ++crate-type = ["staticlib"] + + [workspace] + members = ["crates/ghostty-vt"] +--- a/src/main.rs ++++ b/src/main.rs +@@ -1,3 +1,20 @@ ++#[cfg(target_os = "ios")] ++macro_rules! print { ($($arg:tt)*) => { crate::ios_entry::output(false, format_args!($($arg)*)) }; } ++#[cfg(target_os = "ios")] ++macro_rules! println { ++ () => { print!("\n") }; ++ ($($arg:tt)*) => { print!("{}\n", format_args!($($arg)*)) }; ++} ++#[cfg(target_os = "ios")] ++macro_rules! eprint { ($($arg:tt)*) => { crate::ios_entry::output(true, format_args!($($arg)*)) }; } ++#[cfg(target_os = "ios")] ++macro_rules! eprintln { ++ () => { eprint!("\n") }; ++ ($($arg:tt)*) => { eprint!("{}\n", format_args!($($arg)*)) }; ++} ++#[cfg(target_os = "ios")] ++mod ios_entry; ++ + use std::io; + + pub(crate) const HERDR_ENV_VAR: &str = "HERDR_ENV"; +@@ -512,9 +529,14 @@ + std::process::exit(2); + } + }; ++ run_main(raw_args) ++} ++ ++fn run_main(raw_args: Vec) -> io::Result<()> { + if let Some(outcome) = cli::maybe_run_machine(&raw_args) { + return finish_cli(outcome); + } ++ #[cfg(not(target_os = "ios"))] + let args = match session::configure_from_args(&raw_args) { + Ok(args) => args, + Err(err) => { +@@ -523,6 +545,8 @@ + std::process::exit(2); + } + }; ++ #[cfg(target_os = "ios")] ++ let args = raw_args; + let (args, remote_launch) = match remote::extract_remote_args(&args) { + Ok(parsed) => parsed, + Err(err) => { +--- a/src/platform/unix_common.rs ++++ b/src/platform/unix_common.rs +@@ -253,10 +253,12 @@ + } + } + ++#[cfg(not(target_os = "ios"))] + pub(crate) fn begin_cli_output() { + set_sigpipe_disposition(libc::SIG_DFL); + } + ++#[cfg(not(target_os = "ios"))] + pub(crate) fn end_cli_output() { + set_sigpipe_disposition(libc::SIG_IGN); + } +@@ -634,3 +636,9 @@ + std::fs::remove_dir_all(dir).unwrap(); + } + } ++ ++// The embedding host owns signal dispositions, not an informational command. ++#[cfg(target_os = "ios")] ++pub(crate) fn begin_cli_output() {} ++#[cfg(target_os = "ios")] ++pub(crate) fn end_cli_output() {} diff --git a/Herdr/native/herdr_ios.h b/Herdr/native/herdr_ios.h new file mode 100644 index 00000000..a83e37bc --- /dev/null +++ b/Herdr/native/herdr_ios.h @@ -0,0 +1,23 @@ +#ifndef HERDR_IOS_H +#define HERDR_IOS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Call on an ios_system command thread with streams already installed. + * argv is borrowed. The command owns duplicated descriptors, not host FILEs. + * Supports original local UI and informational flags. Other CLI paths return 78. + * Status: 0 success, 1 I/O error, 2 invalid arguments, 16 singleton busy, + * 70 caught Rust panic, 78 unsupported embedded operation. + * Server and socketpair endpoints live only during this embedded command. + * The host supplies the seven-argument ashell_pane_spawn ABI and related functions. + */ +int herdr_ios_main(int argc, const char **argv); +/* Call when host terminal dimensions change. Zero dimensions are ignored. */ +void herdr_ios_resize(unsigned short cols, unsigned short rows); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/Herdr/native/host_io.rs b/Herdr/native/host_io.rs new file mode 100644 index 00000000..b0a8f0aa --- /dev/null +++ b/Herdr/native/host_io.rs @@ -0,0 +1,137 @@ +//! Host streams are captured once on the command thread and shared by owned descriptors. +#[cfg(target_os = "ios")] +pub(crate) use embedded::*; +#[cfg(not(target_os = "ios"))] +pub(crate) use std::io::{stderr, stdin, stdout}; +#[cfg(not(target_os = "ios"))] +pub(crate) use std::process::exit; + +#[cfg(target_os = "ios")] +mod embedded { + use std::fs::File; + use std::io::{self, BufRead, BufReader, Read, Write}; + use std::os::fd::{AsRawFd, FromRawFd}; + use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, + }; + unsafe extern "C" { + fn ios_stdin() -> *mut libc::FILE; + fn ios_stdout() -> *mut libc::FILE; + fn ios_stderr() -> *mut libc::FILE; + fn ios_isatty(fd: i32) -> i32; + } + static FILES: Mutex, bool); 3]>> = Mutex::new(None); + pub(crate) static INPUT_STOP: AtomicBool = AtomicBool::new(false); + #[derive(Debug)] + pub(crate) struct ExitStatus(pub i32); + pub(crate) fn exit(code: i32) -> ! { + std::panic::resume_unwind(Box::new(ExitStatus(code))) + } + pub(crate) fn capture() -> io::Result<()> { + let mut captured = Vec::new(); + for ptr in unsafe { [ios_stdin(), ios_stdout(), ios_stderr()] } { + if ptr.is_null() { + return Err(io::Error::other("a-Shell stream is missing")); + } + let fd = unsafe { libc::fileno(ptr) }; + let terminal = unsafe { ios_isatty(fd) } != 0; + let fd = crate::pty::fd::duplicate_cloexec_fd(fd)?; + captured.push((Arc::new(unsafe { File::from_raw_fd(fd) }), terminal)); + } + *FILES.lock().unwrap() = Some(captured.try_into().unwrap()); + INPUT_STOP.store(false, Ordering::Release); + Ok(()) + } + pub(crate) fn release() { + INPUT_STOP.store(true, Ordering::Release); + *FILES.lock().unwrap() = None; + } + struct Reader { + file: Arc, + input: bool, + } + impl Read for Reader { + fn read(&mut self, b: &mut [u8]) -> io::Result { + if self.input { + loop { + if INPUT_STOP.load(Ordering::Acquire) { + return Ok(0); + } + if crate::platform::poll_fd_readable(self.file.as_raw_fd(), 100)? { + break; + } + } + } + (&*self.file).read(b) + } + } + pub(crate) struct Stream { + reader: BufReader, + terminal: bool, + } + impl Stream { + pub(crate) fn lock(self) -> Self { + self + } + pub(crate) fn read_line(&mut self, line: &mut String) -> io::Result { + self.reader.read_line(line) + } + pub(crate) fn is_terminal(&self) -> bool { + self.terminal + } + } + impl AsRawFd for Stream { + fn as_raw_fd(&self) -> i32 { + self.reader.get_ref().file.as_raw_fd() + } + } + impl Read for Stream { + fn read(&mut self, b: &mut [u8]) -> io::Result { + self.reader.read(b) + } + } + impl BufRead for Stream { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + self.reader.fill_buf() + } + fn consume(&mut self, n: usize) { + self.reader.consume(n) + } + } + impl Write for Stream { + fn write(&mut self, b: &[u8]) -> io::Result { + (&*self.reader.get_ref().file).write(b) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + fn stream(index: usize) -> Stream { + let (file, terminal) = FILES + .lock() + .unwrap() + .as_ref() + .expect("host streams captured before runtime")[index] + .clone(); + Stream { + reader: BufReader::with_capacity( + 4096, + Reader { + file, + input: index == 0, + }, + ), + terminal, + } + } + pub(crate) fn stdin() -> Stream { + stream(0) + } + pub(crate) fn stdout() -> Stream { + stream(1) + } + pub(crate) fn stderr() -> Stream { + stream(2) + } +} diff --git a/Herdr/native/input-startup.patch b/Herdr/native/input-startup.patch new file mode 100644 index 00000000..2f46fb2e --- /dev/null +++ b/Herdr/native/input-startup.patch @@ -0,0 +1,183 @@ +diff --git a/src/client/shell/state.rs b/src/client/shell/state.rs +--- a/src/client/shell/state.rs ++++ b/src/client/shell/state.rs +@@ -920,6 +920,10 @@ + pub(super) popup_pending_deadline: Option, + pub(super) next_request_id: u64, + pub(super) pending_requests: HashMap, ++ #[cfg(target_os = "ios")] ++ pub(super) pending_creation_input: Option<(String, Option)>, ++ #[cfg(target_os = "ios")] ++ pub(super) creation_input: Vec, + pub(super) pending_integration_installs: usize, + pub(super) pending_notifications: Vec, + pub(super) visible_notification: Option, +@@ -1085,6 +1089,10 @@ + popup_pending_deadline: None, + next_request_id: 1, + pending_requests: HashMap::new(), ++ #[cfg(target_os = "ios")] ++ pending_creation_input: None, ++ #[cfg(target_os = "ios")] ++ creation_input: Vec::new(), + pending_integration_installs: 0, + pending_notifications: Vec::new(), + visible_notification: None, +@@ -1233,6 +1241,11 @@ + self.last_composed_at = None; + self.selection_repaint_deadline = None; + self.pending_requests.clear(); ++ #[cfg(target_os = "ios")] ++ { ++ self.pending_creation_input = None; ++ self.creation_input.clear(); ++ } + self.pane_scroll_in_flight.clear(); + self.pane_scroll_queued.clear(); + self.pane_scroll_targets.clear(); +@@ -1560,6 +1573,16 @@ + Some(_) => {} + } + } ++ #[cfg(target_os = "ios")] ++ if self ++ .pending_creation_input ++ .as_ref() ++ .is_some_and(|(_, expected)| { ++ expected.is_some() && snapshot.focused_pane_id == *expected ++ }) ++ { ++ self.pending_creation_input = None; ++ } + self.snapshot = Some(snapshot); + self.reconcile_pending_workspace_highlight(); + let pending_surface = self.pending_pane_surface.take(); +diff --git a/src/client/shell/actions.rs b/src/client/shell/actions.rs +--- a/src/client/shell/actions.rs ++++ b/src/client/shell/actions.rs +@@ -409,6 +409,18 @@ + let request_id = self.next_request_id; + self.next_request_id = self.next_request_id.saturating_add(1); + let request_id = format!("client-shell:{request_id}"); ++ #[cfg(target_os = "ios")] ++ if changes_focus ++ && matches!( ++ &method, ++ crate::api::schema::Method::PaneSplit(_) ++ | crate::api::schema::Method::TabCreate(_) ++ | crate::api::schema::Method::WorkspaceCreate(_) ++ ) ++ { ++ // The API lane creates the worker; input must not target the old snapshot. ++ self.pending_creation_input = Some((request_id.clone(), None)); ++ } + self.pending_requests.insert( + request_id.clone(), + PendingEndpointRequest { +@@ -514,6 +526,40 @@ + .is_none_or(|snapshot| snapshot.boot_id != boot_id) + { + return (false, Vec::new()); ++ } ++ #[cfg(target_os = "ios")] ++ if self ++ .pending_creation_input ++ .as_ref() ++ .is_some_and(|(id, _)| id == request_id) ++ { ++ use crate::api::schema::ResponseResult; ++ let created = match &result { ++ Ok(ResponseResult::PaneInfo { pane }) => Some(pane.pane_id.clone()), ++ Ok(ResponseResult::TabCreated { root_pane, .. }) ++ | Ok(ResponseResult::WorkspaceCreated { root_pane, .. }) => { ++ Some(root_pane.pane_id.clone()) ++ } ++ _ => None, ++ }; ++ if let Some(pane) = created { ++ if self ++ .snapshot ++ .as_ref() ++ .and_then(|snapshot| snapshot.focused_pane_id.as_ref()) ++ == Some(&pane) ++ { ++ self.pending_creation_input = None; ++ } else { ++ self.pending_creation_input = Some((request_id.to_owned(), Some(pane))); ++ } ++ } else { ++ self.pending_creation_input = None; ++ self.creation_input.clear(); ++ self.receive_endpoint_error( ++ "Pane creation failed; buffered input was discarded".into(), ++ ); ++ } + } + if let PendingEndpointKind::PaneLinkResolve { target } = pending.kind { + return self.complete_link_hover(target, result); +diff --git a/src/client/shell/input.rs b/src/client/shell/input.rs +--- a/src/client/shell/input.rs ++++ b/src/client/shell/input.rs +@@ -157,12 +157,41 @@ + } + + pub(crate) fn handle_raw_events(&mut self, events: Vec) -> ClientShellInput { ++ #[cfg(target_os = "ios")] ++ let awaiting_focus = self ++ .snapshot ++ .as_ref() ++ .is_none_or(|snapshot| snapshot.focused_pane_id.is_none()); ++ #[cfg(target_os = "ios")] ++ let events = if !awaiting_focus ++ && self.pending_creation_input.is_none() ++ && !self.creation_input.is_empty() ++ { ++ let mut buffered = std::mem::take(&mut self.creation_input); ++ buffered.extend(events); ++ buffered ++ } else { ++ events ++ }; + let mut outcome = ClientShellInput::default(); + if !events.is_empty() && self.endpoint_error.take().is_some() { + self.endpoint_error_deadline = None; + outcome.repaint = true; + } + for event in events { ++ #[cfg(target_os = "ios")] ++ if self.pending_creation_input.is_some() { ++ // Buffer only an outstanding creation; unfocused overlays and controls still handle input. ++ // Preserve order even when a split binding and text share one input batch. ++ if self.creation_input.len() < 4096 { ++ self.creation_input.push(event); ++ } else { ++ outcome.repaint |= self.receive_endpoint_error( ++ "Pane startup input buffer is full; input was rejected".into(), ++ ); ++ } ++ continue; ++ } + if self.handle_machine_badge_event(&event, &mut outcome) { + continue; + } +diff --git a/src/client/mod.rs b/src/client/mod.rs +--- a/src/client/mod.rs ++++ b/src/client/mod.rs +@@ -2249,6 +2249,17 @@ + let (effects, outcome, frame) = { + let shell = state.shell.as_mut().expect("checked shell mode"); + let mut outcome = shell.tick_selection_autoscroll(now); ++ #[cfg(target_os = "ios")] ++ { ++ let buffered = shell.handle_raw_events(Vec::new()); ++ outcome.repaint |= buffered.repaint; ++ outcome.resize |= buffered.resize; ++ outcome.detach |= buffered.detach; ++ outcome.query_host_appearance |= buffered.query_host_appearance; ++ outcome.query_host_theme |= buffered.query_host_theme; ++ outcome.requests.extend(buffered.requests); ++ outcome.actions.extend(buffered.actions); ++ } + for expired in expired_endpoints { + if !shell.endpoint_is_active(&expired.endpoint_id) { + continue; diff --git a/Herdr/native/ios_entry.rs b/Herdr/native/ios_entry.rs new file mode 100644 index 00000000..a42dc5b3 --- /dev/null +++ b/Herdr/native/ios_entry.rs @@ -0,0 +1,334 @@ +//! Embedded original client/server lifecycle. The host owns terminal and pane execution. +use std::ffi::CStr; +use std::io::{self, Write}; +use std::sync::{ + atomic::{AtomicBool, AtomicU32, Ordering}, + Arc, Mutex, OnceLock, +}; +use std::thread::JoinHandle; +unsafe extern "C" { + fn ios_startInteractive(); + fn ios_stopInteractive(); + fn ios_getenv(name: *const libc::c_char) -> *const libc::c_char; +} +static ACTIVE: AtomicBool = AtomicBool::new(false); +static GRID: AtomicU32 = AtomicU32::new(0); +static INTERACTIVE: AtomicBool = AtomicBool::new(false); +static SERVER: Mutex>>> = Mutex::new(None); +static CLIENT_QUIT: Mutex>> = Mutex::new(None); +static CLIENT_THREADS: Mutex>> = Mutex::new(Vec::new()); +static STARTUP_CWD: Mutex> = Mutex::new(None); +pub(crate) fn take_startup_cwd() -> Option { + STARTUP_CWD.lock().unwrap().take() +} +pub(crate) fn remember_client_quit(flag: Arc) { + *CLIENT_QUIT.lock().unwrap() = Some(flag); +} +pub(crate) fn spawn_client_thread(operation: impl FnOnce() + Send + 'static) { + CLIENT_THREADS + .lock() + .unwrap() + .push(std::thread::spawn(operation)); +} +pub(crate) fn server_stop_flag() -> Arc { + static STOP: OnceLock> = OnceLock::new(); + STOP.get_or_init(|| Arc::new(AtomicBool::new(false))) + .clone() +} +pub(crate) fn start_server() -> io::Result { + let mut server = SERVER.lock().unwrap(); + if server.is_some() { + return Err(io::Error::from(io::ErrorKind::AlreadyExists)); + } + server_stop_flag().store(false, Ordering::Release); + *server = Some( + std::thread::Builder::new() + .name("herdr-ios-server".into()) + .spawn( + || match std::panic::catch_unwind(crate::server::headless::run_server) { + Ok(result) => result, + Err(payload) => Err(io::Error::other( + if let Some(status) = payload.downcast_ref::() { + format!("server returned status {}", status.0) + } else { + "server panicked".into() + }, + )), + }, + )?, + ); + Ok(std::process::id()) +} +pub(crate) fn output(error: bool, args: std::fmt::Arguments<'_>) { + let _ = if error { + crate::host_io::stderr().write_fmt(args) + } else { + crate::host_io::stdout().write_fmt(args) + }; +} +#[no_mangle] +pub extern "C" fn herdr_ios_resize(cols: u16, rows: u16) { + if cols != 0 && rows != 0 { + GRID.store((u32::from(cols) << 16) | u32::from(rows), Ordering::Release); + } +} +pub(crate) fn grid_size() -> io::Result<(u16, u16)> { + let grid = GRID.load(Ordering::Acquire); + if grid == 0 { + Err(io::Error::new( + io::ErrorKind::NotConnected, + "host terminal geometry is missing", + )) + } else { + Ok(((grid >> 16) as u16, grid as u16)) + } +} +pub(crate) fn terminal_start() -> io::Result<()> { + if INTERACTIVE.swap(true, Ordering::AcqRel) { + return Ok(()); + } + unsafe { + ios_startInteractive(); + } + crate::host_io::stdout().write_all(b"\x1b[?1049h") +} +pub(crate) fn terminal_stop() -> io::Result<()> { + if INTERACTIVE.swap(false, Ordering::AcqRel) { + // Resume a-Shell's line editor at column zero in the normal screen buffer. + let result = crate::host_io::stdout().write_all(b"\x1b[?1049l\x1b[?25h\r\n"); + unsafe { + ios_stopInteractive(); + } + result + } else { + Ok(()) + } +} +struct CommandGuard; +impl Drop for CommandGuard { + fn drop(&mut self) { + if let Some(flag) = CLIENT_QUIT.lock().unwrap().take() { + flag.store(true, Ordering::Release); + } + crate::host_io::INPUT_STOP.store(true, Ordering::Release); + server_stop_flag().store(true, Ordering::Release); + crate::pty::backend::close_all_stdin(); + let threads = std::mem::take(&mut *CLIENT_THREADS.lock().unwrap()); + for thread in threads { + let _ = thread.join(); + } + if let Some(server) = SERVER.lock().unwrap().take() { + let _ = server.join(); + } + let _ = terminal_stop(); + crate::host_io::release(); + ACTIVE.store(false, Ordering::Release); + } +} +/// Borrow argv and capture streams on the ios_system command thread; never unwind into C. +#[no_mangle] +pub unsafe extern "C" fn herdr_ios_main( + argc: libc::c_int, + argv: *const *const libc::c_char, +) -> libc::c_int { + if !(1..=64).contains(&argc) || argv.is_null() { + return 2; + } + if ACTIVE + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return 16; + } + if crate::host_io::capture().is_err() { + ACTIVE.store(false, Ordering::Release); + return 1; + } + let _guard = CommandGuard; + let result = std::panic::catch_unwind(|| { + let mut args = Vec::with_capacity(argc as usize); + for index in 0..argc as usize { + let arg = *argv.add(index); + if arg.is_null() { + return 2; + } + let Ok(arg) = CStr::from_ptr(arg).to_str() else { + return 2; + }; + args.push(arg.to_owned()); + } + // Ancillary process-launching CLI paths require their own host contracts. + if args.len() != 1 + && !(args.len() == 2 + && matches!( + args[1].as_str(), + "--version" | "-V" | "--help" | "-h" | "--skill" | "--default-config" + )) + { + output( + true, + format_args!( + "herdr: this embedded build supports local UI and informational flags\n" + ), + ); + return 78; + } + for (name, shift) in [(c"COLUMNS", 16), (c"LINES", 0)] { + let value = ios_getenv(name.as_ptr()); + if !value.is_null() { + if let Ok(value) = CStr::from_ptr(value).to_string_lossy().parse::() { + if value != 0 { + GRID.fetch_update(Ordering::AcqRel, Ordering::Acquire, |grid| { + Some((grid & !(0xffff << shift)) | (u32::from(value) << shift)) + }) + .ok(); + } + } + } + } + // Keep early keystrokes in the host stdin pipe while worker restoration runs. + if args.len() == 1 { + // PWD belongs to the invoking a-Shell session. The server thread's + // process cwd can instead be the Simulator data or extension directory. + use std::os::unix::ffi::OsStrExt; + let cwd = ios_getenv(c"PWD".as_ptr()); + if cwd.is_null() { + output(true, format_args!("herdr: a-Shell session directory is missing\n")); + return 1; + } + let cwd = std::path::PathBuf::from(std::ffi::OsStr::from_bytes( + CStr::from_ptr(cwd).to_bytes(), + )); + if !cwd.is_absolute() || !cwd.is_dir() { + output(true, format_args!("herdr: a-Shell session directory is unavailable\n")); + return 1; + } + *STARTUP_CWD.lock().unwrap() = Some(cwd); + if let Err(error) = terminal_start() { + output(true, format_args!("herdr: {error}\n")); + return 1; + } + } + match crate::run_main(args) { + Ok(()) => 0, + Err(error) => { + output(true, format_args!("herdr: {error}\n")); + 1 + } + } + }); + match result { + Ok(status) => status, + Err(payload) => payload + .downcast_ref::() + .map_or(70, |status| status.0), + } +} + +// Preserve accessible directories and relocate this app's old container paths. +// Unavailable saved directories fall back to the normal home instead of a dead pane. +pub(crate) fn relocate_snapshot(snapshot: &mut crate::persist::SessionSnapshot) -> bool { + use std::path::{Component, Path, PathBuf}; + fn accessible(path: &Path) -> bool { + use std::os::unix::ffi::OsStrExt; + let Ok(path_c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { + return false; + }; + path.is_dir() && unsafe { libc::access(path_c.as_ptr(), libc::R_OK | libc::X_OK) == 0 } + } + fn relocate(cwd: &Path, root: &Path) -> Option { + // Recover only the exact stock URL-launch root, not selected folders inside it. + if let Some(group) = std::env::var_os("GROUP").and_then(|p| std::fs::canonicalize(p).ok()) { + let documents = root.join("Documents"); + if cwd.canonicalize().is_ok_and(|p| p == group) && accessible(&documents) { + return Some(documents); + } + } + if accessible(cwd) { + return Some(cwd.to_path_buf()); + } + let parent = root.parent()?; + let aliases = [ + parent.to_path_buf(), + PathBuf::from(parent.to_string_lossy().trim_start_matches("/private")), + ]; + for parent in aliases { + let Ok(relative) = cwd.strip_prefix(&parent) else { + continue; + }; + let mut parts = relative.components(); + let Some(Component::Normal(old_id)) = parts.next() else { + continue; + }; + let id = old_id.to_string_lossy(); + if id.len() != 36 + || !id.bytes().enumerate().all(|(i, b)| { + if [8, 13, 18, 23].contains(&i) { + b == b'-' + } else { + b.is_ascii_hexdigit() + } + }) + { + continue; + } + let suffix = parts.as_path(); + if suffix + .components() + .any(|p| matches!(p, Component::ParentDir)) + { + continue; + } + let candidate = root.join(suffix); + if accessible(&candidate) && candidate.canonicalize().is_ok_and(|p| p.starts_with(root)) + { + tracing::info!(old = %cwd.display(), new = %candidate.display(), "relocated saved app-container cwd"); + return Some(candidate); + } + } + None + } + let Some(root) = std::env::var_os("HOME").and_then(|p| std::fs::canonicalize(p).ok()) else { + return false; + }; + if !root + .parent() + .is_some_and(|p| p.ends_with("Containers/Data/Application")) + { + return false; + } + let documents = root.join("Documents"); + let fallback = if accessible(&documents) { + documents + } else { + root.clone() + }; + let mut changed = false; + for workspace in &mut snapshot.workspaces { + let cwd = relocate(&workspace.identity_cwd, &root).unwrap_or_else(|| fallback.clone()); + changed |= cwd != workspace.identity_cwd; + workspace.identity_cwd = cwd; + if let Some(mut space) = workspace.worktree_space.take() { + match ( + relocate(&space.repo_root, &root), + relocate(&space.checkout_path, &root), + ) { + (Some(repo_root), Some(checkout_path)) => { + changed |= repo_root != space.repo_root || checkout_path != space.checkout_path; + space.repo_root = repo_root; + space.checkout_path = checkout_path; + workspace.worktree_space = Some(space); + } + _ => changed = true, + } + } + for tab in &mut workspace.tabs { + for pane in tab.panes.values_mut() { + let cwd = relocate(&pane.cwd, &root).unwrap_or_else(|| fallback.clone()); + changed |= cwd != pane.cwd; + pane.cwd = cwd; + } + } + } + changed +} diff --git a/Herdr/native/ios_ipc.rs b/Herdr/native/ios_ipc.rs new file mode 100644 index 00000000..df88c9e7 --- /dev/null +++ b/Herdr/native/ios_ipc.rs @@ -0,0 +1,120 @@ +//! Embedded endpoints keep the original Unix stream protocol without sockaddr_un path limits. +//! Only this process can look up an endpoint; no filesystem or global CWD is used. +use crate::ipc::LocalStream; +use std::collections::HashMap; +use std::io; +use std::os::fd::OwnedFd; +use std::os::unix::net::UnixStream; +use std::path::{Path, PathBuf}; +use std::sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc, Mutex, OnceLock, +}; +struct Endpoint { + sender: mpsc::SyncSender, + generation: u64, +} +static NEXT: AtomicU64 = AtomicU64::new(1); +fn endpoints() -> &'static Mutex> { + static E: OnceLock>> = OnceLock::new(); + E.get_or_init(|| Mutex::new(HashMap::new())) +} +pub(crate) struct LocalListener { + path: PathBuf, + generation: u64, + receiver: Mutex>, + nonblocking: AtomicBool, +} +impl LocalListener { + pub(crate) fn set_nonblocking( + &self, + mode: interprocess::local_socket::ListenerNonblockingMode, + ) -> io::Result<()> { + self.nonblocking.store( + !matches!( + mode, + interprocess::local_socket::ListenerNonblockingMode::Neither + ), + Ordering::Release, + ); + Ok(()) + } + pub(crate) fn accept(&self) -> io::Result { + let rx = self.receiver.lock().unwrap(); + if self.nonblocking.load(Ordering::Acquire) { + rx.try_recv() + .map_err(|_| io::Error::from(io::ErrorKind::WouldBlock)) + } else { + rx.recv() + .map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe)) + } + } + pub(crate) fn incoming(&self) -> impl Iterator> + '_ { + std::iter::repeat_with(move || self.accept()) + } +} +impl Drop for LocalListener { + fn drop(&mut self) { + remove(&self.path, self.generation); + } +} +pub(crate) fn bind(path: &Path) -> io::Result { + let mut e = endpoints().lock().unwrap(); + if e.contains_key(path) { + return Err(io::Error::from(io::ErrorKind::AddrInUse)); + } + let (sender, receiver) = mpsc::sync_channel(64); + let generation = NEXT.fetch_add(1, Ordering::Relaxed); + e.insert(path.to_owned(), Endpoint { sender, generation }); + Ok(LocalListener { + path: path.to_owned(), + generation, + receiver: Mutex::new(receiver), + nonblocking: AtomicBool::new(false), + }) +} +pub(crate) fn connect(path: &Path) -> io::Result { + let e = endpoints().lock().unwrap(); + let endpoint = e + .get(path) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; + let (client, server) = UnixStream::pair()?; + let wrap = |s: UnixStream| { + LocalStream::UdSocket(interprocess::os::unix::uds_local_socket::Stream::from( + OwnedFd::from(s), + )) + }; + endpoint + .sender + .try_send(wrap(server)) + .map_err(|_| io::Error::from(io::ErrorKind::WouldBlock))?; + Ok(wrap(client)) +} +pub(crate) fn identity(path: &Path) -> io::Result { + endpoints() + .lock() + .unwrap() + .get(path) + .map(|e| e.generation) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound)) +} +pub(crate) fn remove(path: &Path, generation: u64) { + let mut e = endpoints().lock().unwrap(); + if e.get(path).is_some_and(|e| e.generation == generation) { + e.remove(path); + } +} +pub(crate) fn prepare(path: &Path) -> io::Result<()> { + if endpoints().lock().unwrap().contains_key(path) { + Err(io::Error::from(io::ErrorKind::AddrInUse)) + } else { + Ok(()) + } +} +pub(crate) fn private(path: &Path, mode: u32) -> io::Result<()> { + identity(path)?; + if mode & 0o077 != 0 { + return Err(io::Error::from(io::ErrorKind::PermissionDenied)); + } + Ok(()) +} diff --git a/Herdr/native/ios_pty.rs b/Herdr/native/ios_pty.rs new file mode 100644 index 00000000..d7c4fbf5 --- /dev/null +++ b/Herdr/native/ios_pty.rs @@ -0,0 +1,236 @@ +//! Original pane actor integration with the host-owned ios_system backend. +use portable_pty::{Child, ChildKiller, CommandBuilder, ExitStatus}; +use std::collections::HashMap; +use std::ffi::CString; +use std::os::fd::{FromRawFd, OwnedFd}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::{io, thread, time::Duration}; +unsafe extern "C" { + fn ashell_pane_spawn( + command: *const libc::c_char, + cwd: *const libc::c_char, + cols: u32, + rows: u32, + envp: *const *const libc::c_char, + fd: *mut i32, + job: *mut *mut libc::c_void, + ) -> i32; + fn ashell_pane_poll(job: *mut libc::c_void, status: *mut i32) -> i32; + fn ashell_pane_resize(job: *mut libc::c_void, cols: u32, rows: u32) -> i32; + fn ashell_pane_cancel(job: *mut libc::c_void) -> i32; + fn ashell_pane_interrupt(job: *mut libc::c_void) -> i32; + fn ashell_pane_close_stdin(job: *mut libc::c_void) -> i32; + fn ashell_pane_release(job: *mut libc::c_void); +} +fn jobs() -> &'static Mutex>> { + static JOBS: OnceLock>>> = OnceLock::new(); + JOBS.get_or_init(|| Mutex::new(HashMap::new())) +} +fn positive_errno(status: i32) -> io::Result<()> { + if status == 0 { + Ok(()) + } else { + Err(io::Error::from_raw_os_error(status)) + } +} +#[derive(Debug)] +struct Job { + pointer: usize, + fd: i32, + calls: Mutex<()>, +} +impl Drop for Job { + fn drop(&mut self) { + jobs().lock().unwrap().remove(&self.fd); + unsafe { ashell_pane_release(self.pointer as *mut _) } + } +} +pub(crate) fn resize(fd: i32, rows: u16, cols: u16) -> io::Result<()> { + let job = jobs() + .lock() + .unwrap() + .get(&fd) + .and_then(Weak::upgrade) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; + let _call = job.calls.lock().unwrap(); + positive_errno(unsafe { ashell_pane_resize(job.pointer as *mut _, cols.into(), rows.into()) }) +} +pub(crate) fn interrupt(fd: i32) -> io::Result { + let job = jobs() + .lock() + .unwrap() + .get(&fd) + .and_then(Weak::upgrade) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; + let _call = job.calls.lock().unwrap(); + match unsafe { ashell_pane_interrupt(job.pointer as *mut _) } { + 0 => Ok(true), + libc::ENOTSUP => Ok(false), + error => Err(io::Error::from_raw_os_error(error)), + } +} +pub(crate) fn cancel(fd: i32) { + let job = jobs().lock().unwrap().get(&fd).and_then(Weak::upgrade); + if let Some(job) = job { + let _call = job.calls.lock().unwrap(); + let _ = unsafe { ashell_pane_cancel(job.pointer as *mut _) }; + } +} +pub(crate) fn close_all_stdin() { + let live: Vec<_> = jobs() + .lock() + .unwrap() + .values() + .filter_map(Weak::upgrade) + .collect(); + for job in live { + let _call = job.calls.lock().unwrap(); + let _ = positive_errno(unsafe { ashell_pane_close_stdin(job.pointer as *mut _) }); + } +} +#[derive(Debug)] +struct CommandChild { + job: Arc, +} +impl ChildKiller for CommandChild { + fn kill(&mut self) -> io::Result<()> { + let _call = self.job.calls.lock().unwrap(); + positive_errno(unsafe { ashell_pane_cancel(self.job.pointer as *mut _) }) + } + fn clone_killer(&self) -> Box { + Box::new(Self { + job: self.job.clone(), + }) + } +} +impl Child for CommandChild { + fn try_wait(&mut self) -> io::Result> { + let mut status = 0; + let _call = self.job.calls.lock().unwrap(); + match unsafe { ashell_pane_poll(self.job.pointer as *mut _, &mut status) } { + 0 => Ok(None), + 1 => Ok(Some(ExitStatus::with_exit_code(status as u32))), + error => Err(io::Error::from_raw_os_error(-error)), + } + } + fn wait(&mut self) -> io::Result { + loop { + if let Some(status) = self.try_wait()? { + return Ok(status); + } + thread::sleep(Duration::from_millis(10)); + } + } + fn process_id(&self) -> Option { + None + } +} +pub(crate) struct SpawnedPty { + pub master_fd: OwnedFd, + pub child: Box, +} +pub(crate) fn spawn_with_portable_pty( + rows: u16, + cols: u16, + cmd: CommandBuilder, +) -> io::Result { + let mut args: Vec = cmd + .get_argv() + .iter() + .map(|a| { + a.to_str().map(str::to_owned).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "pane argument is not UTF-8") + }) + }) + .collect::>()?; + if args.is_empty() { + return Err(io::Error::from(io::ErrorKind::InvalidInput)); + } + if args[0] == "/bin/sh" { + args[0] = "sh".into(); + } + if args[0] == "/bin/dash" { + args[0] = "dash".into(); + } + // ios_system sh only dispatches commands; native dash owns interactive input. + if args[0] == "sh" && !args.iter().any(|a| a == "-c") { + args[0] = "dash".into(); + } + if matches!(args[0].as_str(), "sh" | "dash") && !args.iter().any(|a| a == "-c" || a == "-i") { + args.push("-i".into()); + } + if args[0] == "dash" + && !args + .iter() + .any(|arg| arg == "-c" || arg == "-E" || arg == "-V") + { + args.push("-E".into()); + } + let command = CString::new( + args.iter() + .map(|a| format!("'{}'", a.replace('\'', "'\\''"))) + .collect::>() + .join(" "), + ) + .map_err(io::Error::other)?; + let fallback_cwd = std::env::current_dir()?.into_os_string(); + let cwd = CString::new( + cmd.get_cwd() + .unwrap_or(&fallback_cwd) + .to_str() + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "pane directory is not UTF-8") + })?, + ) + .map_err(io::Error::other)?; + let env: Vec = cmd + .iter_full_env() + .map(|(k, v)| { + let k = k.to_str().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "pane environment key is not UTF-8", + ) + })?; + let v = v.to_str().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "pane environment value is not UTF-8", + ) + })?; + CString::new(format!("{k}={v}")).map_err(io::Error::other) + }) + .collect::>()?; + let mut envp: Vec<_> = env.iter().map(|v| v.as_ptr()).collect(); + envp.push(std::ptr::null()); + let mut fd = -1; + let mut pointer = std::ptr::null_mut(); + let error = unsafe { + ashell_pane_spawn( + command.as_ptr(), + cwd.as_ptr(), + cols.into(), + rows.into(), + envp.as_ptr(), + &mut fd, + &mut pointer, + ) + }; + if error == libc::ENOSPC { + return Err(io::Error::other("Worker pool full. Close a pane.")); + } + positive_errno(error)?; + if fd < 0 || pointer.is_null() { + return Err(io::Error::other("pane backend returned an invalid handle")); + } + let job = Arc::new(Job { + pointer: pointer as usize, + fd, + calls: Mutex::new(()), + }); + jobs().lock().unwrap().insert(fd, Arc::downgrade(&job)); + Ok(SpawnedPty { + master_fd: unsafe { OwnedFd::from_raw_fd(fd) }, + child: Box::new(CommandChild { job }), + }) +} diff --git a/Herdr/native/platform.patch b/Herdr/native/platform.patch new file mode 100644 index 00000000..71828a98 --- /dev/null +++ b/Herdr/native/platform.patch @@ -0,0 +1,318 @@ +--- a/src/platform/macos.rs ++++ b/src/platform/macos.rs +@@ -29,145 +29,7 @@ + #[cfg(test)] + mod config_file_tests; + +-pub(crate) fn config_file_link_count(path: &Path) -> std::io::Result { +- use std::os::unix::fs::MetadataExt; +- Ok(std::fs::metadata(path)?.nlink()) +-} +- +-pub(crate) fn check_config_write_target(_target: &std::path::Path) -> std::io::Result<()> { +- Ok(()) +-} +- +-pub(crate) fn write_existing_config( +- _target: &std::path::Path, +- _contents: &[u8], +-) -> std::io::Result { +- // Unix keeps atomic replacement for existing files too. +- Ok(false) +-} +- +-pub(crate) fn create_config_temporary( +- path: &Path, +- private: bool, +-) -> std::io::Result { +- if !private { +- return std::fs::OpenOptions::new() +- .write(true) +- .create_new(true) +- .open(path); +- } +- use std::os::fd::FromRawFd; +- // Darwin's opaque ACL/filesec APIs (, ) are not +- // exposed by libc. Supply a non-inheriting empty ACL at creation: clearing +- // inherited ACEs later cannot revoke descriptors opened in the meantime. +- unsafe extern "C" { +- fn acl_init(count: libc::c_int) -> *mut libc::c_void; +- fn acl_free(acl: *mut libc::c_void) -> libc::c_int; +- fn acl_get_flagset_np(acl: *mut libc::c_void, flags: *mut *mut libc::c_void) +- -> libc::c_int; +- fn acl_add_flag_np(flags: *mut libc::c_void, flag: libc::c_uint) -> libc::c_int; +- fn filesec_init() -> *mut libc::c_void; +- fn filesec_free(security: *mut libc::c_void); +- fn filesec_set_property( +- security: *mut libc::c_void, +- property: libc::c_int, +- value: *const libc::c_void, +- ) -> libc::c_int; +- fn openx_np( +- path: *const libc::c_char, +- flags: libc::c_int, +- security: *mut libc::c_void, +- ) -> libc::c_int; +- } +- const FILESEC_MODE: libc::c_int = 4; +- const FILESEC_ACL: libc::c_int = 5; +- const ACL_FLAG_NO_INHERIT: libc::c_uint = 1 << 17; +- let path = +- std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(std::io::Error::other)?; +- let acl = unsafe { acl_init(0) }; +- if acl.is_null() { +- return Err(std::io::Error::last_os_error()); +- } +- let security = unsafe { filesec_init() }; +- if security.is_null() { +- let error = std::io::Error::last_os_error(); +- unsafe { +- acl_free(acl); +- } +- return Err(error); +- } +- let result = (|| { +- let mut flags = std::ptr::null_mut(); +- let mode: libc::mode_t = 0o600; +- if unsafe { acl_get_flagset_np(acl, &mut flags) } != 0 +- || unsafe { acl_add_flag_np(flags, ACL_FLAG_NO_INHERIT) } != 0 +- || unsafe { +- filesec_set_property(security, FILESEC_MODE, std::ptr::from_ref(&mode).cast()) +- } != 0 +- || unsafe { +- filesec_set_property(security, FILESEC_ACL, std::ptr::from_ref(&acl).cast()) +- } != 0 +- { +- return Err(std::io::Error::last_os_error()); +- } +- let fd = unsafe { +- openx_np( +- path.as_ptr(), +- libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC, +- security, +- ) +- }; +- if fd < 0 { +- return Err(std::io::Error::last_os_error()); +- } +- // The successful exclusive create returns one owned descriptor. +- Ok(unsafe { std::fs::File::from_raw_fd(fd) }) +- })(); +- unsafe { +- filesec_free(security); +- acl_free(acl); +- } +- result +-} +- +-pub(crate) fn write_config_temporary( +- source: Option<&Path>, +- temporary: &Path, +- contents: &[u8], +-) -> std::io::Result<()> { +- use std::os::{fd::AsRawFd, unix::fs::MetadataExt}; +- let mut output = std::fs::OpenOptions::new() +- .write(true) +- .truncate(true) +- .open(temporary)?; +- if let Some(source) = source { +- let input = std::fs::File::open(source)?; +- let metadata = input.metadata()?; +- let current = output.metadata()?; +- if (metadata.uid(), metadata.gid()) != (current.uid(), current.gid()) +- && unsafe { libc::fchown(output.as_raw_fd(), metadata.uid(), metadata.gid()) } != 0 +- { +- return Err(std::io::Error::last_os_error()); +- } +- // Prepare access controls while the temporary is still empty. Copy ACLs +- // before mode bits so no inherited/default grant can expose the content. +- // Do not copy data or old timestamps. +- if unsafe { +- libc::fcopyfile( +- input.as_raw_fd(), +- output.as_raw_fd(), +- std::ptr::null_mut(), +- libc::COPYFILE_ACL | libc::COPYFILE_XATTR, +- ) +- } != 0 +- { +- return Err(std::io::Error::last_os_error()); +- } +- output.set_permissions(metadata.permissions())?; +- } +- output.write_all(contents)?; +- output.sync_all() +-} ++pub(crate) use super::darwin_config::*; + + const PROC_PGRP_ONLY: u32 = 2; + const SERVER_NOFILE_LIMIT_TARGET: libc::rlim_t = 8192; +--- /dev/null ++++ b/src/platform/darwin_config.rs +@@ -0,0 +1,143 @@ ++use std::io::Write; ++use std::os::unix::ffi::OsStrExt; ++use std::path::Path; ++ ++pub(crate) fn config_file_link_count(path: &Path) -> std::io::Result { ++ use std::os::unix::fs::MetadataExt; ++ Ok(std::fs::metadata(path)?.nlink()) ++} ++ ++pub(crate) fn check_config_write_target(_target: &std::path::Path) -> std::io::Result<()> { ++ Ok(()) ++} ++ ++pub(crate) fn write_existing_config( ++ _target: &std::path::Path, ++ _contents: &[u8], ++) -> std::io::Result { ++ // Unix keeps atomic replacement for existing files too. ++ Ok(false) ++} ++ ++pub(crate) fn create_config_temporary( ++ path: &Path, ++ private: bool, ++) -> std::io::Result { ++ if !private { ++ return std::fs::OpenOptions::new() ++ .write(true) ++ .create_new(true) ++ .open(path); ++ } ++ use std::os::fd::FromRawFd; ++ // Darwin's opaque ACL/filesec APIs (, ) are not ++ // exposed by libc. Supply a non-inheriting empty ACL at creation: clearing ++ // inherited ACEs later cannot revoke descriptors opened in the meantime. ++ unsafe extern "C" { ++ fn acl_init(count: libc::c_int) -> *mut libc::c_void; ++ fn acl_free(acl: *mut libc::c_void) -> libc::c_int; ++ fn acl_get_flagset_np(acl: *mut libc::c_void, flags: *mut *mut libc::c_void) ++ -> libc::c_int; ++ fn acl_add_flag_np(flags: *mut libc::c_void, flag: libc::c_uint) -> libc::c_int; ++ fn filesec_init() -> *mut libc::c_void; ++ fn filesec_free(security: *mut libc::c_void); ++ fn filesec_set_property( ++ security: *mut libc::c_void, ++ property: libc::c_int, ++ value: *const libc::c_void, ++ ) -> libc::c_int; ++ fn openx_np( ++ path: *const libc::c_char, ++ flags: libc::c_int, ++ security: *mut libc::c_void, ++ ) -> libc::c_int; ++ } ++ const FILESEC_MODE: libc::c_int = 4; ++ const FILESEC_ACL: libc::c_int = 5; ++ const ACL_FLAG_NO_INHERIT: libc::c_uint = 1 << 17; ++ let path = ++ std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(std::io::Error::other)?; ++ let acl = unsafe { acl_init(0) }; ++ if acl.is_null() { ++ return Err(std::io::Error::last_os_error()); ++ } ++ let security = unsafe { filesec_init() }; ++ if security.is_null() { ++ let error = std::io::Error::last_os_error(); ++ unsafe { ++ acl_free(acl); ++ } ++ return Err(error); ++ } ++ let result = (|| { ++ let mut flags = std::ptr::null_mut(); ++ let mode: libc::mode_t = 0o600; ++ if unsafe { acl_get_flagset_np(acl, &mut flags) } != 0 ++ || unsafe { acl_add_flag_np(flags, ACL_FLAG_NO_INHERIT) } != 0 ++ || unsafe { ++ filesec_set_property(security, FILESEC_MODE, std::ptr::from_ref(&mode).cast()) ++ } != 0 ++ || unsafe { ++ filesec_set_property(security, FILESEC_ACL, std::ptr::from_ref(&acl).cast()) ++ } != 0 ++ { ++ return Err(std::io::Error::last_os_error()); ++ } ++ let fd = unsafe { ++ openx_np( ++ path.as_ptr(), ++ libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC, ++ security, ++ ) ++ }; ++ if fd < 0 { ++ return Err(std::io::Error::last_os_error()); ++ } ++ // The successful exclusive create returns one owned descriptor. ++ Ok(unsafe { std::fs::File::from_raw_fd(fd) }) ++ })(); ++ unsafe { ++ filesec_free(security); ++ acl_free(acl); ++ } ++ result ++} ++ ++pub(crate) fn write_config_temporary( ++ source: Option<&Path>, ++ temporary: &Path, ++ contents: &[u8], ++) -> std::io::Result<()> { ++ use std::os::{fd::AsRawFd, unix::fs::MetadataExt}; ++ let mut output = std::fs::OpenOptions::new() ++ .write(true) ++ .truncate(true) ++ .open(temporary)?; ++ if let Some(source) = source { ++ let input = std::fs::File::open(source)?; ++ let metadata = input.metadata()?; ++ let current = output.metadata()?; ++ if (metadata.uid(), metadata.gid()) != (current.uid(), current.gid()) ++ && unsafe { libc::fchown(output.as_raw_fd(), metadata.uid(), metadata.gid()) } != 0 ++ { ++ return Err(std::io::Error::last_os_error()); ++ } ++ // Prepare access controls while the temporary is still empty. Copy ACLs ++ // before mode bits so no inherited/default grant can expose the content. ++ // Do not copy data or old timestamps. ++ if unsafe { ++ libc::fcopyfile( ++ input.as_raw_fd(), ++ output.as_raw_fd(), ++ std::ptr::null_mut(), ++ libc::COPYFILE_ACL | libc::COPYFILE_XATTR, ++ ) ++ } != 0 ++ { ++ return Err(std::io::Error::last_os_error()); ++ } ++ output.set_permissions(metadata.permissions())?; ++ } ++ output.write_all(contents)?; ++ output.sync_all() ++} +--- a/src/platform/mod.rs ++++ b/src/platform/mod.rs +@@ -347,6 +347,20 @@ + mod linux; + #[cfg(target_os = "linux")] + pub use linux::*; ++ ++#[cfg(any(target_os = "macos", target_os = "ios"))] ++mod darwin_config; ++#[cfg(target_os = "ios")] ++pub(crate) use darwin_config::*; ++#[cfg(target_os = "ios")] ++pub(crate) use unix_common::{ ++ shutdown_client_stream, wait_client_stream_readable, write_client_stream, ClientStreamReader, ++}; ++#[cfg(target_os = "ios")] ++pub fn foreground_process_group_id_for_tty_fd(fd: std::os::fd::RawFd) -> Option { ++ let pgid = unsafe { libc::tcgetpgrp(fd) }; ++ (pgid > 0).then_some(pgid as u32) ++} + + #[cfg(target_os = "macos")] + mod macos; diff --git a/Herdr/native/runtime.patch b/Herdr/native/runtime.patch new file mode 100644 index 00000000..bdb96867 --- /dev/null +++ b/Herdr/native/runtime.patch @@ -0,0 +1,1779 @@ +--- a/src/terminal_notify.rs ++++ b/src/terminal_notify.rs +@@ -49,7 +49,7 @@ + sequence + }; + +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + stdout.write_all(&sequence)?; + stdout.flush()?; + Ok(true) +--- a/src/update.rs ++++ b/src/update.rs +@@ -1127,7 +1127,7 @@ + plans: &[RunningServerUpdatePlan], + release: &ReleaseInfo, + ) -> Result { +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + return Err( + "one or more Herdr sessions must stop for this update. Stop running Herdr sessions when ready, then run `herdr update` again from an interactive terminal." + .to_string(), +@@ -1151,12 +1151,12 @@ + + loop { + eprint!("stop after installing? [y/N] "); +- io::stderr() ++ crate::host_io::stderr() + .flush() + .map_err(|e| format!("failed to flush prompt: {e}"))?; + + let mut input = String::new(); +- let read = io::stdin() ++ let read = crate::host_io::stdin() + .read_line(&mut input) + .map_err(|e| format!("failed to read prompt response: {e}"))?; + if read == 0 { +@@ -1253,7 +1253,7 @@ + return Ok(true); + } + +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + return Ok(false); + } + +@@ -1280,12 +1280,12 @@ + noun, + release.label() + ); +- io::stderr() ++ crate::host_io::stderr() + .flush() + .map_err(|e| format!("failed to flush prompt: {e}"))?; + + let mut input = String::new(); +- let read = io::stdin() ++ let read = crate::host_io::stdin() + .read_line(&mut input) + .map_err(|e| format!("failed to read prompt response: {e}"))?; + if read == 0 { +@@ -1410,7 +1410,7 @@ + ); + eprintln!("stopping the old server will exit its pane processes."); + +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + eprintln!( + "not stopping the old server from a non-interactive update; run `{}` when you are ready.", + plan.stop_command() +@@ -1420,12 +1420,12 @@ + + loop { + eprint!("stop the old server now? [y/N] "); +- io::stderr() ++ crate::host_io::stderr() + .flush() + .map_err(|e| format!("failed to flush prompt: {e}"))?; + + let mut input = String::new(); +- let read = io::stdin() ++ let read = crate::host_io::stdin() + .read_line(&mut input) + .map_err(|e| format!("failed to read prompt response: {e}"))?; + if read == 0 { +@@ -3103,7 +3103,7 @@ + #[test] + fn plain_update_defers_stop_prompt_until_after_install() { + assert!( +- !io::stdin().is_terminal(), ++ !crate::host_io::stdin().is_terminal(), + "this test relies on noninteractive test stdin" + ); + let release = fake_release("9.8.7", Some(77)); +@@ -3306,7 +3306,7 @@ + fn noninteractive_plain_update_does_not_complete_with_running_server() { + let _guard = env_lock().lock().unwrap(); + assert!( +- !io::stdin().is_terminal(), ++ !crate::host_io::stdin().is_terminal(), + "this test relies on noninteractive test stdin" + ); + std::env::set_var(crate::session::SESSION_ENV_VAR, "work"); +@@ -3362,7 +3362,7 @@ + #[test] + fn noninteractive_plain_update_completes_with_compatible_server() { + assert!( +- !io::stdin().is_terminal(), ++ !crate::host_io::stdin().is_terminal(), + "this test relies on noninteractive test stdin" + ); + let release = fake_release("9.8.7", Some(77)); +--- a/src/selection.rs ++++ b/src/selection.rs +@@ -364,8 +364,8 @@ + } + + let sequence = osc52_sequence(bytes); +- let _ = std::io::stdout().write_all(sequence.as_bytes()); +- let _ = std::io::stdout().flush(); ++ let _ = crate::host_io::stdout().write_all(sequence.as_bytes()); ++ let _ = crate::host_io::stdout().flush(); + } + + #[cfg(test)] +--- a/src/main.rs ++++ b/src/main.rs +@@ -14,6 +14,9 @@ + } + #[cfg(target_os = "ios")] + mod ios_entry; ++mod host_io; ++#[cfg(target_os = "ios")] ++mod ios_ipc; + + use std::io; + +@@ -486,7 +489,7 @@ + eprintln!("see configuration if you want to enable it."); + eprintln!(); + eprintln!("\x1b[2m\"{}\"\x1b[0m", random_nested_message()); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + } + +@@ -505,16 +508,16 @@ + + fn finish_cli(outcome: io::Result) -> io::Result<()> { + match outcome { +- Ok(cli::CommandOutcome::Handled(code)) => std::process::exit(code), ++ Ok(cli::CommandOutcome::Handled(code)) => crate::host_io::exit(code), + Ok(cli::CommandOutcome::NotCli) => Ok(()), +- Err(err) if cli::protocol_mismatch_was_reported(&err) => std::process::exit(1), ++ Err(err) if cli::protocol_mismatch_was_reported(&err) => crate::host_io::exit(1), + Err(err) if cli::server_not_running_was_reported(&err) => { + if let Some(response) = cli::server_not_running_reported_response(&err) { + if let Ok(json) = serde_json::to_string(response) { + eprintln!("{json}"); + } + } +- std::process::exit(1); ++ crate::host_io::exit(1); + } + Err(err) => Err(err), + } +@@ -526,7 +529,7 @@ + Err(err) => { + eprintln!("error: {err}"); + eprintln!("run 'herdr --help' for usage"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + }; + run_main(raw_args) +@@ -542,7 +545,7 @@ + Err(err) => { + eprintln!("error: {err}"); + eprintln!("run 'herdr --help' for usage"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + }; + #[cfg(target_os = "ios")] +@@ -552,7 +555,7 @@ + Err(err) => { + eprintln!("error: {err}"); + eprintln!("run 'herdr --help' for usage"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + }; + +@@ -567,7 +570,7 @@ + { + eprintln!("error: --remote can only be used with the default launch command"); + eprintln!("run 'herdr --help' for usage"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + + finish_cli(cli::maybe_run(&args))?; +@@ -597,12 +600,12 @@ + Ok(options) => options, + Err(err) if err.starts_with("usage:") => { + eprintln!("{err}"); +- std::process::exit(0); ++ crate::host_io::exit(0); + } + Err(err) => { + eprintln!("{err}"); + eprintln!("usage: herdr update [--handoff]"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + }; + match update::self_update(options) { +@@ -613,7 +616,7 @@ + } else { + eprintln!("update failed: {e}"); + } +- std::process::exit(1); ++ crate::host_io::exit(1); + } + } + } +@@ -773,7 +776,7 @@ + if arg.starts_with('-') && !known_flags.contains(&arg_name) { + eprintln!("unknown option: {arg}"); + eprintln!("run 'herdr --help' for usage"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + if !arg.starts_with('-') + && ![ +@@ -795,7 +798,7 @@ + { + eprintln!("unknown command: {arg}"); + eprintln!("run 'herdr --help' for usage"); +- std::process::exit(2); ++ crate::host_io::exit(2); + } + } + +@@ -804,7 +807,7 @@ + if let Err(err) = remote::run_remote(remote_launch) { + eprintln!("error: {err}"); + remote::print_remote_error_hint(&err, &remote_target); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + return Ok(()); + } +@@ -816,7 +819,7 @@ + client::endpoint::EndpointCatalog::load().is_ok_and(|catalog| catalog.has_enabled_ssh()); + if let Err(err) = server::autodetect::auto_detect_launch(saved_federation) { + eprintln!("herdr: {err}"); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + Ok(()) + } +--- a/src/platform/unix_common.rs ++++ b/src/platform/unix_common.rs +@@ -162,11 +162,11 @@ + use interprocess::TryClone as _; + + let activity = idle_timeout.map(Activity::start).transpose()?; +- let mut stdout = TrackedIo::new(std::io::stdout().lock(), activity.clone()); ++ let mut stdout = TrackedIo::new(crate::host_io::stdout().lock(), activity.clone()); + let mut socket_to_stdout = TrackedIo::new(stream.try_clone()?, activity.clone()); + let mut stdin_to_socket = stream; + let _upload = std::thread::spawn(move || { +- let mut stdin = TrackedIo::new(std::io::stdin(), activity.clone()); ++ let mut stdin = TrackedIo::new(crate::host_io::stdin(), activity.clone()); + let _ = copy_flush( + &mut stdin, + &mut TrackedIo::new(&mut stdin_to_socket, activity), +@@ -239,6 +239,9 @@ + } + + pub(super) fn read_terminal_grid_size() -> std::io::Result<(u16, u16)> { ++ #[cfg(target_os = "ios")] ++ return crate::ios_entry::grid_size(); ++ #[cfg(not(target_os = "ios"))] + crossterm::terminal::window_size().map(|size| (size.columns, size.rows)) + } + +--- a/src/platform/fallback.rs ++++ b/src/platform/fallback.rs +@@ -22,11 +22,11 @@ + ) -> std::io::Result<()> { + use interprocess::TryClone as _; + +- let mut stdout = std::io::stdout().lock(); ++ let mut stdout = crate::host_io::stdout().lock(); + let mut socket_to_stdout = stream.try_clone()?; + let mut stdin_to_socket = stream; + let _upload = std::thread::spawn(move || { +- let mut stdin = std::io::stdin(); ++ let mut stdin = crate::host_io::stdin(); + let _ = std::io::copy(&mut stdin, &mut stdin_to_socket); + }); + std::io::copy(&mut socket_to_stdout, &mut stdout).map(|_| ()) +@@ -124,7 +124,7 @@ + } + + pub(crate) fn should_query_host_terminal_palette() -> bool { +- false ++ cfg!(target_os = "ios") + } + + pub(crate) fn hostname() -> Option { +--- a/src/platform/windows.rs ++++ b/src/platform/windows.rs +@@ -74,13 +74,13 @@ + use interprocess::TryClone as _; + use std::sync::atomic::{AtomicBool, Ordering}; + +- let mut stdout = std::io::stdout().lock(); ++ let mut stdout = crate::host_io::stdout().lock(); + let mut socket_to_stdout = stream.try_clone()?; + let mut stdin_to_socket = stream; + let upload_done = Arc::new(AtomicBool::new(false)); + let upload_done_worker = Arc::clone(&upload_done); + let _upload = std::thread::spawn(move || { +- let mut stdin = std::io::stdin(); ++ let mut stdin = crate::host_io::stdin(); + let _ = copy_flush(&mut stdin, &mut stdin_to_socket); + upload_done_worker.store(true, Ordering::Release); + }); +--- a/src/platform/remote_bridge.rs ++++ b/src/platform/remote_bridge.rs +@@ -42,7 +42,7 @@ + if expired { + // Only the dedicated bridge process owns this watchdog. Returning from a + // blocked copy cannot guarantee shutdown, and joining it could hang forever. +- std::process::exit(1); ++ crate::host_io::exit(1); + } + } + })?; +--- a/src/cli/spec.rs ++++ b/src/cli/spec.rs +@@ -67,7 +67,7 @@ + } + + pub(super) fn print_requested_help(args: &[String]) -> std::io::Result { +- let mut stdout = std::io::stdout().lock(); ++ let mut stdout = crate::host_io::stdout().lock(); + write_requested_help(args, &mut stdout, crate::platform::begin_cli_output) + } + +--- a/src/cli/completion.rs ++++ b/src/cli/completion.rs +@@ -36,10 +36,10 @@ + std::io::Error::new(std::io::ErrorKind::InvalidData, err.utf8_error()) + })?; + crate::platform::begin_cli_output(); +- std::io::stdout().write_all(space_separated_zsh_long_options(&script).as_bytes())?; ++ crate::host_io::stdout().write_all(space_separated_zsh_long_options(&script).as_bytes())?; + } else { + crate::platform::begin_cli_output(); +- generate(shell, &mut command, "herdr", &mut std::io::stdout()); ++ generate(shell, &mut command, "herdr", &mut crate::host_io::stdout()); + } + Ok(0) + } +--- a/src/cli/plugin.rs ++++ b/src/cli/plugin.rs +@@ -206,7 +206,7 @@ + } + }; + +- if !yes && !io::stdin().is_terminal() { ++ if !yes && !crate::host_io::stdin().is_terminal() { + eprintln!("remote plugin install requires --yes when stdin is not interactive"); + return Ok(2); + } +@@ -1579,9 +1579,9 @@ + + fn confirm(prompt: &str) -> std::io::Result { + eprint!("{prompt} [y/N] "); +- io::stderr().flush()?; ++ crate::host_io::stderr().flush()?; + let mut line = String::new(); +- io::stdin().read_line(&mut line)?; ++ crate::host_io::stdin().read_line(&mut line)?; + Ok(matches!(line.trim(), "y" | "Y" | "yes" | "YES" | "Yes")) + } + +--- a/src/cli/machine.rs ++++ b/src/cli/machine.rs +@@ -190,7 +190,7 @@ + return Ok(2); + } + }; +- if !std::io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + eprintln!("reconnect requires an interactive terminal; use herdr machine status for noninteractive checks"); + return Ok(2); + } +@@ -310,7 +310,7 @@ + }; + let mut setup = None; + let session = +- if session.is_none() && std::io::stdin().is_terminal() && std::io::stderr().is_terminal() { ++ if session.is_none() && crate::host_io::stdin().is_terminal() && crate::host_io::stderr().is_terminal() { + let discovered = (|| { + let connection = crate::remote::SavedSshSetup::connect(&target)?; + let sessions = connection.running_sessions()?; +@@ -398,7 +398,7 @@ + } + + let _raw_mode = RawModeGuard::enable()?; +- let mut output = std::io::stderr(); ++ let mut output = crate::host_io::stderr(); + let mut selected = 0; + render_remote_session_picker(&mut output, target, sessions, selected, false)?; + loop { +--- a/src/client/shell_runtime.rs ++++ b/src/client/shell_runtime.rs +@@ -97,7 +97,7 @@ + if desired == state.keyboard_report_all_active { + return Ok(()); + } +- crate::terminal_modes::set_host_kitty_keyboard_report_all(&mut io::stdout(), desired) ++ crate::terminal_modes::set_host_kitty_keyboard_report_all(&mut crate::host_io::stdout(), desired) + .map_err(ClientError::ConnectionFailed)?; + state.keyboard_report_all_active = desired; + Ok(()) +@@ -127,7 +127,7 @@ + + state.pane_keyboard_report_all = false; + let _ = sync_client_shell_keyboard_report_all(state); +- let _ = crate::terminal_effects::write_window_title(&mut std::io::stdout(), None); ++ let _ = crate::terminal_effects::write_window_title(&mut crate::host_io::stdout(), None); + } + + pub(super) fn apply_client_shell_input_source_changes( +--- a/src/client/handshake.rs ++++ b/src/client/handshake.rs +@@ -92,7 +92,7 @@ + || is_ssh_session() + || std::env::var_os("TMUX").is_some() + || std::env::var_os("STY").is_some(), +- io::stdin().is_terminal() && io::stdout().is_terminal(), ++ crate::host_io::stdin().is_terminal() && crate::host_io::stdout().is_terminal(), + ) + } + +--- a/src/client/terminal_sessions.rs ++++ b/src/client/terminal_sessions.rs +@@ -42,7 +42,7 @@ + + let mut write_stream = stream.try_clone()?; + let _input_thread = std::thread::spawn(move || { +- let stdin = io::stdin(); ++ let stdin = crate::host_io::stdin(); + for line in stdin.lock().lines() { + let Ok(line) = line else { + break; +@@ -85,7 +85,7 @@ + Ok(stream) => stream, + Err(err) => { + eprintln!("herdr: {}", ClientError::ConnectionFailed(err)); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + }; + +@@ -108,11 +108,11 @@ + "herdr: terminal session observe negotiated unsupported encoding {:?}", + handshake.encoding + ); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + Err(err) => { + eprintln!("herdr: {err}"); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + } + +@@ -121,7 +121,7 @@ + } + + fn write_terminal_session_output(mut stream: LocalStream) -> io::Result<()> { +- let mut stdout = io::stdout().lock(); ++ let mut stdout = crate::host_io::stdout().lock(); + loop { + match protocol::read_message(&mut stream, MAX_GRAPHICS_FRAME_SIZE) { + Ok(ServerMessage::Terminal(frame)) => { +--- a/src/client/terminal_setup.rs ++++ b/src/client/terminal_setup.rs +@@ -45,7 +45,10 @@ + enable_client_protocols: bool, + mouse_capture: bool, + ) -> io::Result { ++ #[cfg(not(target_os = "ios"))] + ratatui::init(); ++ #[cfg(target_os = "ios")] ++ crate::ios_entry::terminal_start()?; + let mut terminal_guard = TerminalGuard { + host_escape_disambiguation_active: false, + buffered_host_input: Vec::new(), +@@ -57,7 +60,7 @@ + #[cfg(windows)] + restore_windows_input_mode: Arc::new(WindowsInputModeRestore::default()), + }; +- crate::terminal_modes::clear_host_mouse_reporting(&mut io::stdout())?; ++ crate::terminal_modes::clear_host_mouse_reporting(&mut crate::host_io::stdout())?; + let host_color_scheme_reports = + should_enable_host_color_scheme_reports(enable_client_protocols); + #[cfg(windows)] +@@ -78,18 +81,18 @@ + push_keyboard_enhancement_flags()?; + let (active, buffered_input) = query_host_escape_disambiguation(); + set_mouse_capture(mouse_capture, false)?; +- execute!(io::stdout(), EnableBracketedPaste, EnableFocusChange)?; ++ execute!(crate::host_io::stdout(), EnableBracketedPaste, EnableFocusChange)?; + if host_color_scheme_reports { + terminal_guard.reset_host_color_scheme_reports = true; +- write_host_color_scheme_report_mode(&mut io::stdout(), true)?; ++ write_host_color_scheme_report_mode(&mut crate::host_io::stdout(), true)?; + } + (active, buffered_input) + } else { + if should_enable_host_color_scheme_reports(true) { +- write_host_color_scheme_report_mode(&mut io::stdout(), false)?; ++ write_host_color_scheme_report_mode(&mut crate::host_io::stdout(), false)?; + } + set_mouse_capture(mouse_capture, false)?; +- execute!(io::stdout(), EnableBracketedPaste)?; ++ execute!(crate::host_io::stdout(), EnableBracketedPaste)?; + (false, Vec::new()) + }; + +@@ -107,7 +110,7 @@ + && windows_virtual_terminal_input.active + && windows_win32_input_mode_enabled() + { +- enable_windows_win32_input_mode(&mut io::stdout())?; ++ enable_windows_win32_input_mode(&mut crate::host_io::stdout())?; + } + + let modify_other_keys_mode = enable_client_protocols +@@ -115,11 +118,11 @@ + .flatten(); + if let Some(mode) = modify_other_keys_mode { + terminal_guard.reset_modify_other_keys = true; +- io::stdout().write_all(mode.set_sequence())?; +- io::stdout().flush()?; +- } +- +- execute!(io::stdout(), DisableLineWrap)?; ++ crate::host_io::stdout().write_all(mode.set_sequence())?; ++ crate::host_io::stdout().flush()?; ++ } ++ ++ execute!(crate::host_io::stdout(), DisableLineWrap)?; + + terminal_guard.host_escape_disambiguation_active = host_escape_disambiguation_active; + terminal_guard.buffered_host_input = buffered_host_input; +@@ -160,16 +163,16 @@ + const QUERY: &[u8] = b"\x1b[?u\x1b[c"; + + let mut buffered_input = Vec::new(); +- if let Err(err) = io::stdout() ++ if let Err(err) = crate::host_io::stdout() + .write_all(QUERY) +- .and_then(|()| io::stdout().flush()) ++ .and_then(|()| crate::host_io::stdout().flush()) + { + tracing::debug!(%err, "host keyboard enhancement query unavailable"); + return (false, buffered_input); + } + + // Bypass StdinLock's shared buffer so poll and read observe the same bytes. +- let stdin = io::stdin(); ++ let stdin = crate::host_io::stdin(); + let stdin_fd = stdin.as_raw_fd(); + let deadline = Instant::now() + HOST_KEYBOARD_QUERY_TIMEOUT; + let mut responses = HostKeyboardProbeResponses::default(); +@@ -349,7 +352,11 @@ + )?; + } + // Restore a visible cursor and reset DECSCUSR back to the terminal default. ++ #[cfg(not(target_os = "ios"))] + writer.write_all(b"\x1b[?25h\x1b[0 q")?; ++ // a-Shell owns its cursor style; resetting DECSCUSR would enable blinking. ++ #[cfg(target_os = "ios")] ++ writer.write_all(b"\x1b[?25h")?; + writer.flush() + } + +@@ -563,34 +570,34 @@ + #[cfg(windows)] + if windows_uses_vt_mouse_reporting() { + if !enabled { +- crate::terminal_modes::clear_host_mouse_reporting(&mut io::stdout())?; ++ crate::terminal_modes::clear_host_mouse_reporting(&mut crate::host_io::stdout())?; + } + return crate::terminal_modes::set_windows_mouse_reporting( +- &mut io::stdout(), ++ &mut crate::host_io::stdout(), + enabled, + sgr_pixels, + ); + } + #[cfg(windows)] +- return set_windows_native_mouse_capture(&mut io::stdout(), enabled, sgr_pixels, |enabled| { ++ return set_windows_native_mouse_capture(&mut crate::host_io::stdout(), enabled, sgr_pixels, |enabled| { + if enabled { +- execute!(io::stdout(), EnableMouseCapture) ++ execute!(crate::host_io::stdout(), EnableMouseCapture) + } else { + disable_windows_native_mouse_capture() + } + }); + #[cfg(not(windows))] +- crate::terminal_modes::clear_host_mouse_reporting(&mut io::stdout())?; ++ crate::terminal_modes::clear_host_mouse_reporting(&mut crate::host_io::stdout())?; + #[cfg(not(windows))] + if enabled { +- execute!(io::stdout(), EnableMouseCapture)?; ++ execute!(crate::host_io::stdout(), EnableMouseCapture)?; + if sgr_pixels { +- io::stdout().write_all(b"\x1b[?1016h")?; +- io::stdout().flush()?; ++ crate::host_io::stdout().write_all(b"\x1b[?1016h")?; ++ crate::host_io::stdout().flush()?; + } + Ok(()) + } else { +- match execute!(io::stdout(), DisableMouseCapture) { ++ match execute!(crate::host_io::stdout(), DisableMouseCapture) { + Ok(()) => Ok(()), + Err(err) => Err(err), + } +@@ -599,7 +606,7 @@ + + #[cfg(windows)] + fn disable_windows_native_mouse_capture() -> io::Result<()> { +- match execute!(io::stdout(), DisableMouseCapture) { ++ match execute!(crate::host_io::stdout(), DisableMouseCapture) { + Ok(()) => Ok(()), + Err(err) if err.to_string() == "Initial console modes not set" => Ok(()), + Err(err) => Err(err), +@@ -633,12 +640,12 @@ + reset_host_color_scheme_reports: bool, + #[cfg(windows)] restore_windows_input_mode: Option, + ) -> io::Result<()> { +- let _ = clear_received_kitty_graphics(&mut io::stdout()); ++ let _ = clear_received_kitty_graphics(&mut crate::host_io::stdout()); + + // Reset modifyOtherKeys if we enabled it. + if reset_modify_other_keys { +- let _ = io::stdout().write_all(b"\x1b[>4;0m"); +- let _ = io::stdout().flush(); ++ let _ = crate::host_io::stdout().write_all(b"\x1b[>4;0m"); ++ let _ = crate::host_io::stdout().flush(); + } + + if reset_keyboard_enhancements { +@@ -646,7 +653,7 @@ + } + + let _ = execute!( +- io::stdout(), ++ crate::host_io::stdout(), + EnableLineWrap, + DisableFocusChange, + DisableBracketedPaste +@@ -661,13 +668,17 @@ + let _ = disable_windows_native_mouse_capture(); + } + ++ #[cfg(not(target_os = "ios"))] + let restore_result = ratatui::try_restore(); ++ #[cfg(target_os = "ios")] ++ // The host command guard restores the screen after render/input threads join. ++ let restore_result: io::Result<()> = Ok(()); + let postlude_result = +- write_terminal_restore_postlude(&mut io::stdout(), reset_host_color_scheme_reports); ++ write_terminal_restore_postlude(&mut crate::host_io::stdout(), reset_host_color_scheme_reports); + + #[cfg(windows)] + if windows_vti_input_backend_enabled() && windows_win32_input_mode_enabled() { +- let _ = disable_windows_win32_input_mode(&mut io::stdout()); ++ let _ = disable_windows_win32_input_mode(&mut crate::host_io::stdout()); + } + + restore_result.and(postlude_result) +@@ -676,7 +687,7 @@ + #[cfg(not(windows))] + fn push_keyboard_enhancement_flags() -> io::Result<()> { + execute!( +- io::stdout(), ++ crate::host_io::stdout(), + PushKeyboardEnhancementFlags(crate::input::ime_compatible_keyboard_enhancement_flags()) + ) + } +@@ -688,7 +699,7 @@ + + #[cfg(not(windows))] + fn pop_keyboard_enhancement_flags() -> io::Result<()> { +- execute!(io::stdout(), PopKeyboardEnhancementFlags) ++ execute!(crate::host_io::stdout(), PopKeyboardEnhancementFlags) + } + + #[cfg(windows)] +@@ -732,7 +743,7 @@ + ) + .active; + if active && windows_win32_input_mode_enabled() { +- enable_windows_win32_input_mode(&mut io::stdout())?; ++ enable_windows_win32_input_mode(&mut crate::host_io::stdout())?; + } + Ok(()) + } +--- a/src/client/mod.rs ++++ b/src/client/mod.rs +@@ -167,7 +167,7 @@ + // client initializes the terminal, so defer the host mouse reset to + // `setup_terminal_with_capabilities` instead of emitting raw escapes early. + #[cfg(not(windows))] +- crate::terminal_modes::clear_host_mouse_reporting(&mut io::stdout())?; ++ crate::terminal_modes::clear_host_mouse_reporting(&mut crate::host_io::stdout())?; + let client_rendered_shell = attach_request.is_none(); + let socket_path = client_socket_path(); + let keybinding_source = client_shell_keybinding_source(); +@@ -311,6 +311,8 @@ + loop_config.initial_host_input = terminal_guard.take_buffered_host_input(); + + // Install a panic hook so the foreground client always restores its terminal. ++ #[cfg(not(target_os = "ios"))] ++ { + let panic_restore = terminal_guard.panic_restore(); + let original_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { +@@ -318,6 +320,8 @@ + original_hook(info); + })); + ++ } ++ + // Create the tokio runtime. + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() +@@ -328,6 +332,8 @@ + + // ctrlc's "termination" feature also catches SIGTERM/SIGHUP so direct + // termination signals still run the quit path and TerminalGuard::Drop. ++ #[cfg(not(target_os = "ios"))] ++ { + let quit_flag = should_quit.clone(); + if let Err(err) = ctrlc::set_handler(move || { + quit_flag.store(true, Ordering::Release); +@@ -335,6 +341,10 @@ + warn!(%err, "failed to install termination handler; terminal restore relies on TerminalGuard::Drop and the panic hook"); + } + ++ } ++ #[cfg(target_os = "ios")] ++ crate::ios_entry::remember_client_quit(should_quit.clone()); ++ let client_quit = should_quit.clone(); + let result = rt.block_on(async { + run_client_loop( + initial, +@@ -352,11 +362,12 @@ + .await + }); + ++ client_quit.store(true, Ordering::Release); + // Restore the terminal before printing any final status message. + let terminal_restore_failed = terminal_guard.restore().is_err(); + + if let Err(err) = result { +- let _ = writeln!(io::stderr(), "herdr: {err}"); ++ let _ = writeln!(crate::host_io::stderr(), "herdr: {err}"); + rt.shutdown_timeout(Duration::from_millis(100)); + crate::logging::shutdown("client"); + +@@ -372,7 +383,7 @@ + return Ok(()); + } + +- std::process::exit(1); ++ crate::host_io::exit(1); + } + + rt.shutdown_timeout(Duration::from_millis(100)); +@@ -536,7 +547,11 @@ + .lock() + .map(|matcher| matcher.active_handle()) + .unwrap_or_default(); +- std::thread::spawn(move || { ++ #[cfg(target_os = "ios")] ++ use crate::ios_entry::spawn_client_thread; ++ #[cfg(not(target_os = "ios"))] ++ use std::thread::spawn as spawn_client_thread; ++ spawn_client_thread(move || { + input::stdin_reader_loop( + stdin_tx, + &stdin_quit, +@@ -572,7 +587,7 @@ + let resize_cell_size = reported_cell_size.clone(); + let pixel_geometry_enabled = state.pixel_geometry_enabled; + let pixel_geometry_fallback = config.pixel_geometry_fallback; +- std::thread::spawn(move || { ++ spawn_client_thread(move || { + resize_poll_loop( + resize_tx, + cols, +@@ -1535,21 +1550,21 @@ + { + record_received_kitty_graphics(&frame.bytes); + } +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + let _ = stdout.write_all(&frame.bytes); + let _ = stdout.flush(); + } + ServerMessage::Graphics { bytes } => { + if state.kitty_graphics_enabled { + record_received_kitty_graphics(&bytes); +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + let _ = stdout.write_all(&bytes); + let _ = stdout.flush(); + } + } + ServerMessage::TerminalBell { count } => { + if let Err(err) = +- crate::terminal_effects::write_terminal_bells(&mut io::stdout(), count) ++ crate::terminal_effects::write_terminal_bells(&mut crate::host_io::stdout(), count) + { + warn!(err = %err, "failed to emit terminal bell"); + } +@@ -1643,7 +1658,7 @@ + &control, + &path, + ); +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + let written = state + .flush_native_cleanup(&mut stdout) + .and_then(|()| stdout.write_all(&command)) +@@ -1921,11 +1936,11 @@ + state.present_frame(frame); + } + } +- let _ = io::stdout().flush(); ++ let _ = crate::host_io::stdout().flush(); + } + ServerMessage::WindowTitle { title } => { + let _ = crate::terminal_effects::write_window_title( +- &mut io::stdout(), ++ &mut crate::host_io::stdout(), + title.as_deref(), + ); + } +@@ -1978,7 +1993,7 @@ + } => { + if state.attach_escape.is_some() { + crate::terminal_modes::set_direct_host_keyboard_protocol( +- &mut io::stdout(), ++ &mut crate::host_io::stdout(), + &mut state.direct_keyboard_protocol, + flags, + modify_other_keys_level, +@@ -2278,7 +2293,7 @@ + // Clean exit (Ctrl+C). Send Detach before closing. + let detach = ClientMessage::Detach; + let _ = write_to_server(&mut write_stream, &detach); +- let _ = io::stdout().flush(); ++ let _ = crate::host_io::stdout().flush(); + + Ok(()) + } +--- a/src/client/state.rs ++++ b/src/client/state.rs +@@ -84,7 +84,7 @@ + fn drop(&mut self) { + if self.attach_escape.is_some() { + let _ = crate::terminal_modes::set_direct_host_keyboard_protocol( +- &mut io::stdout(), ++ &mut crate::host_io::stdout(), + &mut self.direct_keyboard_protocol, + 0, + 0, +@@ -310,7 +310,7 @@ + if self.presentation_frozen || graphics.is_empty() || !self.kitty_graphics_enabled { + return; + } +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + let _ = write_encoded_frame_with_graphics(&mut stdout, &[], graphics); + let _ = stdout.flush(); + } +@@ -349,7 +349,7 @@ + crate::render_prof::duration_since("client_surface_patch.encode", encode_started); + let write_started = crate::render_prof::timer(); + if !encoded.bytes.is_empty() { +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + stdout.write_all(&encoded.bytes)?; + stdout.flush()?; + } +@@ -561,7 +561,7 @@ + } else { + self.blit_encoder.encode(&frame_data, self.repaint_pending) + }; +- let mut stdout = io::stdout(); ++ let mut stdout = crate::host_io::stdout(); + if let Err(error) = self.write_composed_output(&mut stdout, &encoded.bytes, graphics) { + tracing::warn!(%error, "failed to present client frame"); + self.repaint_pending = true; +--- a/src/client/input.rs ++++ b/src/client/input.rs +@@ -90,7 +90,7 @@ + direct_response: Arc>, + direct_response_active: Arc, + ) { +- let stdin = io::stdin(); ++ let stdin = crate::host_io::stdin(); + let mut reader = stdin.lock(); + let mut scratch = [0u8; 4096]; + let mut framer = crate::raw_input::RawInputByteFramer::for_host_input(); +--- a/src/client/terminal_geometry.rs ++++ b/src/client/terminal_geometry.rs +@@ -179,7 +179,7 @@ + + #[cfg(not(windows))] + pub(super) fn query_host_terminal_appearance() { +- let _ = write_host_terminal_appearance_query(io::stdout()); ++ let _ = write_host_terminal_appearance_query(crate::host_io::stdout()); + } + + #[cfg(any(not(windows), test))] +@@ -189,7 +189,7 @@ + } + + pub(super) fn query_host_terminal_theme() { +- let _ = write_host_terminal_theme_query(io::stdout()); ++ let _ = write_host_terminal_theme_query(crate::host_io::stdout()); + } + + pub(super) fn write_host_terminal_theme_query(mut writer: impl io::Write) -> io::Result<()> { +@@ -203,7 +203,7 @@ + const HOST_CELL_SIZE_QUERY: &[u8] = b"\x1b[16t"; + + pub(super) fn query_host_cell_size() { +- let _ = write_host_cell_size_query(io::stdout()); ++ let _ = write_host_cell_size_query(crate::host_io::stdout()); + } + + pub(super) fn should_query_host_cell_size() -> bool { +--- a/src/client/image_files.rs ++++ b/src/client/image_files.rs +@@ -68,8 +68,8 @@ + #[cfg(unix)] + fn environment_allows() -> bool { + allowed( +- std::io::stdin().is_terminal(), +- std::io::stdout().is_terminal(), ++ crate::host_io::stdin().is_terminal(), ++ crate::host_io::stdout().is_terminal(), + |key| std::env::var_os(key), + ) + } +--- a/src/remote/attach.rs ++++ b/src/remote/attach.rs +@@ -1014,7 +1014,7 @@ + let stderr_relay = thread::spawn(move || -> io::Result> { + let mut captured = Vec::new(); + let mut buffer = [0_u8; 8 * 1024]; +- let mut destination = io::stderr(); ++ let mut destination = crate::host_io::stderr(); + + loop { + let read = child_stderr.read(&mut buffer)?; +@@ -1974,7 +1974,7 @@ + let status = match remote_server_status(ssh, remote_herdr, require_surface_interest) { + Ok(status) => status, + Err(err) => { +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + return Err(io::Error::other(format!( + "could not inspect the running remote herdr server on {target} before installing: {err}; run from an interactive terminal to approve updating the remote binary" + ))); +@@ -1983,10 +1983,10 @@ + "could not inspect the running remote herdr server on {target} before installing: {err}" + ); + eprint!("continue installing the remote herdr binary? [y/N] "); +- io::stderr().flush()?; ++ crate::host_io::stderr().flush()?; + + let mut answer = String::new(); +- io::stdin().read_line(&mut answer)?; ++ crate::host_io::stdin().read_line(&mut answer)?; + let answer = answer.trim().to_ascii_lowercase(); + if answer != "y" && answer != "yes" { + return Err(io::Error::new( +@@ -2019,7 +2019,7 @@ + ); + + if plan == RemoteInstallRunningServerPlan::KeepRunning { +- if io::stdin().is_terminal() { ++ if crate::host_io::stdin().is_terminal() { + eprintln!("remote herdr server on {target} is already compatible:"); + eprintln!(" server: v{}", version_label(version.as_deref())); + eprintln!( +@@ -2030,7 +2030,7 @@ + return Ok(false); + } + +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + match plan { + RemoteInstallRunningServerPlan::LiveHandoff => return Ok(false), + RemoteInstallRunningServerPlan::StopRequired(_) => { +@@ -2064,10 +2064,10 @@ + "Install {} and stop the remote server now? [y/N] ", + current_version() + ); +- io::stderr().flush()?; ++ crate::host_io::stderr().flush()?; + + let mut answer = String::new(); +- io::stdin().read_line(&mut answer)?; ++ crate::host_io::stdin().read_line(&mut answer)?; + let answer = answer.trim().to_ascii_lowercase(); + if answer != "y" && answer != "yes" { + return Err(io::Error::new( +@@ -2254,7 +2254,7 @@ + | RemoteServerRestartReason::SurfaceInterest + | RemoteServerRestartReason::HealthCheck + ); +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + if required_upgrade { + return Err(io::Error::other(format!( + "remote herdr server on {target} needs one final update before this client can attach; run from an interactive terminal to approve updating it" +@@ -2302,9 +2302,9 @@ + "restart the remote server now? [y/N] " + }; + eprint!("{prompt}"); +- io::stderr().flush()?; +- +- if read_remote_confirmation(&mut io::stdin().lock(), false)? { ++ crate::host_io::stderr().flush()?; ++ ++ if read_remote_confirmation(&mut crate::host_io::stdin().lock(), false)? { + return Ok(true); + } + if required_upgrade { +@@ -2581,7 +2581,7 @@ + remote_herdr: &RemoteHerdr, + source_description: &str, + ) -> io::Result<()> { +- if !io::stdin().is_terminal() { ++ if !crate::host_io::stdin().is_terminal() { + return Err(io::Error::other(format!( + "matching remote herdr {} is not installed at {}; run from an interactive terminal to approve installation", + current_version(), +@@ -2599,9 +2599,9 @@ + source_description, + remote_herdr.executable.display() + ); +- io::stderr().flush()?; +- +- if !read_remote_confirmation(&mut io::stdin().lock(), true)? { ++ crate::host_io::stderr().flush()?; ++ ++ if !read_remote_confirmation(&mut crate::host_io::stdin().lock(), true)? { + return Err(io::Error::new( + io::ErrorKind::Interrupted, + "remote herdr installation cancelled", +--- a/src/server/headless/bootstrap.rs ++++ b/src/server/headless/bootstrap.rs +@@ -2,7 +2,10 @@ + + /// Run the headless server. This is the entry point called from main.rs. + pub fn run_server() -> io::Result<()> { ++ #[cfg(not(target_os = "ios"))] + let args: Vec = std::env::args().collect(); ++ #[cfg(target_os = "ios")] ++ let args = vec!["herdr".to_owned(), "server".to_owned()]; + let handoff_import = args.get(2).map(String::as_str) == Some("--handoff-import"); + let process_context = crate::platform::prepare_server_process(handoff_import); + init_logging(); +@@ -29,7 +32,10 @@ + let loaded_config = config::Config::load(); + let (api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel(); + let event_hub = api::EventHub::default(); ++ #[cfg(not(target_os = "ios"))] + let should_quit = Arc::new(AtomicBool::new(false)); ++ #[cfg(target_os = "ios")] ++ let should_quit = crate::ios_entry::server_stop_flag(); + + // Start the JSON API socket server. + let _api_server = match api::start_server_with_stop_control( +@@ -41,7 +47,7 @@ + Err(err) if err.kind() == io::ErrorKind::AddrInUse => { + eprintln!("error: herdr server is already running"); + eprintln!("api socket: {}", api::socket_path().display()); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + Err(err) => return Err(err), + }; +@@ -74,7 +80,7 @@ + Err(err) if err.kind() == io::ErrorKind::AddrInUse => { + eprintln!("error: herdr server is already running"); + eprintln!("client socket: {}", client_socket_path().display()); +- std::process::exit(1); ++ crate::host_io::exit(1); + } + Err(err) => return Err(err), + }; +@@ -120,6 +126,8 @@ + } + + fn take_startup_cwd() -> Option { ++ #[cfg(target_os = "ios")] ++ return crate::ios_entry::take_startup_cwd(); + let cwd = std::env::var_os(crate::server::autodetect::STARTUP_CWD_ENV_VAR)?; + std::env::remove_var(crate::server::autodetect::STARTUP_CWD_ENV_VAR); + (!cwd.is_empty()).then(|| PathBuf::from(cwd)) +--- a/src/platform/windows/config_backup/tests.rs ++++ b/src/platform/windows/config_backup/tests.rs +@@ -312,7 +312,7 @@ + }; + let _ = write_observed(&path, b"new", |phase| { + if phase == crash_phase { +- std::process::exit(23); ++ crate::host_io::exit(23); + } + Ok(()) + }); +--- a/src/platform/mod.rs ++++ b/src/platform/mod.rs +@@ -160,8 +160,8 @@ + + pub(crate) const fn capabilities() -> PlatformCapabilities { + PlatformCapabilities { +- live_handoff: cfg!(unix), +- direct_terminal_attach: cfg!(unix), ++ live_handoff: cfg!(all(unix, not(target_os = "ios"))), ++ direct_terminal_attach: cfg!(all(unix, not(target_os = "ios"))), + preserve_legacy_doubled_escape_input: cfg!(target_os = "macos"), + } + } +@@ -228,6 +228,8 @@ + /// Records SIGWINCH events that size polling can miss. + #[cfg(unix)] + pub(crate) fn watch_terminal_resize_signal() { ++ #[cfg(target_os = "ios")] ++ return; + let mut action: libc::sigaction = unsafe { std::mem::zeroed() }; + action.sa_sigaction = + record_terminal_resize_signal as extern "C" fn(libc::c_int) as libc::sighandler_t; +--- a/src/server/headless.rs ++++ b/src/server/headless.rs +@@ -3328,6 +3328,7 @@ + /// Installs a Ctrl+C handler that sets the should_quit flag and wakes up + /// the event loop by sending a QuitSignal on the server event channel. + fn ctrlc_handler(should_quit: Arc, server_event_tx: mpsc::Sender) { ++ #[cfg(not(target_os = "ios"))] + let _ = ctrlc::set_handler(move || { + should_quit.store(true, Ordering::Release); + // Wake up the event loop so the quit flag is checked promptly. +--- a/src/server/autodetect.rs ++++ b/src/server/autodetect.rs +@@ -47,13 +47,15 @@ + + /// Checks whether a herdr server is listening at a specific socket path. + fn is_server_listening_at(socket_path: &Path) -> bool { ++ #[cfg(target_os = "ios")] ++ { return client_protocol_accepts_hello(socket_path).unwrap_or(false); } + #[cfg(windows)] + { + let _ = socket_path; + read_server_status().ok().flatten().is_some() + } + +- #[cfg(not(windows))] ++ #[cfg(all(not(windows), not(target_os = "ios")))] + { + if !socket_path.exists() { + return false; +@@ -92,8 +94,9 @@ + crate::api::read_runtime_status_at(&crate::api::socket_path(), STATUS_REQUEST_TIMEOUT) + } + +-#[cfg(windows)] ++#[cfg(any(windows, target_os = "ios"))] + fn client_protocol_accepts_hello(socket_path: &Path) -> io::Result { ++ #[cfg(windows)] + if !socket_path.exists() { + return Ok(false); + } +@@ -114,6 +117,11 @@ + Err(err) => return Err(err), + }; + ++ #[cfg(target_os = "ios")] ++ { return crate::client::probe_endpoint_negotiation(&mut stream).map(|_| true); } ++ ++ #[cfg(windows)] ++ { + let hello = crate::protocol::ClientMessage::TerminalHello { + version: crate::protocol::PROTOCOL_VERSION, + cols: 80, +@@ -139,6 +147,7 @@ + Ok(false) + } + Err(err) => Err(io::Error::other(err.to_string())), ++ } + } + } + +@@ -192,6 +201,8 @@ + /// + /// Returns the PID of the spawned server process. + pub fn spawn_server_daemon() -> io::Result { ++ #[cfg(target_os = "ios")] ++ return crate::ios_entry::start_server(); + let exe = std::env::current_exe().map_err(|err| { + io::Error::new( + err.kind(), +@@ -253,13 +264,13 @@ + let deadline = std::time::Instant::now() + timeout; + + while std::time::Instant::now() < deadline { +- #[cfg(windows)] ++ #[cfg(any(windows, target_os = "ios"))] + if client_protocol_accepts_hello(socket_path)? { + info!(path = %socket_path.display(), "server client protocol ready"); + return Ok(()); + } + +- #[cfg(not(windows))] ++ #[cfg(all(not(windows), not(target_os = "ios")))] + if is_server_listening_at(socket_path) { + info!(path = %socket_path.display(), "server socket ready"); + return Ok(()); +--- a/src/pty/backend.rs ++++ b/src/pty/backend.rs +@@ -1,8 +1,14 @@ +-#[cfg(unix)] ++#[cfg(all(unix, not(target_os = "ios")))] + mod unix; + +-#[cfg(unix)] ++#[cfg(all(unix, not(target_os = "ios")))] + pub(crate) use unix::*; ++ ++#[cfg(target_os = "ios")] ++#[path = "ios.rs"] ++mod ios; ++#[cfg(target_os = "ios")] ++pub(crate) use ios::*; + + #[cfg(windows)] + use portable_pty::{native_pty_system, Child, CommandBuilder, MasterPty, PtySize}; +--- a/src/pty/fd.rs ++++ b/src/pty/fd.rs +@@ -224,6 +224,9 @@ + cell_width_px: u32, + cell_height_px: u32, + ) -> std::io::Result<()> { ++ #[cfg(target_os = "ios")] ++ { ++ return crate::pty::backend::resize(fd,rows,cols); } + let size = libc::winsize { + ws_row: rows, + ws_col: cols, +--- a/src/ipc.rs ++++ b/src/ipc.rs +@@ -7,7 +7,10 @@ + #[cfg(unix)] + use interprocess::local_socket::traits::Stream as _; + ++#[cfg(not(target_os = "ios"))] + pub(crate) type LocalListener = interprocess::local_socket::Listener; ++#[cfg(target_os = "ios")] ++pub(crate) use crate::ios_ipc::LocalListener; + pub(crate) type LocalStream = interprocess::local_socket::Stream; + + pub(crate) enum LocalStreamRead { +@@ -24,16 +27,20 @@ + + #[derive(Clone, Debug, Eq, PartialEq)] + pub(crate) struct SocketFileIdentity { +- #[cfg(unix)] ++ #[cfg(target_os = "ios")] ++ generation:u64, ++ #[cfg(all(unix, not(target_os = "ios")))] + dev: u64, +- #[cfg(unix)] ++ #[cfg(all(unix, not(target_os = "ios")))] + ino: u64, + #[cfg(windows)] + marker: Vec, + } + + pub(crate) fn connect_local_stream(path: &Path) -> io::Result { +- #[cfg(unix)] ++ #[cfg(target_os = "ios")] ++ return crate::ios_ipc::connect(path); ++ #[cfg(all(unix, not(target_os = "ios")))] + { + use interprocess::local_socket::{prelude::*, GenericFilePath}; + +@@ -52,7 +59,9 @@ + } + + pub(crate) fn bind_local_listener(path: &Path) -> io::Result { +- #[cfg(unix)] ++ #[cfg(target_os = "ios")] ++ return crate::ios_ipc::bind(path); ++ #[cfg(all(unix, not(target_os = "ios")))] + { + use interprocess::local_socket::{prelude::*, GenericFilePath, ListenerOptions}; + +@@ -82,6 +91,8 @@ + path: &Path, + busy_message: impl FnOnce(&Path) -> String, + ) -> io::Result<()> { ++ #[cfg(target_os = "ios")] ++ return crate::ios_ipc::prepare(path); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } +@@ -278,6 +289,8 @@ + } + + pub(crate) fn socket_file_identity(path: &Path) -> io::Result { ++ #[cfg(target_os = "ios")] ++ return crate::ios_ipc::identity(path).map(|generation|SocketFileIdentity{generation}); + #[cfg(windows)] + { + Ok(SocketFileIdentity { +@@ -285,7 +298,7 @@ + }) + } + +- #[cfg(unix)] ++ #[cfg(all(unix, not(target_os = "ios")))] + { + let metadata = fs::metadata(path)?; + Ok(SocketFileIdentity { +@@ -299,6 +312,8 @@ + path: &Path, + identity: &SocketFileIdentity, + ) -> io::Result<()> { ++ #[cfg(target_os = "ios")] ++ { crate::ios_ipc::remove(path,identity.generation); return Ok(()); } + let current = match socket_file_identity(path) { + Ok(current) => current, + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), +@@ -327,6 +342,8 @@ + + #[cfg(unix)] + pub(crate) fn restrict_socket_permissions(path: &Path, mode: u32) -> io::Result<()> { ++ #[cfg(target_os = "ios")] ++ return crate::ios_ipc::private(path,mode); + let mut permissions = fs::metadata(path)?.permissions(); + permissions.set_mode(mode); + fs::set_permissions(path, permissions) +--- a/vendor/portable-pty/src/cmdbuilder.rs ++++ b/vendor/portable-pty/src/cmdbuilder.rs +@@ -409,6 +409,13 @@ ++ /// Preserve the full environment and OS strings across an embedded process boundary. ++ #[cfg(target_os = "ios")] ++ pub fn iter_full_env(&self) -> impl Iterator { ++ self.envs.values() ++ .map(|entry| (entry.preferred_key.as_os_str(), entry.value.as_os_str())) ++ } ++ + /// Iterate over the configured environment. Only includes environment + /// variables set by the caller via `env`, not variables set in the base + /// environment. + pub fn iter_extra_env_as_str(&self) -> impl Iterator { + self.envs.values().filter_map( + |EnvEntry { +--- a/src/pane.rs ++++ b/src/pane.rs +@@ -1680,6 +1680,9 @@ + } + + fn pane_shell(configured_shell: &str) -> String { ++ #[cfg(target_os = "ios")] ++ { return if configured_shell.trim().is_empty() { "dash".to_owned() } else { configured_shell.trim().to_owned() }; } ++ #[cfg(not(target_os = "ios"))] + pane_shell_from(configured_shell, std::env::var("SHELL").ok()) + } + +--- a/src/api/status.rs ++++ b/src/api/status.rs +@@ -15,6 +15,7 @@ + socket_path: &Path, + timeout: Duration, + ) -> io::Result> { ++ #[cfg(not(target_os = "ios"))] + if !socket_path.exists() { + return Ok(None); + } +--- a/src/pty/actor/unix.rs ++++ b/src/pty/actor/unix.rs +@@ -402,6 +402,29 @@ + response_order: Arc::clone(&response_order), + }; + ++ // Socket panes have no kernel ONLCR. Normalize only terminal output, ++ // preserving existing CRLF even when CR and LF arrive in different reads. ++ #[cfg(target_os = "ios")] ++ let on_read: ReadCallback = if unsafe { libc::isatty(config.master_fd.as_raw_fd()) } == 0 { ++ let mut callback = config.on_read; ++ let mut previous_cr = false; ++ Box::new(move |bytes| { ++ let mut output = Vec::with_capacity(bytes.len() * 2); ++ for &byte in bytes { ++ if byte == b'\n' && !previous_cr { ++ output.push(b'\r'); ++ } ++ output.push(byte); ++ previous_cr = byte == b'\r'; ++ } ++ callback(&output) ++ }) ++ } else { ++ config.on_read ++ }; ++ #[cfg(not(target_os = "ios"))] ++ let on_read = config.on_read; ++ + let mut runner = PtyIoActorRunner { + pane_id: config.pane_id, + file: std::fs::File::from(config.master_fd), +@@ -419,7 +442,7 @@ + wake_read_fd: wake_pipe.read_fd, + controls, + response_order, +- on_read: config.on_read, ++ on_read, + on_reader_exit: config.on_reader_exit, + poll_observer, + }; +@@ -639,6 +662,17 @@ + PtyIoDataCommand::WriteUserInput(bytes) => { + if self.state == ActorState::Running { ++ #[cfg(target_os = "ios")] ++ if bytes.as_ref() == [3] { ++ match crate::pty::backend::interrupt(self.file.as_raw_fd()) { ++ Ok(true) => return false, ++ Ok(false) => {}, // A raw editor/TUI consumes ETX itself. ++ Err(error) => { ++ warn!(pane = self.pane_id, %error, "pane interrupt failed"); ++ return false; ++ } ++ } ++ } + self.enqueue_write(bytes); + } + } + PtyIoDataCommand::SubmitUserInput { +@@ -710,7 +744,11 @@ + let _ = reply.send(Ok(())); + return true; + } +- PtyIoControlCommand::Shutdown => return true, ++ PtyIoControlCommand::Shutdown => { ++ #[cfg(target_os = "ios")] ++ crate::pty::backend::cancel(self.file.as_raw_fd()); ++ return true; ++ } + } + false + } +--- a/src/persist/io.rs ++++ b/src/persist/io.rs +@@ -105,7 +105,20 @@ + } + }; + match parse_snapshot(&content) { +- Ok(snapshot) => Some(snapshot), ++ Ok(snapshot) => { ++ #[cfg(target_os = "ios")] ++ let snapshot = { ++ let mut snapshot = snapshot; ++ if crate::ios_entry::relocate_snapshot(&mut snapshot) { ++ if let Err(err) = save_to_path(&path, &snapshot) { ++ warn!(path = %path.display(), err = %err, ++ "failed to save relocated app-container cwd"); ++ } ++ } ++ snapshot ++ }; ++ Some(snapshot) ++ }, + Err(err) => { + if let Some(version) = snapshot_file_version(&content) { + if version > SNAPSHOT_VERSION { + +--- a/src/app/mod.rs ++++ b/src/app/mod.rs +@@ -250,7 +250,14 @@ + .theme + .name + .clone() +- .unwrap_or_else(|| "catppuccin".to_string()); ++ .unwrap_or_else(|| { ++ if cfg!(target_os = "ios") { ++ "terminal" ++ } else { ++ "catppuccin" ++ } ++ .to_string() ++ }); + let (default_dark, default_light) = sibling_theme_names(&manual_name); + state::ThemeRuntimeConfig { + manual_name, +--- a/src/client/shell/overlays.rs ++++ b/src/client/shell/overlays.rs +@@ -534,15 +534,6 @@ + } + + fn render_onboarding_overlay(b: &mut Buffer, p: &Palette) -> Option { +- let outer = popup(b.area, 64, 16)?; +- let inner = panel(b, outer, p.accent, p.panel_bg)?; +- if inner.height < 11 { +- return Some(OverlayRender { +- area: outer, +- ..OverlayRender::default() +- }); +- } +- let stack = crate::ui::modal_stack_areas(inner, 2, 0, 1, 1); + let base = Style::default() + .bg(p.panel_bg) + .remove_modifier(Modifier::DIM); +@@ -551,63 +542,37 @@ + let text = base.fg(p.overlay1); + let accent = base.fg(p.accent).add_modifier(Modifier::BOLD); + +- put_text( +- b, +- stack.header.x, +- stack.header.y, +- stack.header.width, +- crate::ui::ONBOARDING_TITLE, +- title, +- ); +- put_text( +- b, +- stack.header.x, +- stack.header.y.saturating_add(1), +- stack.header.width, +- crate::ui::ONBOARDING_SUBTITLE, +- muted, +- ); +- +- let content = stack.content; +- for (offset, line) in crate::ui::ONBOARDING_DESCRIPTION.iter().enumerate() { +- put_text( +- b, +- content.x, +- content.y.saturating_add(offset as u16), +- content.width, +- line, +- text, +- ); +- } +- +- let key_y = content.y.saturating_add(4); +- let mut key_x = content.x; +- for (value, style) in [ +- (" ", base), +- (crate::ui::ONBOARDING_PREFIX_LABEL, accent), +- (crate::ui::ONBOARDING_PREFIX_SUFFIX, text), +- (crate::ui::ONBOARDING_HELP_LABEL, accent), +- (crate::ui::ONBOARDING_HELP_SUFFIX, text), +- ] { +- let width = display_width(value); +- put_text( +- b, +- key_x, +- key_y, +- content.right().saturating_sub(key_x), +- value, +- style, +- ); +- key_x = key_x.saturating_add(width); +- } +- put_text( +- b, +- content.x, +- content.y.saturating_add(5), +- content.width, +- crate::ui::ONBOARDING_NEXT, +- text, +- ); ++ use ratatui::text::{Line, Span}; ++ use ratatui::widgets::{Paragraph, Widget, Wrap}; ++ let mut lines = crate::ui::ONBOARDING_DESCRIPTION ++ .iter() ++ .map(|line| Line::styled(*line, text)) ++ .collect::>(); ++ lines.push(Line::raw("")); ++ lines.push(Line::from(vec![ ++ Span::styled(" ", base), ++ Span::styled(crate::ui::ONBOARDING_PREFIX_LABEL, accent), ++ Span::styled(crate::ui::ONBOARDING_PREFIX_SUFFIX, text), ++ Span::styled(crate::ui::ONBOARDING_HELP_LABEL, accent), ++ Span::styled(crate::ui::ONBOARDING_HELP_SUFFIX, text), ++ ])); ++ lines.push(Line::styled(crate::ui::ONBOARDING_NEXT, text)); ++ let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false }); ++ ++ let width = b.area.width.saturating_sub(6).min(62); ++ let subtitle = Paragraph::new(crate::ui::ONBOARDING_SUBTITLE) ++ .style(muted) ++ .wrap(Wrap { trim: false }); ++ let header_height = 1 + u16::try_from(subtitle.line_count(width)).unwrap_or(u16::MAX); ++ let height = u16::try_from(paragraph.line_count(width)).unwrap_or(u16::MAX) ++ .saturating_add(header_height) ++ .saturating_add(5); ++ let outer = popup(b.area, 64, height.max(16))?; ++ let inner = panel(b, outer, p.accent, p.panel_bg)?; ++ let stack = crate::ui::modal_stack_areas(inner, header_height, 0, 1, 1); ++ put_text(b, stack.header.x, stack.header.y, stack.header.width, crate::ui::ONBOARDING_TITLE, title); ++ subtitle.render(Rect::new(stack.header.x, stack.header.y + 1, stack.header.width, header_height.saturating_sub(1)), b); ++ paragraph.render(stack.content, b); + + let primary = crate::ui::onboarding_welcome_continue_rect(stack.actions.unwrap_or_default()); + button( +--- a/src/events.rs ++++ b/src/events.rs +@@ -76,6 +76,8 @@ + /// An event from a background task to the main loop. + #[derive(Debug)] + pub enum AppEvent { ++ #[cfg(target_os = "ios")] ++ PaneExitStatus { pane_id: PaneId, status: u32 }, + /// A pane's child process exited. + PaneDied { + pane_id: PaneId, +--- a/src/app/actions.rs ++++ b/src/app/actions.rs +@@ -1373,6 +1373,8 @@ + + pub fn handle_app_event(&mut self, event: AppEvent) -> Vec { + match event { ++ #[cfg(target_os = "ios")] ++ AppEvent::PaneExitStatus { .. } => Vec::new(), + AppEvent::PaneDied { pane_id, .. } => { + self.handle_pane_died(pane_id); + Vec::new() +--- a/src/pane.rs ++++ b/src/pane.rs +@@ -2605,6 +2605,11 @@ + tokio::task::spawn_blocking(move || { + let exit_reason = match child.wait() { + Ok(status) => { ++ #[cfg(target_os = "ios")] ++ let _ = rt.block_on(events.send(AppEvent::PaneExitStatus { ++ pane_id, ++ status: status.exit_code(), ++ })); + let exit_reason = crate::platform::classify_child_exit(&status); + let status_text = format!("{status:?}"); + crate::logging::pane_exited(pane_id.raw(), &status_text); +--- a/src/client/shell/actions.rs ++++ b/src/client/shell/actions.rs +@@ -430,6 +430,14 @@ + } + + pub(crate) fn receive_endpoint_error(&mut self, message: String) -> bool { ++ #[cfg(target_os = "ios")] ++ return self.push_endpoint_notice( ++ ClientEndpointNoticeKind::Rejected, ++ "pane_error", ++ message.clone(), ++ message, ++ ); ++ #[cfg(not(target_os = "ios"))] + self.push_endpoint_notice( + ClientEndpointNoticeKind::Rejected, + "paste_rejected", +@@ -550,12 +558,18 @@ + "Server unavailable", + error.message.clone(), + ), +- _ => ( +- ClientEndpointNoticeKind::Rejected, +- format!("{}:{code}", pending.method_name), +- "Action rejected", +- error.message.clone(), +- ), ++ _ => { ++ #[cfg(target_os = "ios")] ++ let title = error.message.as_str(); ++ #[cfg(not(target_os = "ios"))] ++ let title = "Action rejected"; ++ ( ++ ClientEndpointNoticeKind::Rejected, ++ format!("{}:{code}", pending.method_name), ++ title, ++ error.message.clone(), ++ ) ++ } + }; + self.push_endpoint_notice(kind, notice_code, title, body); + } +--- a/src/server/headless/notifications.rs ++++ b/src/server/headless/notifications.rs +@@ -646,6 +646,17 @@ + } + true + } ++ #[cfg(target_os = "ios")] ++ AppEvent::PaneExitStatus { pane_id, status } => { ++ // Explicit pane close removes the pane before its exit event arrives. ++ if self.app.find_pane(*pane_id).is_none() { ++ return false; ++ } ++ self.send_to_client_shells(ServerMessage::ClientShellError { ++ message: format!("Pane {} exited: {status}", pane_id.raw()), ++ }); ++ true ++ } + AppEvent::PaneDied { pane_id, .. } + | AppEvent::WorktreeRuntimeRestoreFailed { pane_id, .. } => { + let focus_before = self.shell_focus_targets(); +--- a/src/app/actions.rs ++++ b/src/app/actions.rs +@@ -2055,6 +2055,12 @@ + self.workspaces.remove(ws_idx); + self.remove_unattached_terminal_ids(workspace_terminal_ids); + if self.workspaces.is_empty() { ++ #[cfg(target_os = "ios")] ++ { ++ // Embedded Herdr returns to its containing a-Shell command ++ // when the final shell ends instead of replacing the workspace. ++ self.should_quit = true; ++ } + self.active = None; + self.selected = 0; + if self.mode == Mode::Terminal { +--- a/src/app/mod.rs ++++ b/src/app/mod.rs +@@ -696,6 +696,11 @@ + } + + pub(crate) fn ensure_default_workspace(&mut self) -> bool { ++ // Do not launch a replacement while the embedded command is shutting down. ++ #[cfg(target_os = "ios")] ++ if self.state.should_quit { ++ return false; ++ } + if !self.state.workspaces.is_empty() { + return false; + } +--- a/src/client/shell/endpoint_notices.rs ++++ b/src/client/shell/endpoint_notices.rs +@@ -15 +15 @@ +- Some(¬ice.body), ++ Some(notice.body.as_str()).filter(|body| !cfg!(target_os = "ios") || *body != notice.title), +@@ -67 +67,5 @@ +- ¬ice.body, ++ if cfg!(target_os = "ios") && notice.body == notice.title { ++ "" ++ } else { ++ ¬ice.body ++ }, diff --git a/Herdr/tests/three-panes.sh b/Herdr/tests/three-panes.sh new file mode 100755 index 00000000..1928f917 --- /dev/null +++ b/Herdr/tests/three-panes.sh @@ -0,0 +1,91 @@ +#!/bin/bash +# Exercise an installed disposable Simulator app through its public terminal UI. +set -euo pipefail +if [ "$#" -ne 3 ]; then + echo "usage: $0 SIMULATOR_UDID APP_BUNDLE_ID URL_SCHEME" >&2 + exit 2 +fi +sim=$1 +bundle=$2 +scheme=$3 +command -v axe >/dev/null +command -v jq >/dev/null +data=$(xcrun simctl get_app_container "$sim" "$bundle" data) +app=$(xcrun simctl get_app_container "$sim" "$bundle" app) +receipts=$(mktemp -d "$data/Documents/herdr-ui.XXXXXX") +steps=$(mktemp) +trap 'rm -f "$steps"' EXIT + +# HID bursts can overrun Simulator input. Preserve characters and modifier order. +type_command() { + local character escaped + while IFS= read -r -n 1 character; do + escaped=${character//\\/\\\\} + escaped=${escaped//\"/\\\"} + printf 'type "%s"\nsleep 0.08\n' "$escaped" + done < <(printf '%s' "$1") + printf 'sleep 0.5\nkey 40\nsleep 2\n' +} +wait_output() { + local attempt + for ((attempt = 0; attempt < 200; attempt++)); do + if [ -s "$1" ]; then return 0; fi + sleep 0.1 + done + echo "missing or empty receipt: $1" >&2 + return 1 +} + +# Start at a fresh shell, with default Herdr keybindings and tab-name prompts. +xcrun simctl launch "$sim" "$bundle" >/dev/null +xcrun simctl openurl "$sim" "$scheme:herdr" +printf 'sleep 3\ntap -x 130 -y 260\nsleep 1\n' >"$steps" +axe batch --udid "$sim" --file "$steps" >/dev/null +pids=() +for pane in a b c; do + : >"$steps" + if [ "$pane" != a ]; then + # Ctrl+B,c opens a name dialog; Return creates the tab, not a shell command. + printf 'key-combo --modifiers 224 --key 5\nsleep 0.4\ntype c\nsleep 0.5\n' >>"$steps" + type_command "pane-$pane" >>"$steps" + fi + printf -v command 'printenv ASHELL_WORKER_PID > %q' "$receipts/$pane" + type_command "$command" >>"$steps" + axe batch --udid "$sim" --file "$steps" >/dev/null + wait_output "$receipts/$pane" + pid=$(cat "$receipts/$pane") + case "$pid" in + '' | *[!0-9]*) + echo "invalid worker PID for pane $pane" >&2 + exit 1 + ;; + esac + pids+=("$pid") +done +if [ "${pids[0]}" = "${pids[1]}" ] || [ "${pids[0]}" = "${pids[2]}" ] || [ "${pids[1]}" = "${pids[2]}" ]; then + echo "panes share a worker PID" >&2 + exit 1 +fi +# Simulator workers are Mac processes. Verify all belong to this installed app +# and remain alive together after all three commands have produced output. +for pid in "${pids[@]}"; do + worker=$(ps -p "$pid" -o comm=) + case "$worker" in + "$app"/Extensions/ShellWorker?.appex/ShellWorker?) ;; + *) + echo "PID $pid is not a live worker of the tested app" >&2 + exit 1 + ;; + esac +done +printf 'three concurrent workers: %s %s %s\n' "${pids[@]}" + +# Leave the real shell usable and prove same-process command re-entry. +printf 'key-combo --modifiers 224 --key 5\nsleep 0.4\ntype q\nsleep 3\n' >"$steps" +axe batch --udid "$sim" --file "$steps" >/dev/null +printf -v command 'herdr --version > %q' "$receipts/reentry" +encoded=$(jq -nr --arg command "$command" '$command | @uri') +xcrun simctl openurl "$sim" "$scheme:$encoded" +wait_output "$receipts/reentry" +printf 'herdr 0.9.3\n' | cmp - "$receipts/reentry" +printf 'detach and same-process re-entry: PASS\nreceipts: %s\n' "$receipts" diff --git a/README.md b/README.md index ce15a868..94984196 100644 --- a/README.md +++ b/README.md @@ -99,3 +99,7 @@ The host retains each `AppExtensionProcess` and XPC connection until release or Workers share the host's command libraries. Build with ios_system changes #179–#184 and dash_iOS#1–#2, including the matched libedit dependency described there. The build derives each worker's catalogue and executable markers from `Resources_mini/commandDictionary.plist`; it generates the ExtensionFoundation binding from `PRODUCT_BUNDLE_PREFIX`. Keep worker versions in `ShellWorkers/Worker.xcconfig` aligned with the containing app. The mini bundle suffixes are `.ShellWorkerA` through `.ShellWorkerJ`; each requires its own App ID and profile for a device build. `tests/worker-pool.m` is a real app-command consumer for Simulator qualification. Device memory limits, background execution without other host background modes, and App Store acceptance require separate validation. Retaining the process handle provides no promise of unlimited background execution. + +## Embedded Herdr + +The mini target registers `herdr` as a native embedded command. Build its pinned static archive with `./Herdr/build.sh aarch64-apple-ios-sim` before a Simulator build, or select `aarch64-apple-ios` for a device build. See [Herdr/README.md](Herdr/README.md) for toolchain requirements, supported operations and qualification limits. diff --git a/a-Shell.xcodeproj/project.pbxproj b/a-Shell.xcodeproj/project.pbxproj index 8055ff92..b5efc24d 100644 --- a/a-Shell.xcodeproj/project.pbxproj +++ b/a-Shell.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ FD0000000000000000000001 /* fd.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = FD0000000000000000000002 /* fd.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; F2F000000000000000000001 /* fzf.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = F2F000000000000000000002 /* fzf.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; AA7100000000000000000001 /* navi.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = AA7100000000000000000002 /* navi.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + A2B1818A0000000000000001 /* Herdr LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = A2B1818A0000000000000002 /* Herdr LICENSE */; }; 2203367A28C4B8070027664C /* pico.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 2232245E289695A9001BAE04 /* pico.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 22068CC62F51C11A004307F7 /* TerminalView+KeyCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22068CC52F51BFCE004307F7 /* TerminalView+KeyCommands.swift */; }; 22068CC72F51CE47004307F7 /* TerminalView+KeyCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22068CC52F51BFCE004307F7 /* TerminalView+KeyCommands.swift */; }; @@ -2181,6 +2182,7 @@ /* Begin PBXFileReference section */ 619225000000000000000002 /* gitoxide.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = gitoxide/gitoxide.xcframework; sourceTree = SOURCE_ROOT; }; + A2B1818A0000000000000002 /* Herdr LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; name = "Herdr LICENSE"; path = Herdr/LICENSE; sourceTree = SOURCE_ROOT; }; 22068CC52F51BFCE004307F7 /* TerminalView+KeyCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TerminalView+KeyCommands.swift"; sourceTree = ""; }; 2208ACBE22CCE57E003985D6 /* String+C.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "String+C.swift"; path = "Util/String+C.swift"; sourceTree = SOURCE_ROOT; }; 2208ACC422D2026E003985D6 /* UIDevice+Name.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "UIDevice+Name.swift"; path = "Util/UIDevice+Name.swift"; sourceTree = SOURCE_ROOT; }; @@ -3340,6 +3342,7 @@ 22984EE122C93DBC00069497 = { isa = PBXGroup; children = ( + A2B1818A0000000000000002 /* Herdr LICENSE */, 220F36512BC458C800842FEE /* PrivacyInfo.xcprivacy */, 223FC3CA2611F9C300CDC89F /* wasm.html */, 2220059F2871EF3300DC7A23 /* Intents.intentdefinition */, @@ -4822,6 +4825,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + A2B1818A0000000000000001 /* Herdr LICENSE in Resources */, 227B248C2BE12FF1003A8031 /* wasm_withWorker.js in Resources */, 22A536352C4521CA0031A9FF /* wasm_worker_wasm.js in Resources */, 22068CCC2F5C9AAF004307F7 /* wasm.js in Resources */, @@ -5915,6 +5919,8 @@ "$(PROJECT_DIR)/Frameworks", "$(PROJECT_DIR)", ); + "HERDR_RUST_TARGET[sdk=iphoneos*]" = "aarch64-apple-ios"; + "HERDR_RUST_TARGET[sdk=iphonesimulator*]" = "aarch64-apple-ios-sim"; INFOPLIST_FILE = "a-Shell-mini-Info.plist"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; @@ -5923,6 +5929,7 @@ "@executable_path/Frameworks", ); LIBRARY_SEARCH_PATHS = ( + "$(SRCROOT)/Herdr/build/target/$(HERDR_RUST_TARGET)/release", "$(inherited)", "$(SDKROOT)/usr/lib/swift", "$(PROJECT_DIR)/Frameworks", @@ -5930,6 +5937,16 @@ MARKETING_VERSION = 2.2.3; OTHER_CODE_SIGN_FLAGS = ""; OTHER_LDFLAGS = ( + "$(inherited)", + "-lherdr_ios", + "-Wl,-u,_herdr_ios_main", + "-framework", + "Security", + "-framework", + "SystemConfiguration", + "-lc++", + "-lz", + "-liconv", "-L", Frameworks/, ); @@ -5944,6 +5961,7 @@ SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_OBJC_BRIDGING_HEADER = "a-Shell/a-Shell-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) HERDR_EMBEDDED"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -5968,6 +5986,8 @@ "$(PROJECT_DIR)/Frameworks", "$(PROJECT_DIR)", ); + "HERDR_RUST_TARGET[sdk=iphoneos*]" = "aarch64-apple-ios"; + "HERDR_RUST_TARGET[sdk=iphonesimulator*]" = "aarch64-apple-ios-sim"; INFOPLIST_FILE = "a-Shell-mini-Info.plist"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; @@ -5976,6 +5996,7 @@ "@executable_path/Frameworks", ); LIBRARY_SEARCH_PATHS = ( + "$(SRCROOT)/Herdr/build/target/$(HERDR_RUST_TARGET)/release", "$(inherited)", "$(SDKROOT)/usr/lib/swift", "$(PROJECT_DIR)/Frameworks", @@ -5983,6 +6004,16 @@ MARKETING_VERSION = 2.2.3; OTHER_CODE_SIGN_FLAGS = ""; OTHER_LDFLAGS = ( + "$(inherited)", + "-lherdr_ios", + "-Wl,-u,_herdr_ios_main", + "-framework", + "Security", + "-framework", + "SystemConfiguration", + "-lc++", + "-lz", + "-liconv", "-L", Frameworks/, ); @@ -5996,6 +6027,7 @@ SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = YES; SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_OBJC_BRIDGING_HEADER = "a-Shell/a-Shell-Bridging-Header.h"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) HERDR_EMBEDDED"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; diff --git a/a-Shell/AppDelegate.swift b/a-Shell/AppDelegate.swift index baa29e97..f696b873 100644 --- a/a-Shell/AppDelegate.swift +++ b/a-Shell/AppDelegate.swift @@ -205,6 +205,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { viewBehavior = .ignoreSafeArea } initializeEnvironment() + #if HERDR_EMBEDDED + replaceCommand("herdr", "herdr_ios_main", false) + #endif joinMainThread = false ios_setBookmarkDictionaryName("bookmarkNames") replaceCommand("history", "history", true) diff --git a/a-Shell/SceneDelegate+TerminalView.swift b/a-Shell/SceneDelegate+TerminalView.swift index 5b8ae5e0..3bdaf344 100644 --- a/a-Shell/SceneDelegate+TerminalView.swift +++ b/a-Shell/SceneDelegate+TerminalView.swift @@ -9,6 +9,11 @@ import SwiftTerm // for the terminal window import ios_system import TipKit // for helpful tips +#if HERDR_EMBEDDED +@_silgen_name("herdr_ios_resize") +private func herdrResize(_ cols: UInt16, _ rows: UInt16) +#endif + extension SceneDelegate { func longestCommonPrefix(_ strs: [String]) -> String { @@ -632,6 +637,9 @@ extension SceneDelegate { func sizeChanged(source: SwiftTerm.TerminalView, newCols: Int, newRows: Int) { if (newRows != height) || (newCols != width) { ios_setWindowSize(Int32(newCols), Int32(newRows), self.persistentIdentifier?.toCString()) + #if HERDR_EMBEDDED + herdrResize(UInt16(clamping: newCols), UInt16(clamping: newRows)) + #endif } if (newRows != height) { height = newRows From 38d15cef5a7d8c9292fac2f298e5624b60e42e4e Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:37:11 +0300 Subject: [PATCH 03/16] Export worker pane callbacks in Release builds --- ShellWorkers/NativePane.h | 5 +++++ ShellWorkers/NativePane.m | 8 +++---- ShellWorkers/Worker.m | 8 +++---- tests/worker-pool.m | 46 +++++++++++++++++++++++++-------------- tests/worker-pool.md | 14 +++++++----- 5 files changed, 52 insertions(+), 29 deletions(-) diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h index 0249cf84..34f4294e 100644 --- a/ShellWorkers/NativePane.h +++ b/ShellWorkers/NativePane.h @@ -5,6 +5,9 @@ extern "C" { #endif +// Keep the public C ABI discoverable in Release builds with hidden visibility. +#pragma GCC visibility push(default) + // command/cwd must be nonempty UTF-8; cwd must be an absolute accessible directory. // envp is NULL or a NULL-terminated list of UTF-8 key=value overrides, copied before return. // Dimensions are 1..9999. Returns 0 or positive errno; failure sets outputs to -1/NULL. @@ -39,6 +42,8 @@ int ashell_pane_interrupt(void *job); // The handle is opaque and is NOT an OS pid: never pass it to kill/waitpid/process APIs. void ashell_pane_release(void *job); +#pragma GCC visibility pop + #ifdef __cplusplus } #endif diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m index 29db5b84..f48a8411 100644 --- a/ShellWorkers/NativePane.m +++ b/ShellWorkers/NativePane.m @@ -48,7 +48,7 @@ // which can be a shell blocked in ios_waitpid rather than the running command. static _Atomic int foreground_command_pid; -__attribute__((used)) int ashell_pane_exchange_foreground_pid(int pid) { +__attribute__((used, visibility("default"))) int ashell_pane_exchange_foreground_pid(int pid) { return atomic_exchange(&foreground_command_pid, pid); } @@ -347,7 +347,7 @@ static int prepare_input_relay(pane_job *job) { // Wait on the editor's real input and resize event without changing process // signal handlers or inserting synthetic keys into the command stream. // Return 0 for an unrelated reader, 1 for input, 2 for resize, or -errno. -__attribute__((used)) int ashell_pane_wait_editor_input(FILE *input) { +__attribute__((used, visibility("default"))) int ashell_pane_wait_editor_input(FILE *input) { pane_job *job = atomic_load(&foreground_pane); if (!job || !job->input_relay || input != job->streams[0]) return 0; struct kevent event; @@ -360,7 +360,7 @@ static int prepare_input_relay(pane_job *job) { return event.filter == EVFILT_USER ? 2 : 1; } -__attribute__((used)) int ashell_pane_begin_foreground_input(FILE **input, void **token) { +__attribute__((used, visibility("default"))) int ashell_pane_begin_foreground_input(FILE **input, void **token) { if (!input || !token || *token) return EINVAL; pane_job *job = atomic_load(&foreground_pane); if (!job || !job->input_relay || *input != job->streams[0]) return 0; @@ -416,7 +416,7 @@ static int prepare_input_relay(pane_job *job) { return 0; } -__attribute__((used)) int ashell_pane_end_foreground_input(void *token) { +__attribute__((used, visibility("default"))) int ashell_pane_end_foreground_input(void *token) { command_input *command = token; if (!command) return EINVAL; int cancellation; diff --git a/ShellWorkers/Worker.m b/ShellWorkers/Worker.m index e215311c..c8bb984a 100644 --- a/ShellWorkers/Worker.m +++ b/ShellWorkers/Worker.m @@ -12,13 +12,13 @@ // ios_system discovers these stock host callbacks with dlsym. Each extension // owns one shell; its socket already carries input directly to the command. static atomic_bool interactive_input; -__attribute__((used)) void startInteractive(void) { atomic_store(&interactive_input, true); } -__attribute__((used)) void stopInteractive(void) { atomic_store(&interactive_input, false); } -__attribute__((used)) int storeInteractive(void) { return atomic_load(&interactive_input); } +__attribute__((used, visibility("default"))) void startInteractive(void) { atomic_store(&interactive_input, true); } +__attribute__((used, visibility("default"))) void stopInteractive(void) { atomic_store(&interactive_input, false); } +__attribute__((used, visibility("default"))) int storeInteractive(void) { return atomic_load(&interactive_input); } // The stock host clear command calls its UIKit delegate. Workers clear through // the terminal stream, just like an external terminal command. -__attribute__((used)) int clear(int argc, char **argv) { +__attribute__((used, visibility("default"))) int clear(int argc, char **argv) { if (!thread_stdout) return 1; return fputs("\033[H\033[2J", thread_stdout) == EOF || fflush(thread_stdout) == EOF ? 1 : 0; } diff --git a/tests/worker-pool.m b/tests/worker-pool.m index 64f32d16..2a4a9ddc 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -6,6 +6,7 @@ #include #include #include +#include // Keep each command alive at its public stdin boundary while the other slots start. @@ -15,14 +16,16 @@ static int capacity_check(void) { void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); if (!spawn || !pollJob || !release) { fputs("worker pool unavailable: FAIL\n", thread_stdout); return 1; } NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:[@"Documents/worker-pool-" stringByAppendingString:NSUUID.UUID.UUIDString]]; + const int capacity = [[NSBundle.mainBundle objectForInfoDictionaryKey:@"ShellWorkerCount"] intValue]; + if (capacity < 1 || capacity > 10) return 64; void *jobs[10] = {0}; int descriptors[10]; char output[10][2048] = {{0}}; size_t used[10] = {0}; int pids[10] = {0}; BOOL passed = YES; - for (int i = 0; i < 10; i++) descriptors[i] = -1; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < capacity; i++) descriptors[i] = -1; + for (int i = 0; i < capacity; i++) { NSString *directory = [root stringByAppendingPathComponent:[NSString stringWithFormat:@"slot-%d", i]]; if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil]) { passed = NO; break; } char value[32], command[256]; @@ -37,7 +40,7 @@ static int capacity_check(void) { BOOL allReady = NO; while (passed && NSProcessInfo.processInfo.systemUptime < deadline) { allReady = YES; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < capacity; i++) { ssize_t count = read(descriptors[i], output[i] + used[i], sizeof(output[i]) - used[i] - 1); if (count > 0) used[i] += count; if (!strchr(output[i], '\n') || !strchr(strchr(output[i], '\n') + 1, '\n')) allReady = NO; @@ -48,13 +51,19 @@ static int capacity_check(void) { usleep(10000); } if (!allReady) passed = NO; - for (int i = 0; passed && i < 10; i++) { + for (int i = 0; passed && i < capacity; i++) { char value[32]; if (sscanf(output[i], "READY=%d,%31[^\n]", &pids[i], value) != 2 || pids[i] <= 0) { passed = NO; break; } char expectedValue[32]; snprintf(expectedValue, sizeof(expectedValue), "slot-%d", i); - NSString *expectedDirectory = [[root stringByAppendingPathComponent:[NSString stringWithFormat:@"slot-%d", i]] stringByAppendingString:@"\n"]; - if (strcmp(value, expectedValue) || strcmp(strchr(output[i], '\n') + 1, expectedDirectory.fileSystemRepresentation)) passed = NO; + NSString *expectedDirectory = [root stringByAppendingPathComponent:[NSString stringWithFormat:@"slot-%d", i]]; + NSString *observedDirectory = [[NSString stringWithUTF8String:strchr(output[i], '\n') + 1] stringByTrimmingCharactersInSet:NSCharacterSet.newlineCharacterSet]; + struct stat expectedStat, observedStat; + BOOL sameDirectory = stat(expectedDirectory.fileSystemRepresentation, &expectedStat) == 0 && stat(observedDirectory.fileSystemRepresentation, &observedStat) == 0 && expectedStat.st_dev == observedStat.st_dev && expectedStat.st_ino == observedStat.st_ino; + if (strcmp(value, expectedValue) || !sameDirectory) { + fprintf(thread_stdout, "expected cwd=%s\nactual=%s", expectedDirectory.fileSystemRepresentation, output[i]); + passed = NO; + } for (int j = 0; j < i; j++) if (pids[i] == pids[j]) passed = NO; fprintf(thread_stdout, "slot=%d real_pid=%d cwd/env=%s\n", i, pids[i], passed ? "PASS" : "FAIL"); } @@ -63,7 +72,7 @@ static int capacity_check(void) { void *job = NULL; int error = spawn("dash -c 'exit 0'", root.fileSystemRepresentation, 80, 24, NULL, &descriptor, &job); BOOL full = error == ENOSPC && descriptor == -1 && job == NULL; - fprintf(thread_stdout, "eleventh worker error=%d: %s\n", error, full ? "PASS" : "FAIL"); + fprintf(thread_stdout, "worker=%d error=%d: %s\n", capacity + 1, error, full ? "PASS" : "FAIL"); if (job) release(job); if (descriptor >= 0) close(descriptor); passed = full; @@ -71,8 +80,8 @@ static int capacity_check(void) { // The same open sessions must still accept input after more than five seconds. if (passed) { sleep(6); - for (int i = 0; i < 10; i++) if (write(descriptors[i], "continue\n", 9) != 9) passed = NO; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < capacity; i++) if (write(descriptors[i], "continue\n", 9) != 9) passed = NO; + for (int i = 0; i < capacity; i++) { BOOL exited = NO, eof = NO; int status = -1; deadline = NSProcessInfo.processInfo.systemUptime + 10; @@ -90,12 +99,12 @@ static int capacity_check(void) { if (!completed) passed = NO; } } - for (int i = 0; i < 10; i++) { + for (int i = 0; i < capacity; i++) { if (jobs[i]) release(jobs[i]); if (descriptors[i] >= 0) close(descriptors[i]); } [[NSFileManager defaultManager] removeItemAtPath:root error:nil]; - fprintf(thread_stdout, "ten-worker capacity: %s\n", passed ? "PASS" : "FAIL"); + fprintf(thread_stdout, "workers=%d capacity: %s\n", capacity, passed ? "PASS" : "FAIL"); return passed ? 0 : 1; } @@ -111,7 +120,7 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { int descriptors[3] = {-1, -1, -1}, pids[3] = {0}; BOOL passed = YES; for (int i = 0; i < 3; i++) { - const char *command = busy && i == 0 ? "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; while :; do :; done'" : "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; read value; printf \"DONE=%s\\n\" \"$value\"; exit 7'"; + const char *command = i == 1 ? "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; read value; worker-pool-crash'" : busy && i == 0 ? "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; while :; do :; done'" : "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; read value; printf \"DONE=%s\\n\" \"$value\"; exit 7'"; int error = spawn(command, directory.fileSystemRepresentation, 80, 24, NULL, &descriptors[i], &jobs[i]); if (error) { fprintf(thread_stdout, "lifecycle slot=%d startup=%d: FAIL\n", i, error); passed = NO; break; } struct pollfd ready = {.fd = descriptors[i], .events = POLLIN}; @@ -138,9 +147,9 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { close(descriptors[0]); descriptors[0] = -1; } if (passed) { - // Inject OS process loss only after that process identified itself through - // its public output and was proved distinct from the consumer and peers. - BOOL lost = kill(pids[1], SIGKILL) == 0; + // Ask the disposable crash command to terminate its own worker process. + // iOS denies a host process permission to signal an extension directly. + BOOL lost = write(descriptors[1], "crash\n", 6) == 6; int status = -1, result = 0; NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 5; while (lost && NSProcessInfo.processInfo.systemUptime < deadline) { @@ -177,7 +186,6 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { for (int i = 0; i < 3; i++) { if (jobs[i]) release(jobs[i]); if (descriptors[i] >= 0) close(descriptors[i]); } // Re-enter the full public capacity check after asynchronous teardown. if (passed) passed = capacity_check() == 0; - if (!passed && busy && pids[0] > 0 && pids[0] != getpid()) kill(pids[0], SIGKILL); fprintf(thread_stdout, "worker lifecycle and full capacity reuse: %s\n", passed ? "PASS" : "FAIL"); return passed ? 0 : 1; } @@ -224,3 +232,9 @@ int worker_pool_check_main(int argc, char **argv) { return passed ? 0 : 1; } } + +// Register only in disposable worker command catalogues for loss acceptance. +int worker_pool_crash_main(int argc, char **argv) { + kill(getpid(), SIGKILL); + return 1; +} diff --git a/tests/worker-pool.md b/tests/worker-pool.md index a362535d..b14ddb2c 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -1,8 +1,10 @@ # Extension worker pool consumer -`worker-pool.m` is an app command that calls the public C interface in `ShellWorkers/NativePane.h` through `dlsym`. It uses real extensions, XPC, socket streams and Dash. It does not mock the pool or add a production test entry point. +`worker-pool.m` calls the public C interface in `ShellWorkers/NativePane.h` through `dlsym`. It uses real extensions, XPC, socket streams and Dash. -In a disposable a-Shell mini build, add this source to the host target and register `replaceCommand("worker-pool-check", "worker_pool_check_main", true)` after `initializeEnvironment()` in `AppDelegate.swift`. Build the host with the matched ios_system#179–#184 and dash_iOS#1–#2 frameworks and libedit patch. Run these commands in the app terminal: +For a disposable app, compile this source into a dynamic framework named `WorkerPoolChecks.framework` linked with Foundation and ios_system. In the host command catalogue register `worker-pool-check` as `["WorkerPoolChecks.framework/WorkerPoolChecks", "worker_pool_check_main", "", "file"]`. In each worker catalogue register `worker-pool-crash` as `["@rpath/WorkerPoolChecks.framework/WorkerPoolChecks", "worker_pool_crash_main", "", "file"]` and add its executable PATH marker in the worker's `bin` directory. Embed the framework in the host's Frameworks directory and sign it before signing the extensions and app. These registrations belong only to the disposable test build. No production test entry point is needed. + +Use the matching ios_system session/stream and Dash terminal changes, then run these commands in the app terminal: ```sh worker-pool-check @@ -12,8 +14,10 @@ worker-pool-check lifecycle-busy worker-pool-check lifecycle-close ``` -Each command returns zero on success and prints its assertions to the command output stream. The capacity check keeps ten commands open, requires ten distinct real process IDs and independent cwd/environment, rejects the eleventh request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. The lifecycle checks cancel or close one worker, inject `SIGKILL` into another worker that identified itself through stdout, check the surviving worker's input/output/status, and repeat the full capacity check. The busy variants make the first command ignore EOF. Run them only in a disposable build: they deliberately terminate worker processes belonging to that build. +Each command returns zero on success and prints assertions to its output stream. The capacity check reads `ShellWorkerCount` from the host Info.plist (1 through 10), keeps that many commands open, requires distinct real process IDs and independent cwd/environment, rejects one additional request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. It compares directory device/inode pairs because the phone can return `/private/var/...` for a cwd requested through its `/var/...` alias. + +The lifecycle checks cancel or close one worker, ask a second worker to terminate itself with `SIGKILL`, verify the surviving worker's input/output/status, and repeat the full capacity check. The busy variants make the first command ignore EOF. iOS denies host-to-extension `kill` with `EPERM`, so process loss is injected by the normal disposable command inside the worker. Run these checks only in a disposable build: they deliberately terminate its worker processes. -For a baseline, register the same command in unmodified a-Shell mini. It must print `worker pool unavailable: FAIL` and return one. The final stock baseline and patched app were built with byte-identical consumer source (SHA-256 `6e9dd2d1bc22548c5932dbc173983a51bd423e0883bb9632bc63849532d35967`). The stock baseline returned the missing-API failure for `lifecycle-close`; the patched app completed the lifecycle and ten-slot checks. +Register the same consumer in an unmodified host for the baseline. It must print `worker pool unavailable: FAIL` and return one. A Release build must export the public C functions and callbacks loaded through `dlsym`; a consumer compiled into an executable with hidden symbols does not prove that interface usable by a dynamic command. -Verified on iOS 27 Simulator: the stock baseline failed at missing pool API; the patched app passed the single-command and ten-worker checks. A first busy-loop lifecycle run failed with `EBUSY` after invalidation; explicit worker termination made that same regression pass. Simulator does not qualify physical-device sandbox enforcement, memory limits, ten-worker device capacity, background lifetime or App Store acceptance. Keep those checks separate. +The upstream configuration remains ten workers. Historical iOS 27 Simulator tests passed ten-slot capacity and lifecycle checks. A physical run with three provisioned identities qualifies three-worker behavior only; it does not qualify ten-worker device capacity, background lifetime or App Store acceptance. From 6ad68a7605253458281947361228fea309c85c22 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:18:51 +0300 Subject: [PATCH 04/16] Avoid status RPCs while shell workers are running --- ShellWorkers/RemotePane.m | 12 ++++++++++++ tests/worker-pool.m | 30 ++++++++++++++++++++++++++++++ tests/worker-pool.md | 3 +++ 3 files changed, 45 insertions(+) diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m index 09929eb1..a60cff2a 100644 --- a/ShellWorkers/RemotePane.m +++ b/ShellWorkers/RemotePane.m @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -22,12 +23,14 @@ static void log_host_library(const char *phase) { @interface RemotePane : NSObject @property(nonatomic, strong) NSXPCConnection *connection; @property(nonatomic, strong) id proxy; +@property(nonatomic, strong) NSFileHandle *output; @property(atomic) BOOL interrupted; @property(nonatomic, strong) NSMutableArray *directories; @property(nonatomic, copy) NSString *probeDirectory; @end @implementation RemotePane - (void)dealloc { + [_output closeAndReturnError:NULL]; // Only remove our empty disposable directory, never a project tree. if (_probeDirectory) rmdir(_probeDirectory.fileSystemRepresentation); log_host_library("before_scope_release"); @@ -116,6 +119,7 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsig fd = dup(handle.fileDescriptor); if (fd < 0) error = errno; else if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { error = errno; close(fd); fd = -1; } + else pane.output = handle; } NSLog(@"Shell extension spawn: real_pid=%d error=%d startup_ms=%.3f", pid, error, (NSProcessInfo.processInfo.systemUptime - started) * 1000); }]; @@ -132,6 +136,14 @@ int ashell_pane_poll(void *job, int *status_out) { if (!pane || !status_out) return -EINVAL; // 137 is this backend's lost-worker status, not a recovered waitpid status. if (pane.interrupted) { *status_out = 137; return 1; } + // The worker closes its socket streams before publishing completion. A + // hangup is observable even with unread output; keep polling local until + // then instead of waking the worker with an XPC request on every poll. + struct pollfd output = {.fd = pane.output.fileDescriptor, .events = POLLIN}; + int ready = poll(&output, 1, 0); + if (ready < 0) return errno == EINTR ? 0 : -errno; + if (output.revents & POLLNVAL) return -EBADF; + if (!(output.revents & (POLLHUP | POLLERR))) return 0; __block int result = -EPIPE; [pane.proxy poll:^(int value, int status) { result = value; *status_out = status; }]; if (result == -EPIPE) { pane.interrupted = YES; *status_out = 137; return 1; } diff --git a/tests/worker-pool.m b/tests/worker-pool.m index 2a4a9ddc..f2a5f429 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -190,9 +190,39 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { return passed ? 0 : 1; } +// Exit status must not depend on the consumer draining pending output first. +static int completion_check(void) { + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); + int (*pollJob)(void *, int *) = dlsym(RTLD_DEFAULT, "ashell_pane_poll"); + void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); + if (!spawn || !pollJob || !release) return 1; + NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; + int descriptor = -1, status = -1, result = 0; + void *job = NULL; + int error = spawn("dash -c 'printf pending-output; exit 7'", directory.fileSystemRepresentation, 80, 24, NULL, &descriptor, &job); + if (error) { fprintf(thread_stdout, "completion startup=%d: FAIL\n", error); return 1; } + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 10; + while (!result && NSProcessInfo.processInfo.systemUptime < deadline) { + result = pollJob(job, &status); + if (!result) usleep(10000); + } + BOOL passed = result == 1 && status == 7; + status = -1; + passed = passed && pollJob(job, &status) == 1 && status == 7; + char output[64] = {0}; + ssize_t count = passed ? read(descriptor, output, sizeof(output) - 1) : -1; + passed = passed && count == 14 && !strcmp(output, "pending-output"); + if (passed) passed = read(descriptor, output, 1) == 0; + release(job); + close(descriptor); + fprintf(thread_stdout, "status before output drain and repeated status: %s\n", passed ? "PASS" : "FAIL"); + return passed ? 0 : 1; +} + // Run as a real app command. The same consumer must fail on the stock app. int worker_pool_check_main(int argc, char **argv) { @autoreleasepool { + if (argc == 2 && !strcmp(argv[1], "completion")) return completion_check(); if (argc == 2 && !strcmp(argv[1], "capacity")) return capacity_check(); if (argc == 2 && !strcmp(argv[1], "lifecycle")) return lifecycle_check(NO, NO); if (argc == 2 && !strcmp(argv[1], "lifecycle-busy")) return lifecycle_check(YES, NO); diff --git a/tests/worker-pool.md b/tests/worker-pool.md index b14ddb2c..70d22e1b 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -8,6 +8,7 @@ Use the matching ios_system session/stream and Dash terminal changes, then run t ```sh worker-pool-check +worker-pool-check completion worker-pool-check capacity worker-pool-check lifecycle worker-pool-check lifecycle-busy @@ -16,6 +17,8 @@ worker-pool-check lifecycle-close Each command returns zero on success and prints assertions to its output stream. The capacity check reads `ShellWorkerCount` from the host Info.plist (1 through 10), keeps that many commands open, requires distinct real process IDs and independent cwd/environment, rejects one additional request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. It compares directory device/inode pairs because the phone can return `/private/var/...` for a cwd requested through its `/var/...` alias. +The completion check leaves output unread until polling reports status 7, checks that a second poll preserves it, then reads the exact pending output and EOF. + The lifecycle checks cancel or close one worker, ask a second worker to terminate itself with `SIGKILL`, verify the surviving worker's input/output/status, and repeat the full capacity check. The busy variants make the first command ignore EOF. iOS denies host-to-extension `kill` with `EPERM`, so process loss is injected by the normal disposable command inside the worker. Run these checks only in a disposable build: they deliberately terminate its worker processes. Register the same consumer in an unmodified host for the baseline. It must print `worker pool unavailable: FAIL` and return one. A Release build must export the public C functions and callbacks loaded through `dlsym`; a consumer compiled into an executable with hidden symbols does not prove that interface usable by a dynamic command. From 1ac4bdb3bf15bd9350d25ec60cbdb5f46030ef05 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Tue, 20 Oct 2026 20:16:41 +0300 Subject: [PATCH 05/16] Cap concurrent shell workers at the physical core count, raisable in Settings The host runs min(worker_limit setting, hw.physicalcpu, bundled ShellWorkerCount) workers at once and returns ENOSPC beyond that. ShellWorkers/generate-targets.sh (POSIX sh and awk, like the other scripts of the repo) keeps the extension targets and the Settings list in line with ShellWorkerCount. The new Settings strings are localized in the existing Root.strings files. tests/worker-pool.m gains a limit check. --- README.md | 4 +- Resources_mini/Settings.bundle/Root.plist | 40 +++++ .../Settings.bundle/en.lproj/Root.strings | Bin 1238 -> 1466 bytes .../Settings.bundle/es.lproj/Root.strings | Bin 1552 -> 1796 bytes .../Settings.bundle/fr.lproj/Root.strings | Bin 1560 -> 1800 bytes .../Settings.bundle/it.lproj/Root.strings | Bin 1498 -> 1732 bytes .../Settings.bundle/ko.lproj/Root.strings | Bin 1456 -> 1628 bytes ShellWorkers/Host.swift | 26 ++- ShellWorkers/NativePane.h | 5 + ShellWorkers/RemotePane.m | 3 + ShellWorkers/generate-targets.sh | 148 ++++++++++++++++++ tests/worker-pool.m | 52 +++++- tests/worker-pool.md | 5 +- 13 files changed, 271 insertions(+), 12 deletions(-) create mode 100755 ShellWorkers/generate-targets.sh diff --git a/README.md b/README.md index c54f7dce..cb4a40c6 100644 --- a/README.md +++ b/README.md @@ -111,10 +111,10 @@ If you enable VoiceOver in Settings, a-Shell will work with VoiceOver: reading c ## Independent shell workers -On iOS 26 and later, the mini target includes ten dedicated Generic Non-UI extensions, `ShellWorkerA` through `ShellWorkerJ`. Each worker owns one native command and its ios_system state. The original Intents and IntentsUI targets remain separate. Consumers call `ashell_pane_spawn` from a background thread, read the returned full-duplex descriptor, poll completion and release the opaque handle. The API and stream ownership rules are in `ShellWorkers/NativePane.h`. +On iOS 26 and later, the mini target includes dedicated Generic Non-UI extensions, `ShellWorkerA` onward (ten at present; `ShellWorkerCount` in `a-Shell-mini-Info.plist` is the count, and `ShellWorkers/generate-targets.sh [N]` brings the project targets and the Settings list in line with it, a second run changes nothing). The host runs as many workers at once as the "Shell workers" setting says (`worker_limit` in Settings; Automatic is one per physical core, `hw.physicalcpu`), never more than the bundled count; a request beyond that gets `ENOSPC`. Each worker owns one native command and its ios_system state. The original Intents and IntentsUI targets remain separate. Consumers call `ashell_pane_spawn` from a background thread, read the returned full-duplex descriptor, poll completion and release the opaque handle. The API and stream ownership rules are in `ShellWorkers/NativePane.h`. The host retains each `AppExtensionProcess` and XPC connection until release or interruption. A full pool returns `ENOSPC`; earlier iOS versions return `ENOTSUP`. Cancel and release terminate the dedicated worker through XPC before freeing its reservation; releasing an ExtensionFoundation assertion alone permits process reuse. Commands that ignore EOF therefore cannot retain a released slot. A lost worker reports status 137 while the host and other workers remain available. Directory access uses security-scoped bookmarks and is checked with actual file operations in the worker. -Workers share the host's command libraries. Build with ios_system changes #179–#184 and dash_iOS#1–#2, including the matched libedit dependency described there. The build derives each worker's catalogue and executable markers from `Resources_mini/commandDictionary.plist`; it generates the ExtensionFoundation binding from `PRODUCT_BUNDLE_PREFIX`. Keep worker versions in `ShellWorkers/Worker.xcconfig` aligned with the containing app. The mini bundle suffixes are `.ShellWorkerA` through `.ShellWorkerJ`; each requires its own App ID and profile for a device build. +Workers share the host's command libraries. Build with ios_system changes #179–#184 and dash_iOS#1–#2, including the matched libedit dependency described there. The build derives each worker's catalogue and executable markers from `Resources_mini/commandDictionary.plist`; it generates the ExtensionFoundation binding from `PRODUCT_BUNDLE_PREFIX`. Keep worker versions in `ShellWorkers/Worker.xcconfig` aligned with the containing app. The mini bundle suffixes are `.ShellWorkerA` onward; each requires its own App ID and profile for a device build. `tests/worker-pool.m` is a real app-command consumer for Simulator qualification. Device memory limits, background execution without other host background modes, and App Store acceptance require separate validation. Retaining the process handle provides no promise of unlimited background execution. diff --git a/Resources_mini/Settings.bundle/Root.plist b/Resources_mini/Settings.bundle/Root.plist index cfde6e7e..4d06095b 100644 --- a/Resources_mini/Settings.bundle/Root.plist +++ b/Resources_mini/Settings.bundle/Root.plist @@ -144,6 +144,46 @@ DefaultValue + + + Type + PSMultiValueSpecifier + Title + Shell workers (Automatic: one per core) + Key + worker_limit + DefaultValue + 0 + Titles + + Automatic + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + + Values + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + + + diff --git a/Resources_mini/Settings.bundle/en.lproj/Root.strings b/Resources_mini/Settings.bundle/en.lproj/Root.strings index 9a278b87f41042aa933db62fe0a119d61e8ebb13..8e0a92440e49143735c6dd39d856ee768b3030c2 100644 GIT binary patch delta 237 zcmcb{xr=+lHI{lMhG2#ahE#?eAXH!|XUJzLV#o&aix`T5d<_OihEj$SplB{bB9P8x zNM^7Cisv)r0o5ol6o6GK07XIiQW-QElz^hPKun~$sU#R|&As1z?p5Kv9ssR0d53C7`G+5GyeR07deFGO0k5ih-tp%qvE+3v6~F uis6MoWgufgR+Iv*09lX-GzMfrFk>l@1+u`JfeT1tIt*box*Wt@h)w`4*(*r^ delta 7 OcmeC+o58a|f(-x(fdUBt diff --git a/Resources_mini/Settings.bundle/it.lproj/Root.strings b/Resources_mini/Settings.bundle/it.lproj/Root.strings index 1604559b04a8f0388b0a573c73c753d6a0cf4994..5dce9216346f18d47fde7383c8c19314513de062 100644 GIT binary patch delta 243 zcmcb`eS~+zE!KJ^hG2#ahE#?eAXH!|XUJzLV#o&aix`T5d<_OihEj$SplB{bB9P8x zNM^7Cisv)r0o5ol6o6GK07XIiQW-QElz^hPK&-?N02Ijw%A^8KDhBFQ0FnrspeARd g7@ZF`ycB47J`TgJ8MuH(V>$|9Ev8&PPzOjK07}d&Z2$lO delta 7 OcmX@Ydy9L+Emi;x=mSOo diff --git a/Resources_mini/Settings.bundle/ko.lproj/Root.strings b/Resources_mini/Settings.bundle/ko.lproj/Root.strings index 207d03fba17343607bbbb70da88abfa0878322f2..9561556aea1b6ffa9d05196f87ed0c5e74fbdd93 100644 GIT binary patch delta 181 zcmdnMeTQem2G)8dhG2#ahE#?eAXH!|XUJzLV#o&aix`T5d<_OihEj$SplB{bB9P8x zNM^7Cisv)r0o5ol6o6GK07XIiQW-QElz^hPK&-@2aZrI_;_;(LCmaWvGvWBn%^;m2 j=eHdFxk-T`;_8eIK-Ibo)(l)g#hBJ03<7CY0;>Z6{Ix3h delta 7 Ocmcb^vw?fV237zKWCIBR diff --git a/ShellWorkers/Host.swift b/ShellWorkers/Host.swift index 9028e57e..bf9c3630 100644 --- a/ShellWorkers/Host.swift +++ b/ShellWorkers/Host.swift @@ -7,6 +7,29 @@ extension AppExtensionPoint { static var shellWorker: AppExtensionPoint { Name("ShellWorker") } } +// Concurrent workers: the user's "worker_limit" setting (0 or unset = automatic, the physical +// core count), never more than the bundled ShellWorkerCount extensions. 0 means no workers. +enum ShellWorkerCapacity { + static var bundled: Int { + let configured = Bundle.main.object(forInfoDictionaryKey: "ShellWorkerCount") + return (configured as? NSNumber)?.intValue ?? Int(configured as? String ?? "") ?? 0 + } + + static var physicalCores: Int { + var count: Int32 = 0 + var size = MemoryLayout.size + return sysctlbyname("hw.physicalcpu", &count, &size, nil, 0) == 0 ? Int(count) : 1 + } + + static var current: Int { + let requested = UserDefaults.standard.integer(forKey: "worker_limit") + return min(requested > 0 ? requested : physicalCores, bundled) + } +} + +@_cdecl("ashell_extension_capacity") +func shellExtensionCapacity() -> Int32 { Int32(ShellWorkerCapacity.current) } + // Process lifetime and discovery belong to MainActor. Blocking C ABI calls wait // only on the calling runner thread, never on the UI actor. @available(iOS 26.0, *) @@ -31,8 +54,7 @@ final class ShellWorkerPool { } let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: .shellWorker) for _ in 0..<100 { - let configured = Bundle.main.object(forInfoDictionaryKey: "ShellWorkerCount") - let capacity = (configured as? NSNumber)?.intValue ?? Int(configured as? String ?? "") ?? 0 + let capacity = ShellWorkerCapacity.current if capacity > 0 && slots.count >= capacity { throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENOSPC), userInfo: [NSLocalizedDescriptionKey: "All shell workers are in use. Close a pane before opening another."]) } diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h index 34f4294e..4a4f7172 100644 --- a/ShellWorkers/NativePane.h +++ b/ShellWorkers/NativePane.h @@ -8,6 +8,11 @@ extern "C" { // Keep the public C ABI discoverable in Release builds with hidden visibility. #pragma GCC visibility push(default) +// Host only: how many panes can run at once, so ashell_pane_spawn returns ENOSPC for the next one. +// The "worker_limit" setting (0 = automatic) or else the device's physical core count, +// limited to the bundled worker extensions. Read on every spawn, so a change applies at once. +int ashell_pane_capacity(void); + // command/cwd must be nonempty UTF-8; cwd must be an absolute accessible directory. // envp is NULL or a NULL-terminated list of UTF-8 key=value overrides, copied before return. // Dimensions are 1..9999. Returns 0 or positive errno; failure sets outputs to -1/NULL. diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m index a60cff2a..5e9c0d13 100644 --- a/ShellWorkers/RemotePane.m +++ b/ShellWorkers/RemotePane.m @@ -9,6 +9,7 @@ extern void ashell_extension_connect(void (^)(NSXPCConnection *, NSError *)); extern void ashell_extension_disconnect(NSXPCConnection *); +extern int ashell_extension_capacity(void); static void log_host_library(const char *phase) { int saved = errno; @@ -42,6 +43,8 @@ - (void)dealloc { } @end +int ashell_pane_capacity(void) { return ashell_extension_capacity(); } + int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { if (fd_out) *fd_out = -1; if (job_out) *job_out = NULL; diff --git a/ShellWorkers/generate-targets.sh b/ShellWorkers/generate-targets.sh new file mode 100755 index 00000000..30b77d90 --- /dev/null +++ b/ShellWorkers/generate-targets.sh @@ -0,0 +1,148 @@ +#!/bin/sh +# Make the project carry exactly N ShellWorker extension targets. +# +# ShellWorkers/generate-targets.sh bring everything in line with ShellWorkerCount +# ShellWorkers/generate-targets.sh N set ShellWorkerCount to N (1-26) first +# +# ShellWorkerCount in a-Shell-mini-Info.plist is the one source. ShellWorkerA is the template: +# every other worker is a copy of its objects (target, build configurations, build phases and +# files, product, embed entry, host dependency) with ids derived from the letter, so a second run +# changes nothing. The "Shell workers" list in Resources_mini/Settings.bundle/Root.plist is +# regenerated between its BEGIN/END markers. +set -eu +cd "$(dirname "$0")/.." + +PROJECT=a-Shell.xcodeproj/project.pbxproj +INFO=a-Shell-mini-Info.plist +SETTINGS=Resources_mini/Settings.bundle/Root.plist +BEGIN='' +END='' +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +if [ $# -gt 0 ]; then + case $1 in + '' | *[!0-9]*) echo "usage: $0 [N]" >&2; exit 2 ;; + esac + if [ "$1" -lt 1 ] || [ "$1" -gt 26 ]; then echo "N must be 1-26" >&2; exit 2; fi + sed -E "/ShellWorkerCount/{n;s/[0-9]+$1 "$tmp/info" + if ! cmp -s "$tmp/info" "$INFO"; then cat "$tmp/info" > "$INFO"; echo "info: ShellWorkerCount = $1"; fi +fi +count=$(plutil -extract ShellWorkerCount raw -o - "$INFO") + +# Project: add or remove whole workers. +awk -v count="$count" ' +function val(id, key, i, s) { + for (i = start[id] + 1; i < endl[id]; i++) + if (index(line[i], "\t\t\t" key " = ") == 1) { + s = line[i]; sub(/^\t+[A-Za-z]+ = "?/, "", s); return substr(s, 1, 24) + } + return "" +} +function items(id, key, out, i, s, k, inlist) { + k = 0 + for (i = start[id] + 1; i < endl[id]; i++) { + if (index(line[i], "\t\t\t" key " = (") == 1) { inlist = 1; continue } + if (inlist && line[i] == "\t\t\t);") break + if (inlist) { s = line[i]; sub(/^\t+"?/, "", s); out[++k] = substr(s, 1, 24) } + } + return k +} +function closure(letter, out, prod, t, cl, k, i, j, a, b, ph, nb, np) { + t = tid[letter]; k = 0 + out[++k] = t + cl = val(t, "buildConfigurationList"); out[++k] = cl + nb = items(cl, "buildConfigurations", a); for (i = 1; i <= nb; i++) out[++k] = a[i] + np = items(t, "buildPhases", ph); for (i = 1; i <= np; i++) out[++k] = ph[i] + for (i = 1; i <= np; i++) { nb = items(ph[i], "files", b); for (j = 1; j <= nb; j++) out[++k] = b[j] } + prod = val(t, "productReference"); out[++k] = prod + out[++k] = embed[prod] + out[++k] = dep[t] + return k +} +function listline(id, i) { + for (i = 1; i <= n; i++) + if (line[i] ~ /^\t+"?[0-9A-F]+"?( \/\*.*\*\/)?,$/ && index(line[i], id) > 0) return i + print "list element " id " not found" > "/dev/stderr"; exit 1 +} +function newid(letter, old, cmd, h) { + cmd = "printf %s ShellWorker" letter ":" old " | shasum -a 256" + cmd | getline h; close(cmd) + return toupper(substr(h, 1, 24)) +} +{ line[NR] = $0 } +END { + n = NR; cur = "" + for (i = 1; i <= n; i++) { + if (line[i] ~ /^\t\t"?[0-9A-F]+"?( \/\*.*\*\/)? = \{$/) { + s = line[i]; sub(/^\t\t"?/, "", s); cur = substr(s, 1, 24); start[cur] = i + } else if (cur != "" && line[i] == "\t\t};") { endl[cur] = i; cur = "" } + } + for (id in start) { + kind = line[start[id] + 1] + if (kind ~ /PBXNativeTarget/) { + for (i = start[id]; i < endl[id]; i++) + if (line[i] ~ /^\t\t\tname = "?ShellWorker[A-Z]"?;$/) { s = line[i]; tid[substr(s, index(s, "ShellWorker") + 11, 1)] = id } + } else if (kind ~ /PBXBuildFile/) embed[val(id, "fileRef")] = id + else if (kind ~ /PBXTargetDependency/) dep[val(id, "target")] = id + } + L = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + for (present = 0; substr(L, present + 1, 1) in tid; present++) ; + total = 0; for (x in tid) total++ + if (total != present) { print "workers in the project are not a prefix of A..Z" > "/dev/stderr"; exit 1 } + for (c = present; c > count; c--) { # remove the surplus, last letter first + m = closure(substr(L, c, 1), T) + for (k = 1; k <= m; k++) for (i = start[T[k]]; i <= endl[T[k]]; i++) skip[i] = 1 + skip[listline(T[1])] = 1; skip[listline(T[m - 1])] = 1; skip[listline(T[m])] = 1 + } + if (count > present) { + m = closure("A", T); closure(substr(L, present, 1), P) + for (c = present + 1; c <= count; c++) { + letter = substr(L, c, 1) + for (k = 1; k <= m; k++) map[T[k]] = newid(letter, T[k]) + for (k = 1; k <= m; k++) { + for (i = start[T[k]]; i <= endl[T[k]]; i++) { + s = line[i] + for (j = 1; j <= m; j++) gsub(T[j], map[T[j]], s) + gsub(/ShellWorkerA/, "ShellWorker" letter, s) + after[endl[P[k]]] = after[endl[P[k]]] s "\n" + } + } + for (k = 1; k <= 3; k++) { # target, embed and dependency lists + id = (k == 1) ? T[1] : (k == 2) ? T[m - 1] : T[m] + pid = (k == 1) ? P[1] : (k == 2) ? P[m - 1] : P[m] + at = listline(pid); ind = line[at]; sub(/[^\t].*$/, "", ind) + after[at] = after[at] ind "\"" map[id] "\",\n" + } + } + } + for (i = 1; i <= n; i++) { if (!skip[i]) print line[i]; if (i in after) printf "%s", after[i] } +}' "$PROJECT" > "$tmp/project" +if cmp -s "$tmp/project" "$PROJECT"; then echo "project: $count workers, no change" +else cat "$tmp/project" > "$PROJECT"; echo "project: now $count workers"; fi + +# Settings: "Automatic" (0) and 1..N between the markers. +{ + printf '\t\t%s\n\t\t\n' "$BEGIN" + printf '\t\t\tType\n\t\t\tPSMultiValueSpecifier\n' + printf '\t\t\tTitle\n\t\t\tShell workers (Automatic: one per core)\n' + printf '\t\t\tKey\n\t\t\tworker_limit\n' + printf '\t\t\tDefaultValue\n\t\t\t0\n' + printf '\t\t\tTitles\n\t\t\t\n\t\t\t\tAutomatic\n' + seq 1 "$count" | sed 's|.*|\t\t\t\t&|' + printf '\t\t\t\n\t\t\tValues\n\t\t\t\n\t\t\t\t0\n' + seq 1 "$count" | sed 's|.*|\t\t\t\t&|' + printf '\t\t\t\n\t\t\n\t\t%s\n' "$END" +} > "$tmp/block" +if grep -qF "$BEGIN" "$SETTINGS"; then + awk -v b="$BEGIN" -v e="$END" -v f="$tmp/block" ' + index($0, b) { while ((getline l < f) > 0) print l; skipping = 1 } + !skipping { print } + skipping && index($0, e) { skipping = 0 }' "$SETTINGS" > "$tmp/settings" +else + awk -v f="$tmp/block" ' + /^\t<\/array>$/ && !done { while ((getline l < f) > 0) print l; done = 1 } + { print }' "$SETTINGS" > "$tmp/settings" +fi +if cmp -s "$tmp/settings" "$SETTINGS"; then echo "settings: no change" +else cat "$tmp/settings" > "$SETTINGS"; echo "settings: updated"; fi diff --git a/tests/worker-pool.m b/tests/worker-pool.m index f2a5f429..90a77bf7 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -7,8 +7,11 @@ #include #include #include +#include +#define MAX_WORKERS 64 + // Keep each command alive at its public stdin boundary while the other slots start. static int capacity_check(void) { int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); @@ -16,13 +19,16 @@ static int capacity_check(void) { void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); if (!spawn || !pollJob || !release) { fputs("worker pool unavailable: FAIL\n", thread_stdout); return 1; } NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:[@"Documents/worker-pool-" stringByAppendingString:NSUUID.UUID.UUIDString]]; - const int capacity = [[NSBundle.mainBundle objectForInfoDictionaryKey:@"ShellWorkerCount"] intValue]; - if (capacity < 1 || capacity > 10) return 64; - void *jobs[10] = {0}; - int descriptors[10]; - char output[10][2048] = {{0}}; - size_t used[10] = {0}; - int pids[10] = {0}; + // The cap in force now: the setting or the core count, limited to the bundled extensions. + int (*capacityOf)(void) = dlsym(RTLD_DEFAULT, "ashell_pane_capacity"); + const int capacity = capacityOf ? capacityOf() : [[NSBundle.mainBundle objectForInfoDictionaryKey:@"ShellWorkerCount"] intValue]; + if (capacity < 1 || capacity > MAX_WORKERS) return 64; + void *jobs[MAX_WORKERS] = {0}; + int descriptors[MAX_WORKERS]; + static char output[MAX_WORKERS][2048]; + memset(output, 0, sizeof(output)); + size_t used[MAX_WORKERS] = {0}; + int pids[MAX_WORKERS] = {0}; BOOL passed = YES; for (int i = 0; i < capacity; i++) descriptors[i] = -1; for (int i = 0; i < capacity; i++) { @@ -219,11 +225,43 @@ static int completion_check(void) { return passed ? 0 : 1; } +// The cap follows the setting: default is the physical core count, a larger setting allows more +// concurrent workers up to the bundled count, a smaller one fewer, and ENOSPC comes right after it. +static int limit_check(void) { + int (*capacityOf)(void) = dlsym(RTLD_DEFAULT, "ashell_pane_capacity"); + if (!capacityOf) { fputs("worker pool capacity unavailable: FAIL\n", thread_stdout); return 1; } + int bundled = [[NSBundle.mainBundle objectForInfoDictionaryKey:@"ShellWorkerCount"] intValue]; + int cores = 0; + size_t size = sizeof(cores); + if (sysctlbyname("hw.physicalcpu", &cores, &size, NULL, 0) || cores < 1) return 64; + NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults; + id previous = [defaults objectForKey:@"worker_limit"]; + BOOL passed = YES; + [defaults removeObjectForKey:@"worker_limit"]; + int expected = cores < bundled ? cores : bundled; + fprintf(thread_stdout, "default capacity=%d expected=%d (cores=%d bundled=%d): %s\n", capacityOf(), expected, cores, bundled, capacityOf() == expected ? "PASS" : "FAIL"); + passed = capacityOf() == expected; + if (passed) passed = capacity_check() == 0; + // A setting of 2, the bundled count and more than the bundled count. + int settings[] = {2, bundled, bundled + 5}; + for (int i = 0; passed && i < 3; i++) { + [defaults setInteger:settings[i] forKey:@"worker_limit"]; + expected = settings[i] < bundled ? settings[i] : bundled; + passed = capacityOf() == expected; + fprintf(thread_stdout, "worker_limit=%d capacity=%d expected=%d: %s\n", settings[i], capacityOf(), expected, passed ? "PASS" : "FAIL"); + if (passed) passed = capacity_check() == 0; + } + if (previous) [defaults setObject:previous forKey:@"worker_limit"]; else [defaults removeObjectForKey:@"worker_limit"]; + fprintf(thread_stdout, "worker limit setting: %s\n", passed ? "PASS" : "FAIL"); + return passed ? 0 : 1; +} + // Run as a real app command. The same consumer must fail on the stock app. int worker_pool_check_main(int argc, char **argv) { @autoreleasepool { if (argc == 2 && !strcmp(argv[1], "completion")) return completion_check(); if (argc == 2 && !strcmp(argv[1], "capacity")) return capacity_check(); + if (argc == 2 && !strcmp(argv[1], "limit")) return limit_check(); if (argc == 2 && !strcmp(argv[1], "lifecycle")) return lifecycle_check(NO, NO); if (argc == 2 && !strcmp(argv[1], "lifecycle-busy")) return lifecycle_check(YES, NO); if (argc == 2 && !strcmp(argv[1], "lifecycle-close")) return lifecycle_check(YES, YES); diff --git a/tests/worker-pool.md b/tests/worker-pool.md index 70d22e1b..4dacd8b3 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -10,15 +10,18 @@ Use the matching ios_system session/stream and Dash terminal changes, then run t worker-pool-check worker-pool-check completion worker-pool-check capacity +worker-pool-check limit worker-pool-check lifecycle worker-pool-check lifecycle-busy worker-pool-check lifecycle-close ``` -Each command returns zero on success and prints assertions to its output stream. The capacity check reads `ShellWorkerCount` from the host Info.plist (1 through 10), keeps that many commands open, requires distinct real process IDs and independent cwd/environment, rejects one additional request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. It compares directory device/inode pairs because the phone can return `/private/var/...` for a cwd requested through its `/var/...` alias. +Each command returns zero on success and prints assertions to its output stream. The capacity check asks the host for the effective cap (`ashell_pane_capacity`: the `worker_limit` setting, or the physical core count when unset, at most `ShellWorkerCount` from the host Info.plist), keeps that many commands open, requires distinct real process IDs and independent cwd/environment, rejects one additional request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. It compares directory device/inode pairs because the phone can return `/private/var/...` for a cwd requested through its `/var/...` alias. The completion check leaves output unread until polling reports status 7, checks that a second poll preserves it, then reads the exact pending output and EOF. +The limit check requires the default cap to equal `min(hw.physicalcpu, ShellWorkerCount)`, then sets `worker_limit` to 2, to the bundled count and above it (clamped to the bundled count), repeats the capacity check under each and restores the setting. Build the host with more workers than cores to see the default and the raised cap differ. + The lifecycle checks cancel or close one worker, ask a second worker to terminate itself with `SIGKILL`, verify the surviving worker's input/output/status, and repeat the full capacity check. The busy variants make the first command ignore EOF. iOS denies host-to-extension `kill` with `EPERM`, so process loss is injected by the normal disposable command inside the worker. Run these checks only in a disposable build: they deliberately terminate its worker processes. Register the same consumer in an unmodified host for the baseline. It must print `worker pool unavailable: FAIL` and return one. A Release build must export the public C functions and callbacks loaded through `dlsym`; a consumer compiled into an executable with hidden symbols does not prove that interface usable by a dynamic command. From 12c08494daf05219d22d6dfbd42f9365ccee21df Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:25:04 +0300 Subject: [PATCH 06/16] Add ashell_pane_spawn_ex: separate stderr and an optional terminal for a pane --- ShellWorkers/NativePane.h | 21 ++++++++++++++++ ShellWorkers/NativePane.m | 53 ++++++++++++++++++++++++++++++++++----- ShellWorkers/PaneWire.h | 2 +- ShellWorkers/RemotePane.m | 23 ++++++++++++++--- ShellWorkers/Worker.m | 32 ++++++++++++----------- 5 files changed, 106 insertions(+), 25 deletions(-) diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h index 4a4f7172..6c3da7ab 100644 --- a/ShellWorkers/NativePane.h +++ b/ShellWorkers/NativePane.h @@ -1,6 +1,8 @@ #ifndef ASHELL_NATIVE_PANE_H #define ASHELL_NATIVE_PANE_H +#include + #ifdef __cplusplus extern "C" { #endif @@ -23,6 +25,25 @@ int ashell_pane_capacity(void); int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out); +// Options for ashell_pane_spawn_ex. The caller sets size to sizeof(ashell_pane_options). +typedef struct ashell_pane_options { + size_t size; + // Nonzero: the command sees a terminal on stdin, stdout and stderr (isatty is true). + // Zero: it sees plain streams, as when the caller redirects them to a file or a pipe. + int tty; + // Nonzero: stderr is a separate stream; its read side is written to stderr_fd. + int separate_stderr; + // Output, -1 unless separate_stderr succeeded. The caller owns and closes it. Drain it + // as well as the main fd; a full unread stderr blocks the command like a full stdout. + int stderr_fd; +} ashell_pane_options; + +// ashell_pane_spawn with options. ashell_pane_spawn is this call with tty = 1 and +// separate_stderr = 0, so its behaviour is unchanged. Returns 0 or positive errno. +int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, + const char *const *envp, ashell_pane_options *options, + int *fd_out, void **job_out); + // Returns 0 running, 1 exited (writes final command status), or -errno. // Repeated polling after exit preserves status. Drain the returned fd to EOF independently. // A cleanup/restore error returns -errno after completion instead of hiding the failure. diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m index f48a8411..94cdd49f 100644 --- a/ShellWorkers/NativePane.m +++ b/ShellWorkers/NativePane.m @@ -32,6 +32,8 @@ int peer_control, input_closed, is_pty; unsigned char eof_key; FILE *streams[3]; + // Without a tty the session streams differ from the command streams, so stock isatty reports false. + FILE *session_in, *session_out, *session_err; void *registration; char key[64]; char *command, *cwd, *previous_cwd; @@ -260,6 +262,12 @@ static int request_input(pane_input_relay *relay, int request, command_input *co return error; } +static void baseline_streams(pane_job *job, FILE *input) { + ios_setStreams(job->session_in ? job->session_in : input, + job->session_out ? job->session_out : job->streams[1], + job->session_err ? job->session_err : job->streams[2]); +} + static int stop_input_relay(pane_job *job) { pane_input_relay *relay = job->input_relay; if (!relay) return 0; @@ -276,7 +284,7 @@ static int stop_input_relay(pane_job *job) { if (relay->command) { command_input *command = relay->command; ashell_wait_owned_streams(command->registration); - ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + baseline_streams(job, job->streams[0]); ios_settty(job->streams[0]); ashell_unregister_owned_streams(&command->registration); if (fclose(command->reader) && !error) error = errno; @@ -409,7 +417,7 @@ static int prepare_input_relay(pane_job *job) { *token = command; // Stock tty detection compares command streams against the session streams. // Keep baseline outputs so explicit redirects remain non-terminal streams. - ios_setStreams(command->reader, job->streams[1], job->streams[2]); + baseline_streams(job, command->reader); // Stock ios_opentty borrowers must receive this command's input as well. ios_settty(command->reader); pthread_setcancelstate(cancellation, NULL); @@ -427,7 +435,7 @@ static int prepare_input_relay(pane_job *job) { // Dash. Borrow counts include asynchronous children through their cleanup. ashell_wait_owned_streams(command->registration); pane_job *job = command->job; - ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + baseline_streams(job, job->streams[0]); ios_settty(job->streams[0]); int retired = request_input(command->relay, INPUT_RETIRE, command); if (!error) error = retired; @@ -467,6 +475,11 @@ static int close_streams(pane_job *job) { if (job->streams[i] && fclose(job->streams[i]) && !error) error = errno; job->streams[i] = NULL; } + FILE **session[3] = {&job->session_in, &job->session_out, &job->session_err}; + for (int i = 0; i < 3; i++) { + if (*session[i] && fclose(*session[i]) && !error) error = errno; + *session[i] = NULL; + } return error; } @@ -484,7 +497,7 @@ static int socket_options(int fd) { // This runner is new: no parent session or TLS streams are switched or overwritten. ios_switchSession(job->key); ios_setContext(job->key); - ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + baseline_streams(job, job->streams[0]); ios_settty(job->streams[0]); thread_stdin = job->streams[0]; thread_stdout = job->streams[1]; @@ -558,8 +571,18 @@ static int socket_options(int fd) { int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { + ashell_pane_options options = {.size = sizeof(options), .tty = 1}; + return ashell_pane_spawn_ex(command, cwd, cols, rows, envp, &options, fd_out, job_out); +} + +int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, + const char *const *envp, ashell_pane_options *options, + int *fd_out, void **job_out) { if (fd_out) *fd_out = -1; if (job_out) *job_out = NULL; + if (!options || options->size < sizeof(*options)) return EINVAL; + options->stderr_fd = -1; + int peer_err = -1; if (!fd_out || !job_out || !command || !*command || !cwd || cwd[0] != '/' || !cols || cols > 9999 || !rows || rows > 9999) return EINVAL; @autoreleasepool { @@ -647,8 +670,18 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, error = job->is_pty ? (fcntl(job->peer_control, F_SETFD, FD_CLOEXEC) ? errno : 0) : socket_options(job->peer_control); if (!error && job->is_pty && fcntl(peer, F_SETFD, FD_CLOEXEC)) error = errno; if (error) { close(child); goto failed; } + int err_child = -1; + if (options->separate_stderr) { + int pair[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair)) { error = errno; goto failed; } + peer_err = pair[0]; + err_child = pair[1]; + error = socket_options(peer_err); + if (!error) error = socket_options(err_child); + if (error) { close(err_child); goto failed; } + } for (int i = 0; i < 3; i++) { - int fd = i == 0 ? child : dup(child); + int fd = i == 0 ? child : i == 2 && err_child >= 0 ? err_child : dup(child); if (fd < 0) { error = errno; goto failed; } job->streams[i] = fdopen(fd, i == 0 ? "r" : "w"); if (!job->streams[i]) { error = errno; close(fd); goto failed; } @@ -657,6 +690,12 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, int buffering = !job->is_pty && i == 1 ? _IOLBF : _IONBF; if (setvbuf(job->streams[i], NULL, buffering, 0)) { error = EIO; goto failed; } } + if (!options->tty) { + job->session_in = fopen("/dev/null", "r"); + job->session_out = fopen("/dev/null", "w"); + job->session_err = fopen("/dev/null", "w"); + if (!job->session_in || !job->session_out || !job->session_err) { error = errno; goto failed; } + } if (!job->is_pty) error = prepare_input_relay(job); if (!error) error = ashell_register_owned_streams(job->streams[0], job->streams[1], job->streams[2], &job->registration); if (error) goto failed; @@ -673,13 +712,15 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, while (!job->initialized) pthread_cond_wait(&job->ready, &job->mutex); error = job->startup_error; pthread_mutex_unlock(&job->mutex); - if (error) { close(peer); drop_reference(job); return error; } + if (error) { close(peer); if (peer_err >= 0) close(peer_err); drop_reference(job); return error; } *fd_out = peer; + options->stderr_fd = peer_err; *job_out = job; return 0; failed: close_streams(job); if (peer >= 0) close(peer); + if (peer_err >= 0) close(peer_err); drop_reference(job); atomic_store(&pane_in_flight, 0); return error; diff --git a/ShellWorkers/PaneWire.h b/ShellWorkers/PaneWire.h index a1b80a9c..63ddec83 100644 --- a/ShellWorkers/PaneWire.h +++ b/ShellWorkers/PaneWire.h @@ -2,7 +2,7 @@ // One connection owns one real process and one existing native pane handle. @protocol AShellPaneWire -- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int, NSFileHandle *, int))reply; +- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separateStderr reply:(void (^)(int, NSFileHandle *, NSFileHandle *, int))reply; - (void)poll:(void (^)(int, int))reply; - (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply; - (void)closeInput:(void (^)(int))reply; diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m index 5e9c0d13..ddca44df 100644 --- a/ShellWorkers/RemotePane.m +++ b/ShellWorkers/RemotePane.m @@ -25,6 +25,7 @@ @interface RemotePane : NSObject @property(nonatomic, strong) NSXPCConnection *connection; @property(nonatomic, strong) id proxy; @property(nonatomic, strong) NSFileHandle *output; +@property(nonatomic, strong) NSFileHandle *errorOutput; @property(atomic) BOOL interrupted; @property(nonatomic, strong) NSMutableArray *directories; @property(nonatomic, copy) NSString *probeDirectory; @@ -32,6 +33,7 @@ @interface RemotePane : NSObject @implementation RemotePane - (void)dealloc { [_output closeAndReturnError:NULL]; + [_errorOutput closeAndReturnError:NULL]; // Only remove our empty disposable directory, never a project tree. if (_probeDirectory) rmdir(_probeDirectory.fileSystemRepresentation); log_host_library("before_scope_release"); @@ -46,8 +48,14 @@ - (void)dealloc { int ashell_pane_capacity(void) { return ashell_extension_capacity(); } int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { + ashell_pane_options options = {.size = sizeof(options), .tty = 1}; + return ashell_pane_spawn_ex(command, cwd, cols, rows, envp, &options, fd_out, job_out); +} +int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { if (fd_out) *fd_out = -1; if (job_out) *job_out = NULL; + if (!options || options->size < sizeof(*options)) return EINVAL; + options->stderr_fd = -1; if (!command || !cwd || !fd_out || !job_out || !cols || !rows) return EINVAL; if (NSThread.isMainThread) return EDEADLK; @autoreleasepool { @@ -114,22 +122,31 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsig pane.proxy = [pane.connection synchronousRemoteObjectProxyWithErrorHandler:^(NSError *failure) { error = EPIPE; }]; NSMutableArray *env = [NSMutableArray array]; for (size_t i = 0; envp && envp[i]; i++) [env addObject:@(envp[i])]; - __block int fd = -1; - [pane.proxy spawn:@(command) cwd:cwdBookmark home:homeBookmark documents:documentsBookmark probe:pane.probeDirectory env:env cols:cols rows:rows reply:^(int code, NSFileHandle *handle, int pid) { + __block int fd = -1, err_fd = -1; + BOOL separate = options->separate_stderr != 0; + [pane.proxy spawn:@(command) cwd:cwdBookmark home:homeBookmark documents:documentsBookmark probe:pane.probeDirectory env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:separate reply:^(int code, NSFileHandle *handle, NSFileHandle *errorHandle, int pid) { error = code; - if (!code && !handle) error = EPROTO; + if (!code && (!handle || (separate && !errorHandle))) error = EPROTO; if (!error) { fd = dup(handle.fileDescriptor); if (fd < 0) error = errno; else if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { error = errno; close(fd); fd = -1; } else pane.output = handle; } + if (!error && separate) { + err_fd = dup(errorHandle.fileDescriptor); + if (err_fd < 0) error = errno; + else if (fcntl(err_fd, F_SETFD, FD_CLOEXEC)) { error = errno; close(err_fd); err_fd = -1; } + else pane.errorOutput = errorHandle; + if (error && fd >= 0) { close(fd); fd = -1; } + } NSLog(@"Shell extension spawn: real_pid=%d error=%d startup_ms=%.3f", pid, error, (NSProcessInfo.processInfo.systemUptime - started) * 1000); }]; if (rmdir(pane.probeDirectory.fileSystemRepresentation) == 0) pane.probeDirectory = nil; if (!error && fd < 0) error = EPROTO; if (error) { ashell_extension_disconnect(pane.connection); return error; } *fd_out = fd; + options->stderr_fd = err_fd; *job_out = (__bridge_retained void *)pane; return 0; } diff --git a/ShellWorkers/Worker.m b/ShellWorkers/Worker.m index c8bb984a..827dcac6 100644 --- a/ShellWorkers/Worker.m +++ b/ShellWorkers/Worker.m @@ -57,9 +57,9 @@ @implementation PaneService { void *_pane; NSMutableArray *_directories; } -- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int, NSFileHandle *, int))reply { - if (_pane) { reply(EBUSY, nil, getpid()); return; } - if (!cwd || !home || !documents || !probe) { reply(EINVAL, nil, getpid()); return; } +- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separateStderr reply:(void (^)(int, NSFileHandle *, NSFileHandle *, int))reply { + if (_pane) { reply(EBUSY, nil, nil, getpid()); return; } + if (!cwd || !home || !documents || !probe) { reply(EINVAL, nil, nil, getpid()); return; } // Resolve the host's ephemeral grants explicitly and retain them for this // pane, including HOME for shared command configuration and authentication. _directories = [NSMutableArray array]; @@ -77,7 +77,7 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document if (!url) { NSLog(@"Shell worker directory bookmark failed: %@", failure); [self releasePane]; - reply([failure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)failure.code : EIO, nil, getpid()); + reply([failure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)failure.code : EIO, nil, nil, getpid()); return; } BOOL scoped = [url startAccessingSecurityScopedResource]; @@ -94,14 +94,14 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document NSLog(@"Shell worker directory capability: url=%@ read_error=%d", url.path, code); if (code && !readError) readError = code; } - if (readError) { [self releasePane]; reply(readError, nil, getpid()); return; } + if (readError) { [self releasePane]; reply(readError, nil, nil, getpid()); return; } int capabilityError = check_documents_write(documentsURL, probe); NSLog(@"Shell worker Documents capability: real_pid=%d read_write_error=%d", getpid(), capabilityError); - if (capabilityError) { [self releasePane]; reply(capabilityError, nil, getpid()); return; } + if (capabilityError) { [self releasePane]; reply(capabilityError, nil, nil, getpid()); return; } // ios_system globals are private to this extension. The adapter keeps its // original dedicated pthread and stream ownership/cleanup barrier. NSString *temporaryDirectory = NSTemporaryDirectory(); - if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, getpid()); return; } + if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, nil, getpid()); return; } // The host's directory bookmark does not grant its tmp directory. Keep the // extension's stock Foundation/libc temp domain in both environment views. NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 1]; @@ -115,20 +115,20 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document // environment as well as ios_system's forked command environment. for (NSString *value in env) { NSRange separator = [value rangeOfString:@"="]; - if (separator.location == NSNotFound || separator.location == 0) { [self releasePane]; reply(EINVAL, nil, getpid()); return; } + if (separator.location == NSNotFound || separator.location == 0) { [self releasePane]; reply(EINVAL, nil, nil, getpid()); return; } if (setenv([value substringToIndex:separator.location].UTF8String, - [value substringFromIndex:separator.location + 1].UTF8String, 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + [value substringFromIndex:separator.location + 1].UTF8String, 1)) { int error = errno; [self releasePane]; reply(error, nil, nil, getpid()); return; } } // Match stock SceneDelegate before libedit decodes Unicode or measures it. - if (setenv("LC_CTYPE", "UTF-8", 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + if (setenv("LC_CTYPE", "UTF-8", 1)) { int error = errno; [self releasePane]; reply(error, nil, nil, getpid()); return; } const char *locale = setlocale(LC_CTYPE, "UTF-8"); - if (!locale) { [self releasePane]; reply(EINVAL, nil, getpid()); return; } + if (!locale) { [self releasePane]; reply(EINVAL, nil, nil, getpid()); return; } NSLog(@"Shell worker locale: real_pid=%d ctype=%s", getpid(), locale); // The physical device has no kernel tty. Use the same socket-backed route // on Simulator so its acceptance cannot pass through a desktop-only PTY. - if (setenv("ASHELL_IOS_PTY", "0", 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + if (setenv("ASHELL_IOS_PTY", "0", 1)) { int error = errno; [self releasePane]; reply(error, nil, nil, getpid()); return; } const char **values = calloc(env.count + 4, sizeof(char *)); - if (!values) { [self releasePane]; reply(ENOMEM, nil, getpid()); return; } + if (!values) { [self releasePane]; reply(ENOMEM, nil, nil, getpid()); return; } for (NSUInteger i = 0; i < env.count; i++) values[i] = [env[i] hasPrefix:@"ASHELL_IOS_PTY="] ? "ASHELL_IOS_PTY=0" : [env[i] hasPrefix:@"LC_CTYPE="] ? "LC_CTYPE=UTF-8" : env[i].UTF8String; @@ -137,11 +137,13 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document values[env.count + 1] = "LC_CTYPE=UTF-8"; values[env.count + 2] = "ASHELL_IOS_SOCKET_INPUT=1"; int fd = -1; - int error = ashell_pane_spawn(command.UTF8String, directory.path.UTF8String, cols, rows, values, &fd, &_pane); + ashell_pane_options options = {.size = sizeof(options), .tty = tty, .separate_stderr = separateStderr}; + int error = ashell_pane_spawn_ex(command.UTF8String, directory.path.UTF8String, cols, rows, values, &options, &fd, &_pane); free(values); if (error) [self releasePane]; NSFileHandle *handle = error ? nil : [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES]; - reply(error, handle, getpid()); + NSFileHandle *errorHandle = !error && options.stderr_fd >= 0 ? [[NSFileHandle alloc] initWithFileDescriptor:options.stderr_fd closeOnDealloc:YES] : nil; + reply(error, handle, errorHandle, getpid()); } - (void)poll:(void (^)(int, int))reply { int status = 0; From b48641df8a0ca2bdc41a192e6f27e375eba2ba0f Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:21:18 +0300 Subject: [PATCH 07/16] Broker nested shell spawns through the host worker pool --- ShellWorkers/Host.swift | 80 ++++++++++++++++++--- ShellWorkers/NativePane.h | 3 + ShellWorkers/NativePane.m | 19 ++++- ShellWorkers/PaneWire.h | 13 ++++ ShellWorkers/RemotePane.m | 83 +++++++++++++++++++++- ShellWorkers/Worker.m | 113 ++++++++++++++++++++++++++++-- a-Shell/a-Shell-Bridging-Header.h | 1 + 7 files changed, 294 insertions(+), 18 deletions(-) diff --git a/ShellWorkers/Host.swift b/ShellWorkers/Host.swift index bf9c3630..df006016 100644 --- a/ShellWorkers/Host.swift +++ b/ShellWorkers/Host.swift @@ -38,11 +38,12 @@ final class ShellWorkerPool { static let shared = ShellWorkerPool() private enum Slot { case launching(UUID) - case connected(UUID, AppExtensionProcess, NSXPCConnection) + case connected(UUID, AppExtensionProcess, NSXPCConnection, DispatchSourceProcess?) + case retiring(UUID, DispatchSourceProcess?) var generation: UUID { switch self { - case .launching(let generation), .connected(let generation, _, _): generation + case .launching(let generation), .connected(let generation, _, _, _), .retiring(let generation, _): generation } } } @@ -56,6 +57,10 @@ final class ShellWorkerPool { for _ in 0..<100 { let capacity = ShellWorkerCapacity.current if capacity > 0 && slots.count >= capacity { + if slots.values.contains(where: { if case .retiring = $0 { return true }; return false }) { + try await Task.sleep(for: .milliseconds(100)) + continue + } throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENOSPC), userInfo: [NSLocalizedDescriptionKey: "All shell workers are in use. Close a pane before opening another."]) } if let identity = monitor.identities.sorted(by: { $0.bundleIdentifier < $1.bundleIdentifier }).first(where: { slots[$0.bundleIdentifier] == nil }) { @@ -66,7 +71,10 @@ final class ShellWorkerPool { let process = try await AppExtensionProcess(configuration: .init(appExtensionIdentity: identity, onInterruption: { Task { @MainActor in guard self.slots[key]?.generation == generation else { return } - self.slots.removeValue(forKey: key) + // A connected worker is retired using its spawn-reply PID. + if case .launching = self.slots[key] { + self.slots.removeValue(forKey: key) + } } })) guard slots[key]?.generation == generation else { @@ -74,7 +82,9 @@ final class ShellWorkerPool { throw CancellationError() } let connection = try process.makeXPCConnection() - slots[key] = .connected(generation, process, connection) + connection.exportedInterface = NSXPCInterface(with: AShellSpawnBrokerWire.self) + connection.exportedObject = ashell_spawn_broker() + slots[key] = .connected(generation, process, connection, nil) return connection } catch { if slots[key]?.generation == generation { slots.removeValue(forKey: key) } @@ -86,20 +96,68 @@ final class ShellWorkerPool { throw NSError(domain: NSPOSIXErrorDomain, code: Int(ETIMEDOUT), userInfo: [NSLocalizedDescriptionKey: "shell worker discovery timed out"]) } + func observe(_ connection: NSXPCConnection, pid: pid_t, registered: @escaping () -> Void) { + for (key, slot) in slots { + guard case .connected(let generation, let process, let stored, nil) = slot, stored === connection else { continue } + let exit = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: .main) + slots[key] = .connected(generation, process, connection, exit) + exit.setEventHandler { [weak self] in + Task { @MainActor in + guard let self, let current = self.slots[key], current.generation == generation else { return } + let source: DispatchSourceProcess? + switch current { + case .connected(_, _, _, let value), .retiring(_, let value): source = value + case .launching: return + } + source?.cancel() + connection.invalidate() + process.invalidate() + self.slots.removeValue(forKey: key) + } + } + // Arm observation while the admitted process is still alive. + exit.setRegistrationHandler(handler: registered) + exit.resume() + return + } + registered() + } + func disconnect(_ connection: NSXPCConnection) { for (key, slot) in slots { - guard case .connected(_, let process, let stored) = slot, stored === connection else { continue } - // Explicit invalidation does not guarantee an interruption callback. - // Release the reservation in this MainActor transaction; generation - // checks keep a late callback from removing a replacement process. - connection.invalidate() - process.invalidate() - slots.removeValue(forKey: key) + guard case .connected(let generation, let process, let stored, let exit) = slot, stored === connection else { continue } + if exit == nil { + connection.invalidate() + process.invalidate() + slots.removeValue(forKey: key) + return + } + slots[key] = .retiring(generation, exit) + // Keep the process assertion until exit, with a deadline if observation fails. + Task { @MainActor in + try? await Task.sleep(for: .seconds(2)) + guard case .retiring(let current, let source) = self.slots[key], current == generation else { return } + source?.cancel() + connection.invalidate() + process.invalidate() + self.slots.removeValue(forKey: key) + } return } } } +@_cdecl("ashell_extension_observe") +func shellExtensionObserve(_ connection: NSXPCConnection, _ pid: pid_t) { + if #available(iOS 26.0, *), pid > 0 { + let registered = DispatchSemaphore(value: 0) + Task { @MainActor in + ShellWorkerPool.shared.observe(connection, pid: pid) { registered.signal() } + } + _ = registered.wait(timeout: .now() + 1) + } +} + @_cdecl("ashell_extension_disconnect") func shellExtensionDisconnect(_ connection: NSXPCConnection) { if #available(iOS 26.0, *) { diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h index 6c3da7ab..b7dc1057 100644 --- a/ShellWorkers/NativePane.h +++ b/ShellWorkers/NativePane.h @@ -2,6 +2,7 @@ #define ASHELL_NATIVE_PANE_H #include +#include #ifdef __cplusplus extern "C" { @@ -48,6 +49,8 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un // Repeated polling after exit preserves status. Drain the returned fd to EOF independently. // A cleanup/restore error returns -errno after completion instead of hiding the failure. int ashell_pane_poll(void *job, int *status_out); +// Optional usage is the worker's RUSAGE_SELF snapshot at exit, unavailable for lost workers. +int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, int *usage_available); // These operations return 0 or POSITIVE errno, unlike poll. // Resize updates the worker command dimensions through ios_setWindowSize. diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m index 94cdd49f..f6f9e747 100644 --- a/ShellWorkers/NativePane.m +++ b/ShellWorkers/NativePane.m @@ -29,6 +29,8 @@ pthread_cond_t ready; unsigned refs; int initialized, startup_error, done, status, completion_error; + struct rusage usage; + int usage_available; int peer_control, input_closed, is_pty; unsigned char eof_key; FILE *streams[3]; @@ -522,6 +524,11 @@ static int socket_options(int fd) { if (ios_setenv_pid(job->env[i], equals + 1, 1, pid)) error = EINVAL; *equals = '='; } + // Identify this worker's root by its reserved command PID. Setup + // calls cannot consume it, and nested children have different PIDs. + char root_pid[32]; + snprintf(root_pid, sizeof(root_pid), "%d", pid); + if (ios_setenv_pid("ASHELL_WORKER_ROOT_PID", root_pid, 1, pid)) error = EINVAL; pthread_mutex_lock(&job->mutex); job->initialized = 1; pthread_cond_signal(&job->ready); @@ -556,6 +563,7 @@ static int socket_options(int fd) { job->startup_error = job->initialized ? 0 : error; job->completion_error = error; job->initialized = 1; + job->usage_available = getrusage(RUSAGE_SELF, &job->usage) == 0; job->done = 1; NSLog(@"Shell pane lifecycle: exit key=%s status=%d error=%d", job->key, job->status, error); // Close the retained peer before announcing exit so output EOF is observable. @@ -728,11 +736,20 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un } int ashell_pane_poll(void *handle, int *status_out) { + return ashell_pane_poll_usage(handle, status_out, NULL, NULL); +} + +int ashell_pane_poll_usage(void *handle, int *status_out, struct rusage *usage_out, int *usage_available) { + if (usage_available) *usage_available = 0; if (!handle || !status_out) return -EINVAL; pane_job *job = handle; pthread_mutex_lock(&job->mutex); int result = job->completion_error ? -job->completion_error : job->done; - if (job->done) *status_out = job->status; + if (job->done) { + *status_out = job->status; + if (usage_out && job->usage_available) *usage_out = job->usage; + if (usage_available) *usage_available = job->usage_available; + } pthread_mutex_unlock(&job->mutex); return result; } diff --git a/ShellWorkers/PaneWire.h b/ShellWorkers/PaneWire.h index 63ddec83..5f0cf820 100644 --- a/ShellWorkers/PaneWire.h +++ b/ShellWorkers/PaneWire.h @@ -4,6 +4,7 @@ @protocol AShellPaneWire - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separateStderr reply:(void (^)(int, NSFileHandle *, NSFileHandle *, int))reply; - (void)poll:(void (^)(int, int))reply; +- (void)pollUsage:(void (^)(int, int, NSData *))reply; - (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply; - (void)closeInput:(void (^)(int))reply; - (void)interrupt:(void (^)(int))reply; @@ -13,3 +14,15 @@ @end NSObject *ashell_worker_service(void); + +// A worker asks its owning host to allocate another isolated process. +@protocol AShellSpawnBrokerWire +- (void)spawnChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply; +- (void)pollChild:(NSString *)token reply:(void (^)(int, int))reply; +- (void)pollChildUsage:(NSString *)token reply:(void (^)(int, int, NSData *))reply; +- (void)closeChildInput:(NSString *)token reply:(void (^)(int))reply; +- (void)cancelChild:(NSString *)token reply:(void (^)(int))reply; +- (void)releaseChild:(NSString *)token; +@end + +NSObject *ashell_spawn_broker(void); diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m index ddca44df..a4870e0a 100644 --- a/ShellWorkers/RemotePane.m +++ b/ShellWorkers/RemotePane.m @@ -9,6 +9,7 @@ extern void ashell_extension_connect(void (^)(NSXPCConnection *, NSError *)); extern void ashell_extension_disconnect(NSXPCConnection *); +extern void ashell_extension_observe(NSXPCConnection *, pid_t); extern int ashell_extension_capacity(void); static void log_host_library(const char *phase) { @@ -45,6 +46,65 @@ - (void)dealloc { } @end +// A connection owns its descendants; invalidation releases the whole subtree. +@interface BrokerChild : NSObject +@property(nonatomic) void *job; +@end +@implementation BrokerChild +- (void)dealloc { if (_job) ashell_pane_release(_job); } +@end + +@interface SpawnBroker : NSObject +@property(nonatomic, strong) NSMutableDictionary *children; +@end +@implementation SpawnBroker +- (instancetype)init { + if ((self = [super init])) _children = [NSMutableDictionary new]; + return self; +} +- (void)spawnChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply { + const char **values = calloc(env.count + 1, sizeof(*values)); + if (!values) { reply(ENOMEM, nil, nil, nil); return; } + for (NSUInteger i = 0; i < env.count; i++) values[i] = env[i].UTF8String; + int fd = -1; + BrokerChild *child = [BrokerChild new]; + ashell_pane_options options = { .size = sizeof(options), .tty = tty, .separate_stderr = separate }; + void *job = NULL; + int error = ashell_pane_spawn_ex(command.UTF8String, cwd.fileSystemRepresentation, cols, rows, values, &options, &fd, &job); + free(values); + if (error) { reply(error, nil, nil, nil); return; } + child.job = job; + NSString *token = NSUUID.UUID.UUIDString; + @synchronized (self) { self.children[token] = child; } + NSFileHandle *output = [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES]; + NSFileHandle *errors = options.stderr_fd >= 0 ? [[NSFileHandle alloc] initWithFileDescriptor:options.stderr_fd closeOnDealloc:YES] : nil; + reply(0, token, output, errors); +} +- (BrokerChild *)child:(NSString *)token { @synchronized (self) { return self.children[token]; } } +- (void)pollChild:(NSString *)token reply:(void (^)(int, int))reply { + [self pollChildUsage:token reply:^(int result, int status, NSData *usage) { reply(result, status); }]; +} +- (void)pollChildUsage:(NSString *)token reply:(void (^)(int, int, NSData *))reply { + BrokerChild *child = [self child:token]; + int status = 0; + int available = 0; + struct rusage usage; + int result = child ? ashell_pane_poll_usage(child.job, &status, &usage, &available) : -ESRCH; + reply(result, status, result == 1 && available ? [NSData dataWithBytes:&usage length:sizeof(usage)] : nil); +} +- (void)closeChildInput:(NSString *)token reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? ashell_pane_close_stdin(child.job) : ESRCH); +} +- (void)cancelChild:(NSString *)token reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? ashell_pane_cancel(child.job) : ESRCH); +} +- (void)releaseChild:(NSString *)token { @synchronized (self) { [self.children removeObjectForKey:token]; } } +@end + + + int ashell_pane_capacity(void) { return ashell_extension_capacity(); } int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { @@ -125,6 +185,7 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un __block int fd = -1, err_fd = -1; BOOL separate = options->separate_stderr != 0; [pane.proxy spawn:@(command) cwd:cwdBookmark home:homeBookmark documents:documentsBookmark probe:pane.probeDirectory env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:separate reply:^(int code, NSFileHandle *handle, NSFileHandle *errorHandle, int pid) { + ashell_extension_observe(pane.connection, pid); error = code; if (!code && (!handle || (separate && !errorHandle))) error = EPROTO; if (!error) { @@ -144,7 +205,12 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un }]; if (rmdir(pane.probeDirectory.fileSystemRepresentation) == 0) pane.probeDirectory = nil; if (!error && fd < 0) error = EPROTO; - if (error) { ashell_extension_disconnect(pane.connection); return error; } + if (error) { + int spawnError = error; + [pane.proxy terminate:^{}]; + ashell_extension_disconnect(pane.connection); + return spawnError; + } *fd_out = fd; options->stderr_fd = err_fd; *job_out = (__bridge_retained void *)pane; @@ -152,6 +218,10 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un } } int ashell_pane_poll(void *job, int *status_out) { + return ashell_pane_poll_usage(job, status_out, NULL, NULL); +} +int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, int *usage_available) { + if (usage_available) *usage_available = 0; RemotePane *pane = (__bridge RemotePane *)job; if (!pane || !status_out) return -EINVAL; // 137 is this backend's lost-worker status, not a recovered waitpid status. @@ -165,7 +235,14 @@ int ashell_pane_poll(void *job, int *status_out) { if (output.revents & POLLNVAL) return -EBADF; if (!(output.revents & (POLLHUP | POLLERR))) return 0; __block int result = -EPIPE; - [pane.proxy poll:^(int value, int status) { result = value; *status_out = status; }]; + [pane.proxy pollUsage:^(int value, int status, NSData *usage) { + result = value; + *status_out = status; + if (value == 1 && usage.length == sizeof(struct rusage)) { + if (usage_out) memcpy(usage_out, usage.bytes, sizeof(struct rusage)); + if (usage_available) *usage_available = 1; + } + }]; if (result == -EPIPE) { pane.interrupted = YES; *status_out = 137; return 1; } return result; } @@ -205,3 +282,5 @@ void ashell_pane_release(void *job) { [pane.proxy terminate:^{}]; ashell_extension_disconnect(pane.connection); } + +NSObject *ashell_spawn_broker(void) { return [SpawnBroker new]; } diff --git a/ShellWorkers/Worker.m b/ShellWorkers/Worker.m index 827dcac6..f4608aa2 100644 --- a/ShellWorkers/Worker.m +++ b/ShellWorkers/Worker.m @@ -8,6 +8,8 @@ #include #include #include +#undef kill +#include // ios_system discovers these stock host callbacks with dlsym. Each extension // owns one shell; its socket already carries input directly to the command. @@ -50,6 +52,96 @@ static int check_documents_write(NSURL *documents, NSString *probe) { return code; } +static id spawnBroker; +@interface BrokerRemoteChild : NSObject +@property(nonatomic, strong) id broker; +@property(nonatomic, copy) NSString *token; +@property(nonatomic, strong) NSFileHandle *output; +@property(nonatomic, strong) NSFileHandle *errors; +@end +@implementation BrokerRemoteChild +- (void)dealloc { if (_token) [_broker releaseChild:_token]; } +@end + +__attribute__((used, visibility("default"))) int ashell_worker_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { + if (fd_out) *fd_out = -1; + if (job_out) *job_out = NULL; + if (!options || options->size < sizeof(*options)) return EINVAL; + options->stderr_fd = -1; + if (!command || !*command || !cwd || cwd[0] != '/' || !cols || cols > 9999 || !rows || rows > 9999 || !fd_out || !job_out) return EINVAL; + if (!spawnBroker) return ENOTSUP; + NSMutableArray *env = [NSMutableArray new]; + for (size_t i = 0; envp && envp[i]; i++) [env addObject:@(envp[i])]; + BrokerRemoteChild *child = [BrokerRemoteChild new]; + child.broker = spawnBroker; + __block int error = EPIPE; + [child.broker spawnChild:@(command) cwd:@(cwd) env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:options->separate_stderr != 0 reply:^(int code, NSString *token, NSFileHandle *output, NSFileHandle *errors) { + error = code; + if (error) return; + child.token = token; + child.output = output; + child.errors = errors; + if (!token || !output || (options->separate_stderr && !errors)) { error = EPROTO; return; } + *fd_out = dup(output.fileDescriptor); + if (*fd_out < 0) { error = errno; return; } + if (fcntl(*fd_out, F_SETFD, FD_CLOEXEC)) { error = errno; close(*fd_out); *fd_out = -1; return; } + if (errors) { + options->stderr_fd = dup(errors.fileDescriptor); + if (options->stderr_fd < 0) error = errno; + else if (fcntl(options->stderr_fd, F_SETFD, FD_CLOEXEC)) { + error = errno; + close(options->stderr_fd); + options->stderr_fd = -1; + } + if (error) { close(*fd_out); *fd_out = -1; } + } + }]; + if (error) return error; + *job_out = (__bridge_retained void *)child; + return 0; +} +__attribute__((used, visibility("default"))) int ashell_worker_poll_usage(void *handle, int *status, struct rusage *usage_out, int *usage_available) { + if (usage_available) *usage_available = 0; + if (!handle || !status) return -EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)handle; + struct pollfd fd = { child.output.fileDescriptor, POLLIN, 0 }; + if (poll(&fd, 1, 0) < 0) return errno == EINTR ? 0 : -errno; + if (fd.revents & POLLNVAL) return -EBADF; + if (!(fd.revents & (POLLHUP | POLLERR))) return 0; + __block int result = 1; + *status = 137; + [child.broker pollChildUsage:child.token reply:^(int value, int code, NSData *usage) { + result = value; + *status = code; + if (value == 1 && usage.length == sizeof(struct rusage)) { + if (usage_out) memcpy(usage_out, usage.bytes, sizeof(struct rusage)); + if (usage_available) *usage_available = 1; + } + }]; + return result; +} +__attribute__((used, visibility("default"))) int ashell_worker_poll(void *handle, int *status) { + return ashell_worker_poll_usage(handle, status, NULL, NULL); +} +__attribute__((used, visibility("default"))) int ashell_worker_close_stdin(void *handle) { + if (!handle) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)handle; + __block int result = EPIPE; + [child.broker closeChildInput:child.token reply:^(int code) { result = code; }]; + return result; +} +__attribute__((used, visibility("default"))) int ashell_worker_cancel(void *handle) { + if (!handle) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)handle; + __block int result = EPIPE; + [child.broker cancelChild:child.token reply:^(int code) { result = code; }]; + return result; +} +__attribute__((used, visibility("default"))) void ashell_worker_release(void *handle) { + BrokerRemoteChild *child = (__bridge_transfer BrokerRemoteChild *)handle; + (void)child; +} + @interface PaneService : NSObject @end @@ -59,6 +151,11 @@ @implementation PaneService { } - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separateStderr reply:(void (^)(int, NSFileHandle *, NSFileHandle *, int))reply { if (_pane) { reply(EBUSY, nil, nil, getpid()); return; } + NSXPCConnection *connection = NSXPCConnection.currentConnection; + connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(AShellSpawnBrokerWire)]; + spawnBroker = [connection synchronousRemoteObjectProxyWithErrorHandler:^(NSError *failure) { + NSLog(@"Shell worker spawn broker disconnected: %@", failure); + }]; if (!cwd || !home || !documents || !probe) { reply(EINVAL, nil, nil, getpid()); return; } // Resolve the host's ephemeral grants explicitly and retain them for this // pane, including HOME for shared command configuration and authentication. @@ -104,10 +201,13 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, nil, getpid()); return; } // The host's directory bookmark does not grant its tmp directory. Keep the // extension's stock Foundation/libc temp domain in both environment views. - NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 1]; + NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 2]; for (NSString *value in env) - if (![value hasPrefix:@"TMPDIR="]) [environment addObject:value]; + if (![value hasPrefix:@"TMPDIR="] && ![value hasPrefix:@"HOME="]) [environment addObject:value]; [environment addObject:[@"TMPDIR=" stringByAppendingString:temporaryDirectory]]; + // A home-root bookmark can resolve relative to the extension's own home. + // Documents retains the host path; nested spawns need that same host HOME. + [environment addObject:[@"HOME=" stringByAppendingString:documentsURL.URLByDeletingLastPathComponent.path]]; env = environment; initializeEnvironment(); replaceCommand(@"clear", @"clear", true); @@ -146,9 +246,14 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document reply(error, handle, errorHandle, getpid()); } - (void)poll:(void (^)(int, int))reply { + [self pollUsage:^(int result, int status, NSData *usage) { reply(result, status); }]; +} +- (void)pollUsage:(void (^)(int, int, NSData *))reply { int status = 0; - int result = _pane ? ashell_pane_poll(_pane, &status) : -ESRCH; - reply(result, status); + int available = 0; + struct rusage usage; + int result = _pane ? ashell_pane_poll_usage(_pane, &status, &usage, &available) : -ESRCH; + reply(result, status, result == 1 && available ? [NSData dataWithBytes:&usage length:sizeof(usage)] : nil); } - (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply { reply(_pane ? ashell_pane_resize(_pane, cols, rows) : ESRCH); diff --git a/a-Shell/a-Shell-Bridging-Header.h b/a-Shell/a-Shell-Bridging-Header.h index 0282b277..1efe2b86 100644 --- a/a-Shell/a-Shell-Bridging-Header.h +++ b/a-Shell/a-Shell-Bridging-Header.h @@ -3,3 +3,4 @@ // #import "KBWebViewBase.h" +#import "../ShellWorkers/PaneWire.h" From cfe5cdcbceb40944b048221e9ec727fef9c699dc Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:45:10 +0300 Subject: [PATCH 08/16] Expose an explicit host pane broker and report lost worker connections --- Resources/bin/dash | 0 Resources_mini/bin/dash | 0 ShellWorkers/HostPane.h | 42 +++++++++ ShellWorkers/HostPane.m | 12 +++ ShellWorkers/NativePane.h | 2 + ShellWorkers/NativePane.m | 3 + ShellWorkers/PaneWire.h | 3 + ShellWorkers/RemotePane.m | 45 +++++++--- ShellWorkers/Worker.m | 55 +++++++++--- a-Shell.xcodeproj/project.pbxproj | 10 +++ tests/worker-pool.m | 142 ++++++++++++++++++++++++++++-- tests/worker-pool.md | 9 ++ 12 files changed, 294 insertions(+), 29 deletions(-) create mode 100644 Resources/bin/dash create mode 100644 Resources_mini/bin/dash create mode 100644 ShellWorkers/HostPane.h create mode 100644 ShellWorkers/HostPane.m diff --git a/Resources/bin/dash b/Resources/bin/dash new file mode 100644 index 00000000..e69de29b diff --git a/Resources_mini/bin/dash b/Resources_mini/bin/dash new file mode 100644 index 00000000..e69de29b diff --git a/ShellWorkers/HostPane.h b/ShellWorkers/HostPane.h new file mode 100644 index 00000000..b5f6c7f9 --- /dev/null +++ b/ShellWorkers/HostPane.h @@ -0,0 +1,42 @@ +#ifndef ASHELL_HOST_PANE_H +#define ASHELL_HOST_PANE_H + +#include "NativePane.h" + +#ifdef __cplusplus +extern "C" { +#endif +#pragma GCC visibility push(default) + +// Explicit app-process runner for commands that exceed the extension memory limit. +// Uses the same streams, options and handle lifetime as NativePane.h. One live host +// pane is admitted (EBUSY for another); it shares the app's process cwd and memory. +// No extension allocation or automatic routing is performed. Do not forward worker +// identity environment overrides. Cancellation returns ENOTSUP while running; +// interrupt targets the foreground command, and release retains live cleanup. +int ashell_host_pane_spawn(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **); +int ashell_host_pane_spawn_ex(const char *, const char *, unsigned, unsigned, const char *const *, ashell_pane_options *, int *, void **); +int ashell_host_pane_poll(void *, int *); +int ashell_host_pane_poll_usage(void *, int *, struct rusage *, int *); +int ashell_host_pane_resize(void *, unsigned, unsigned); +int ashell_host_pane_close_stdin(void *); +int ashell_host_pane_interrupt(void *); +int ashell_host_pane_cancel(void *); +void ashell_host_pane_release(void *); + +// Explicit worker-to-host broker route. Handles remain in the calling worker; +// poll reports -EPIPE if the host connection is lost. No admission policy here. +int ashell_worker_host_spawn_ex(const char *, const char *, unsigned, unsigned, const char *const *, ashell_pane_options *, int *, void **); +int ashell_worker_host_poll(void *, int *); +int ashell_worker_host_poll_usage(void *, int *, struct rusage *, int *); +int ashell_worker_host_resize(void *, unsigned, unsigned); +int ashell_worker_host_close_stdin(void *); +int ashell_worker_host_interrupt(void *); +int ashell_worker_host_cancel(void *); +void ashell_worker_host_release(void *); + +#pragma GCC visibility pop +#ifdef __cplusplus +} +#endif +#endif diff --git a/ShellWorkers/HostPane.m b/ShellWorkers/HostPane.m new file mode 100644 index 00000000..76521dee --- /dev/null +++ b/ShellWorkers/HostPane.m @@ -0,0 +1,12 @@ +// Compile the same native runner in the app under a distinct public ABI. +#define ASHELL_HOST_PANE 1 +#define ashell_pane_spawn ashell_host_pane_spawn +#define ashell_pane_spawn_ex ashell_host_pane_spawn_ex +#define ashell_pane_poll ashell_host_pane_poll +#define ashell_pane_poll_usage ashell_host_pane_poll_usage +#define ashell_pane_resize ashell_host_pane_resize +#define ashell_pane_close_stdin ashell_host_pane_close_stdin +#define ashell_pane_interrupt ashell_host_pane_interrupt +#define ashell_pane_cancel ashell_host_pane_cancel +#define ashell_pane_release ashell_host_pane_release +#include "NativePane.m" diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h index b7dc1057..85b2e028 100644 --- a/ShellWorkers/NativePane.h +++ b/ShellWorkers/NativePane.h @@ -48,6 +48,8 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un // Returns 0 running, 1 exited (writes final command status), or -errno. // Repeated polling after exit preserves status. Drain the returned fd to EOF independently. // A cleanup/restore error returns -errno after completion instead of hiding the failure. +// Lost XPC returns -EPIPE without inventing an exit status. Explicit cancellation +// returns 137; that status does not identify the cause of an unexpected process loss. int ashell_pane_poll(void *job, int *status_out); // Optional usage is the worker's RUSAGE_SELF snapshot at exit, unavailable for lost workers. int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, int *usage_available); diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m index f6f9e747..920dee96 100644 --- a/ShellWorkers/NativePane.m +++ b/ShellWorkers/NativePane.m @@ -524,11 +524,14 @@ static int socket_options(int fd) { if (ios_setenv_pid(job->env[i], equals + 1, 1, pid)) error = EINVAL; *equals = '='; } +#ifndef ASHELL_HOST_PANE // Identify this worker's root by its reserved command PID. Setup // calls cannot consume it, and nested children have different PIDs. char root_pid[32]; snprintf(root_pid, sizeof(root_pid), "%d", pid); if (ios_setenv_pid("ASHELL_WORKER_ROOT_PID", root_pid, 1, pid)) error = EINVAL; + if (setenv("ASHELL_WORKER_ROOT_PID", root_pid, 1)) error = errno; +#endif pthread_mutex_lock(&job->mutex); job->initialized = 1; pthread_cond_signal(&job->ready); diff --git a/ShellWorkers/PaneWire.h b/ShellWorkers/PaneWire.h index 5f0cf820..e83a8805 100644 --- a/ShellWorkers/PaneWire.h +++ b/ShellWorkers/PaneWire.h @@ -18,10 +18,13 @@ NSObject *ashell_worker_service(void); // A worker asks its owning host to allocate another isolated process. @protocol AShellSpawnBrokerWire - (void)spawnChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply; +- (void)spawnHostChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply; - (void)pollChild:(NSString *)token reply:(void (^)(int, int))reply; - (void)pollChildUsage:(NSString *)token reply:(void (^)(int, int, NSData *))reply; - (void)closeChildInput:(NSString *)token reply:(void (^)(int))reply; - (void)cancelChild:(NSString *)token reply:(void (^)(int))reply; +- (void)resizeChild:(NSString *)token cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply; +- (void)interruptChild:(NSString *)token reply:(void (^)(int))reply; - (void)releaseChild:(NSString *)token; @end diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m index a4870e0a..df4a2db4 100644 --- a/ShellWorkers/RemotePane.m +++ b/ShellWorkers/RemotePane.m @@ -1,4 +1,5 @@ #import "PaneWire.h" +#import "HostPane.h" #include "NativePane.h" #include #include @@ -28,6 +29,7 @@ @interface RemotePane : NSObject @property(nonatomic, strong) NSFileHandle *output; @property(nonatomic, strong) NSFileHandle *errorOutput; @property(atomic) BOOL interrupted; +@property(atomic) BOOL cancelled; @property(nonatomic, strong) NSMutableArray *directories; @property(nonatomic, copy) NSString *probeDirectory; @end @@ -49,9 +51,10 @@ - (void)dealloc { // A connection owns its descendants; invalidation releases the whole subtree. @interface BrokerChild : NSObject @property(nonatomic) void *job; +@property(nonatomic) BOOL host; @end @implementation BrokerChild -- (void)dealloc { if (_job) ashell_pane_release(_job); } +- (void)dealloc { if (_job) { if (_host) ashell_host_pane_release(_job); else ashell_pane_release(_job); } } @end @interface SpawnBroker : NSObject @@ -63,14 +66,27 @@ - (instancetype)init { return self; } - (void)spawnChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply { - const char **values = calloc(env.count + 1, sizeof(*values)); + [self spawn:command cwd:cwd env:env cols:cols rows:rows tty:tty separateStderr:separate host:NO reply:reply]; +} +- (void)spawnHostChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply { + [self spawn:command cwd:cwd env:env cols:cols rows:rows tty:tty separateStderr:separate host:YES reply:reply]; +} +- (void)spawn:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate host:(BOOL)host reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply { + const char **values = calloc(env.count + 2, sizeof(*values)); if (!values) { reply(ENOMEM, nil, nil, nil); return; } - for (NSUInteger i = 0; i < env.count; i++) values[i] = env[i].UTF8String; + NSUInteger count = 0; + for (NSString *value in env) { + if (host && ([value hasPrefix:@"ASHELL_WORKER_PID="] || [value hasPrefix:@"ASHELL_WORKER_ROOT_PID="] || [value hasPrefix:@"TMPDIR="])) continue; + values[count++] = value.UTF8String; + } + NSString *temporary = host ? [@"TMPDIR=" stringByAppendingString:NSTemporaryDirectory()] : nil; + if (temporary) values[count++] = temporary.UTF8String; int fd = -1; BrokerChild *child = [BrokerChild new]; + child.host = host; ashell_pane_options options = { .size = sizeof(options), .tty = tty, .separate_stderr = separate }; void *job = NULL; - int error = ashell_pane_spawn_ex(command.UTF8String, cwd.fileSystemRepresentation, cols, rows, values, &options, &fd, &job); + int error = (host ? ashell_host_pane_spawn_ex : ashell_pane_spawn_ex)(command.UTF8String, cwd.fileSystemRepresentation, cols, rows, values, &options, &fd, &job); free(values); if (error) { reply(error, nil, nil, nil); return; } child.job = job; @@ -89,16 +105,24 @@ - (void)pollChildUsage:(NSString *)token reply:(void (^)(int, int, NSData *))rep int status = 0; int available = 0; struct rusage usage; - int result = child ? ashell_pane_poll_usage(child.job, &status, &usage, &available) : -ESRCH; + int result = child ? (child.host ? ashell_host_pane_poll_usage : ashell_pane_poll_usage)(child.job, &status, &usage, &available) : -ESRCH; reply(result, status, result == 1 && available ? [NSData dataWithBytes:&usage length:sizeof(usage)] : nil); } - (void)closeChildInput:(NSString *)token reply:(void (^)(int))reply { BrokerChild *child = [self child:token]; - reply(child ? ashell_pane_close_stdin(child.job) : ESRCH); + reply(child ? (child.host ? ashell_host_pane_close_stdin : ashell_pane_close_stdin)(child.job) : ESRCH); } - (void)cancelChild:(NSString *)token reply:(void (^)(int))reply { BrokerChild *child = [self child:token]; - reply(child ? ashell_pane_cancel(child.job) : ESRCH); + reply(child ? (child.host ? ashell_host_pane_cancel : ashell_pane_cancel)(child.job) : ESRCH); +} +- (void)resizeChild:(NSString *)token cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? (child.host ? ashell_host_pane_resize : ashell_pane_resize)(child.job, cols, rows) : ESRCH); +} +- (void)interruptChild:(NSString *)token reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? (child.host ? ashell_host_pane_interrupt : ashell_pane_interrupt)(child.job) : ESRCH); } - (void)releaseChild:(NSString *)token { @synchronized (self) { [self.children removeObjectForKey:token]; } } @end @@ -224,8 +248,8 @@ int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, if (usage_available) *usage_available = 0; RemotePane *pane = (__bridge RemotePane *)job; if (!pane || !status_out) return -EINVAL; - // 137 is this backend's lost-worker status, not a recovered waitpid status. - if (pane.interrupted) { *status_out = 137; return 1; } + if (pane.cancelled) { *status_out = 137; return 1; } + if (pane.interrupted) return -EPIPE; // The worker closes its socket streams before publishing completion. A // hangup is observable even with unread output; keep polling local until // then instead of waking the worker with an XPC request on every poll. @@ -243,7 +267,7 @@ int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, if (usage_available) *usage_available = 1; } }]; - if (result == -EPIPE) { pane.interrupted = YES; *status_out = 137; return 1; } + if (result == -EPIPE) pane.interrupted = YES; return result; } int ashell_pane_resize(void *job, unsigned cols, unsigned rows) { @@ -270,6 +294,7 @@ int ashell_pane_interrupt(void *job) { int ashell_pane_cancel(void *job) { RemotePane *pane = (__bridge RemotePane *)job; if (!pane) return EINVAL; + pane.cancelled = YES; pane.interrupted = YES; [pane.proxy terminate:^{}]; ashell_extension_disconnect(pane.connection); diff --git a/ShellWorkers/Worker.m b/ShellWorkers/Worker.m index f4608aa2..79b8052a 100644 --- a/ShellWorkers/Worker.m +++ b/ShellWorkers/Worker.m @@ -63,7 +63,7 @@ @implementation BrokerRemoteChild - (void)dealloc { if (_token) [_broker releaseChild:_token]; } @end -__attribute__((used, visibility("default"))) int ashell_worker_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { +static int broker_spawn(BOOL host, const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { if (fd_out) *fd_out = -1; if (job_out) *job_out = NULL; if (!options || options->size < sizeof(*options)) return EINVAL; @@ -75,7 +75,7 @@ - (void)dealloc { if (_token) [_broker releaseChild:_token]; } BrokerRemoteChild *child = [BrokerRemoteChild new]; child.broker = spawnBroker; __block int error = EPIPE; - [child.broker spawnChild:@(command) cwd:@(cwd) env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:options->separate_stderr != 0 reply:^(int code, NSString *token, NSFileHandle *output, NSFileHandle *errors) { + void (^reply)(int, NSString *, NSFileHandle *, NSFileHandle *) = ^(int code, NSString *token, NSFileHandle *output, NSFileHandle *errors) { error = code; if (error) return; child.token = token; @@ -95,11 +95,19 @@ - (void)dealloc { if (_token) [_broker releaseChild:_token]; } } if (error) { close(*fd_out); *fd_out = -1; } } - }]; + }; + if (host) [child.broker spawnHostChild:@(command) cwd:@(cwd) env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:options->separate_stderr != 0 reply:reply]; + else [child.broker spawnChild:@(command) cwd:@(cwd) env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:options->separate_stderr != 0 reply:reply]; if (error) return error; *job_out = (__bridge_retained void *)child; return 0; } +__attribute__((used, visibility("default"))) int ashell_worker_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { + return broker_spawn(NO, command, cwd, cols, rows, envp, options, fd_out, job_out); +} +__attribute__((used, visibility("default"))) int ashell_worker_host_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { + return broker_spawn(YES, command, cwd, cols, rows, envp, options, fd_out, job_out); +} __attribute__((used, visibility("default"))) int ashell_worker_poll_usage(void *handle, int *status, struct rusage *usage_out, int *usage_available) { if (usage_available) *usage_available = 0; if (!handle || !status) return -EINVAL; @@ -108,11 +116,10 @@ - (void)dealloc { if (_token) [_broker releaseChild:_token]; } if (poll(&fd, 1, 0) < 0) return errno == EINTR ? 0 : -errno; if (fd.revents & POLLNVAL) return -EBADF; if (!(fd.revents & (POLLHUP | POLLERR))) return 0; - __block int result = 1; - *status = 137; + __block int result = -EPIPE; [child.broker pollChildUsage:child.token reply:^(int value, int code, NSData *usage) { result = value; - *status = code; + if (value == 1) *status = code; if (value == 1 && usage.length == sizeof(struct rusage)) { if (usage_out) memcpy(usage_out, usage.bytes, sizeof(struct rusage)); if (usage_available) *usage_available = 1; @@ -142,6 +149,27 @@ - (void)dealloc { if (_token) [_broker releaseChild:_token]; } (void)child; } +// Host children use the same broker tokens and stream ownership as extension children. +__attribute__((used, visibility("default"))) int ashell_worker_host_poll(void *job, int *status) { return ashell_worker_poll(job, status); } +__attribute__((used, visibility("default"))) int ashell_worker_host_poll_usage(void *job, int *status, struct rusage *usage, int *available) { return ashell_worker_poll_usage(job, status, usage, available); } +__attribute__((used, visibility("default"))) int ashell_worker_host_close_stdin(void *job) { return ashell_worker_close_stdin(job); } +__attribute__((used, visibility("default"))) int ashell_worker_host_cancel(void *job) { return ashell_worker_cancel(job); } +__attribute__((used, visibility("default"))) void ashell_worker_host_release(void *job) { ashell_worker_release(job); } +__attribute__((used, visibility("default"))) int ashell_worker_host_resize(void *job, unsigned cols, unsigned rows) { + if (!job) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)job; + __block int result = EPIPE; + [child.broker resizeChild:child.token cols:cols rows:rows reply:^(int code) { result = code; }]; + return result; +} +__attribute__((used, visibility("default"))) int ashell_worker_host_interrupt(void *job) { + if (!job) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)job; + __block int result = EPIPE; + [child.broker interruptChild:child.token reply:^(int code) { result = code; }]; + return result; +} + @interface PaneService : NSObject @end @@ -201,13 +229,16 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, nil, getpid()); return; } // The host's directory bookmark does not grant its tmp directory. Keep the // extension's stock Foundation/libc temp domain in both environment views. - NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 2]; + NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 3]; for (NSString *value in env) - if (![value hasPrefix:@"TMPDIR="] && ![value hasPrefix:@"HOME="]) [environment addObject:value]; + if (![value hasPrefix:@"TMPDIR="] && ![value hasPrefix:@"HOME="] && + ![value hasPrefix:@"ASHELL_WORKER_PID="] && ![value hasPrefix:@"ASHELL_WORKER_ROOT_PID="]) [environment addObject:value]; [environment addObject:[@"TMPDIR=" stringByAppendingString:temporaryDirectory]]; // A home-root bookmark can resolve relative to the extension's own home. // Documents retains the host path; nested spawns need that same host HOME. [environment addObject:[@"HOME=" stringByAppendingString:documentsURL.URLByDeletingLastPathComponent.path]]; + // Dash imports libc environ when it initializes its own variable table. + [environment addObject:[NSString stringWithFormat:@"ASHELL_WORKER_PID=%d", getpid()]]; env = environment; initializeEnvironment(); replaceCommand(@"clear", @"clear", true); @@ -227,15 +258,13 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document // The physical device has no kernel tty. Use the same socket-backed route // on Simulator so its acceptance cannot pass through a desktop-only PTY. if (setenv("ASHELL_IOS_PTY", "0", 1)) { int error = errno; [self releasePane]; reply(error, nil, nil, getpid()); return; } - const char **values = calloc(env.count + 4, sizeof(char *)); + const char **values = calloc(env.count + 3, sizeof(char *)); if (!values) { [self releasePane]; reply(ENOMEM, nil, nil, getpid()); return; } for (NSUInteger i = 0; i < env.count; i++) values[i] = [env[i] hasPrefix:@"ASHELL_IOS_PTY="] ? "ASHELL_IOS_PTY=0" : [env[i] hasPrefix:@"LC_CTYPE="] ? "LC_CTYPE=UTF-8" : env[i].UTF8String; - NSString *identity = [NSString stringWithFormat:@"ASHELL_WORKER_PID=%d", getpid()]; - values[env.count] = identity.UTF8String; - values[env.count + 1] = "LC_CTYPE=UTF-8"; - values[env.count + 2] = "ASHELL_IOS_SOCKET_INPUT=1"; + values[env.count] = "LC_CTYPE=UTF-8"; + values[env.count + 1] = "ASHELL_IOS_SOCKET_INPUT=1"; int fd = -1; ashell_pane_options options = {.size = sizeof(options), .tty = tty, .separate_stderr = separateStderr}; int error = ashell_pane_spawn_ex(command.UTF8String, directory.path.UTF8String, cols, rows, values, &options, &fd, &_pane); diff --git a/a-Shell.xcodeproj/project.pbxproj b/a-Shell.xcodeproj/project.pbxproj index 049ec457..5ccda210 100644 --- a/a-Shell.xcodeproj/project.pbxproj +++ b/a-Shell.xcodeproj/project.pbxproj @@ -996,6 +996,10 @@ isa = "PBXBuildFile"; fileRef = "D847238C57D48CADF264887A"; }; + 601A00000000000000000001 = { + isa = "PBXBuildFile"; + fileRef = "601A00000000000000000002"; + }; C608987E0D35D7D8C92CF091 = { isa = "PBXBuildFile"; fileRef = "11189940A2AF26A6542BDEAF"; @@ -3064,6 +3068,11 @@ path = "ShellWorkers/Host.swift"; sourceTree = "SOURCE_ROOT"; }; + 601A00000000000000000002 = { + isa = "PBXFileReference"; + path = "ShellWorkers/HostPane.m"; + sourceTree = "SOURCE_ROOT"; + }; 11189940A2AF26A6542BDEAF = { isa = "PBXFileReference"; path = "ShellWorkers/RemotePane.m"; @@ -5257,6 +5266,7 @@ buildActionMask = 2147483647; files = ( C608987E0D35D7D8C92CF091, + "601A00000000000000000001", 7A025EB47CCEBDAA7E49CB3E, 229D2477257931E4004A78AC /* ExtraCommands.swift in Sources */, 707000000000000000000003 /* TerminalFont.swift in Sources */, diff --git a/tests/worker-pool.m b/tests/worker-pool.m index 90a77bf7..dc9394a1 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -8,6 +8,7 @@ #include #include #include +#include "../ShellWorkers/NativePane.h" #define MAX_WORKERS 64 @@ -163,8 +164,8 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { if (result) break; usleep(10000); } - lost = lost && result == 1 && status == 137; - fprintf(thread_stdout, "lost worker status=%d: %s\n", status, lost ? "PASS" : "FAIL"); + lost = lost && result == -EPIPE && status == -1; + fprintf(thread_stdout, "lost worker result=%d status=%d: %s\n", result, status, lost ? "PASS" : "FAIL"); passed = lost; release(jobs[1]); jobs[1] = NULL; close(descriptors[1]); descriptors[1] = -1; @@ -197,7 +198,7 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { } // Exit status must not depend on the consumer draining pending output first. -static int completion_check(void) { +static int completion_check(BOOL identity) { int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); int (*pollJob)(void *, int *) = dlsym(RTLD_DEFAULT, "ashell_pane_poll"); void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); @@ -205,7 +206,9 @@ static int completion_check(void) { NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; int descriptor = -1, status = -1, result = 0; void *job = NULL; - int error = spawn("dash -c 'printf pending-output; exit 7'", directory.fileSystemRepresentation, 80, 24, NULL, &descriptor, &job); + const char *environment[] = {"ASHELL_WORKER_PID=-1", "ASHELL_WORKER_ROOT_PID=-1", NULL}; + const char *command = identity ? "dash -c 'test \"$ASHELL_WORKER_PID\" -gt 0 && test \"$ASHELL_WORKER_ROOT_PID\" -gt 0 && dash -c \"test \\\"\\$ASHELL_WORKER_PID\\\" -gt 0 && test \\\"\\$ASHELL_WORKER_ROOT_PID\\\" -gt 0\" && printf pending-output; exit 7'" : "dash -c 'printf pending-output; exit 7'"; + int error = spawn(command, directory.fileSystemRepresentation, 80, 24, identity ? environment : NULL, &descriptor, &job); if (error) { fprintf(thread_stdout, "completion startup=%d: FAIL\n", error); return 1; } NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 10; while (!result && NSProcessInfo.processInfo.systemUptime < deadline) { @@ -221,7 +224,7 @@ static int completion_check(void) { if (passed) passed = read(descriptor, output, 1) == 0; release(job); close(descriptor); - fprintf(thread_stdout, "status before output drain and repeated status: %s\n", passed ? "PASS" : "FAIL"); + fprintf(thread_stdout, "%s: %s\n", identity ? "Dash identity and nested command lookup" : "status before output drain and repeated status", passed ? "PASS" : "FAIL"); return passed ? 0 : 1; } @@ -256,10 +259,137 @@ static int limit_check(void) { return passed ? 0 : 1; } +// Exercise the same public ABI from a host command and from its real worker child. +static int spawn_contract(BOOL nested, BOOL host) { + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, ashell_pane_options *, int *, void **) = dlsym(RTLD_DEFAULT, nested ? (host ? "ashell_worker_host_spawn_ex" : "ashell_worker_spawn_ex") : "ashell_pane_spawn_ex"); + int (*pollJob)(void *, int *, struct rusage *, int *) = dlsym(RTLD_DEFAULT, nested ? (host ? "ashell_worker_host_poll_usage" : "ashell_worker_poll_usage") : "ashell_pane_poll_usage"); + void (*release)(void *) = dlsym(RTLD_DEFAULT, nested ? (host ? "ashell_worker_host_release" : "ashell_worker_release") : "ashell_pane_release"); + if (!spawn || !pollJob || !release) { fputs("spawn contract unavailable: FAIL\n", thread_stdout); return 1; } + NSString *home = nested ? @(getenv("HOME")) : NSHomeDirectory(); + NSString *directory = [home stringByAppendingPathComponent:@"Documents"]; + NSString *homeValue = [@"HOME=" stringByAppendingString:home]; + NSString *expected = [@"POOL_EXPECTED_HOME=" stringByAppendingString:home]; + NSString *parent = [NSString stringWithFormat:@"POOL_PARENT_PID=%d", getpid()]; + NSString *hostPID = nested ? @(getenv("POOL_HOST_PID") ?: "") : [NSString stringWithFormat:@"%d", getpid()]; + NSString *hostValue = [@"POOL_HOST_PID=" stringByAppendingString:hostPID]; + const char *environment[] = {homeValue.UTF8String, expected.UTF8String, parent.UTF8String, hostValue.UTF8String, NULL}; + ashell_pane_options options = {.size = sizeof(options), .tty = 0, .separate_stderr = 1}; + int fd = -1, status = -1; + void *job = NULL; + const char *command = nested ? (host ? "worker-pool-host-payload" : "worker-pool-payload") : (host ? "worker-pool-nested-host" : "worker-pool-nested"); + int error = spawn(command, directory.fileSystemRepresentation, 80, 24, environment, &options, &fd, &job); + if (error) { fprintf(thread_stdout, "spawn contract startup=%d: FAIL\n", error); return 1; } + int descriptors[] = {fd, options.stderr_fd}; + char bytes[2][256] = {{0}}; + size_t used[2] = {0}; + BOOL eof[2] = {NO, NO}, completed = NO, valid = YES; + for (int i = 0; i < 2; i++) + if (fcntl(descriptors[i], F_SETFL, O_NONBLOCK) || !(fcntl(descriptors[i], F_GETFD) & FD_CLOEXEC)) valid = NO; + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 20; + struct rusage usage; + int available = 0; + while (valid && NSProcessInfo.processInfo.systemUptime < deadline && (!completed || !eof[0] || !eof[1])) { + for (int i = 0; i < 2; i++) { + ssize_t count = read(descriptors[i], bytes[i] + used[i], sizeof(bytes[i]) - used[i] - 1); + if (count > 0) used[i] += count; + else if (!count) eof[i] = YES; + else if (errno != EAGAIN && errno != EINTR) valid = NO; + } + int result = pollJob(job, &status, &usage, &available); + if (result < 0) valid = NO; + if (result == 1) completed = YES; + if (!completed || !eof[0] || !eof[1]) usleep(10000); + } + BOOL passed = valid && completed && eof[0] && eof[1] && available && status == 7 && + !strcmp(bytes[0], "PAYLOAD\n") && !strcmp(bytes[1], "ERROR\n"); + if (!passed) fprintf(thread_stderr, "spawn contract nested=%d valid=%d completed=%d eof=%d,%d usage=%d status=%d stdout=[%s] stderr=[%s]\n", nested, valid, completed, eof[0], eof[1], available, status, bytes[0], bytes[1]); + release(job); + close(fd); + close(options.stderr_fd); + if (!nested) fprintf(thread_stdout, "nested %s streams/tty/home/tmpdir/status/usage: %s\n", host ? "host" : "worker", passed ? "PASS" : "FAIL"); + return passed ? 0 : 1; +} + +int worker_pool_nested_main(int argc, char **argv) { + const char *home = getenv("HOME"), *expected = getenv("POOL_EXPECTED_HOME"); + const char *root = ios_getenv("ASHELL_WORKER_ROOT_PID"); + if (!root || atoi(root) != ios_currentPid() || !home || !expected || strcmp(home, expected) || spawn_contract(YES, NO)) return 1; + fputs("PAYLOAD\n", thread_stdout); + fputs("ERROR\n", thread_stderr); + return 7; +} + +int worker_pool_nested_host_main(int argc, char **argv) { + if (spawn_contract(YES, YES)) return 1; + fputs("PAYLOAD\n", thread_stdout); + fputs("ERROR\n", thread_stderr); + return 7; +} + +int worker_pool_host_payload_main(int argc, char **argv) { + const char *host = ios_getenv("POOL_HOST_PID"); + if (!host || atoi(host) != getpid() || ios_getenv("ASHELL_WORKER_PID") || ios_getenv("ASHELL_WORKER_ROOT_PID") || ios_isatty(1)) return 1; + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_host_pane_spawn"); + int fd = -1; + void *job = NULL; + NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; + if (!spawn || spawn("worker-pool-host-payload", directory.fileSystemRepresentation, 80, 24, NULL, &fd, &job) != EBUSY || fd != -1 || job) return 1; + fputs("PAYLOAD\n", thread_stdout); + fputs("ERROR\n", thread_stderr); + return 7; +} + +static int loss_check(void) { + int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); + int (*pollJob)(void *, int *) = dlsym(RTLD_DEFAULT, "ashell_pane_poll"); + void (*release)(void *) = dlsym(RTLD_DEFAULT, "ashell_pane_release"); + if (!spawn || !pollJob || !release) return 1; + int fd = -1, status = -1, result = 0; + void *job = NULL; + NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; + int error = spawn("worker-pool-crash", directory.fileSystemRepresentation, 80, 24, NULL, &fd, &job); + if (error) return 1; + NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 5; + while (!result && NSProcessInfo.processInfo.systemUptime < deadline) { + result = pollJob(job, &status); + if (!result) usleep(10000); + } + BOOL passed = result == -EPIPE && status == -1; + fprintf(thread_stdout, "lost worker result=%d status=%d: %s\n", result, status, passed ? "PASS" : "FAIL"); + release(job); + close(fd); + return passed ? 0 : 1; +} + +int worker_pool_payload_main(int argc, char **argv) { + const char *home = getenv("HOME"), *expected = getenv("POOL_EXPECTED_HOME"); + const char *temporary = getenv("TMPDIR"); + const char *parent = getenv("POOL_PARENT_PID"); + const char *root = ios_getenv("ASHELL_WORKER_ROOT_PID"); + if (!root || atoi(root) != ios_currentPid() || !home || !expected || strcmp(home, expected) || !temporary || + strcmp(temporary, NSTemporaryDirectory().fileSystemRepresentation) || !parent || getpid() == atoi(parent) || ios_isatty(1)) { + fprintf(thread_stderr, "payload root=%s pid=%d home=%d tmp_domain=%d process_distinct=%d tty=%d\n", root ?: "missing", ios_currentPid(), home && expected && !strcmp(home, expected), temporary && !strcmp(temporary, NSTemporaryDirectory().fileSystemRepresentation), parent && getpid() != atoi(parent), ios_isatty(1)); + return 1; + } + NSString *file = [@(temporary) stringByAppendingPathComponent:NSUUID.UUID.UUIDString]; + int fd = open(file.fileSystemRepresentation, O_CREAT | O_EXCL | O_RDWR, 0600); + if (fd < 0) return 1; + BOOL passed = write(fd, "x", 1) == 1; + if (close(fd) || unlink(file.fileSystemRepresentation)) passed = NO; + if (!passed) return 1; + fputs("PAYLOAD\n", thread_stdout); + fputs("ERROR\n", thread_stderr); + return 7; +} + // Run as a real app command. The same consumer must fail on the stock app. int worker_pool_check_main(int argc, char **argv) { @autoreleasepool { - if (argc == 2 && !strcmp(argv[1], "completion")) return completion_check(); + if (argc == 2 && !strcmp(argv[1], "nested")) return spawn_contract(NO, NO); + if (argc == 2 && !strcmp(argv[1], "host")) return spawn_contract(NO, YES); + if (argc == 2 && !strcmp(argv[1], "loss")) return loss_check(); + if (argc == 2 && !strcmp(argv[1], "completion")) return completion_check(NO); + if (argc == 2 && !strcmp(argv[1], "identity")) return completion_check(YES); if (argc == 2 && !strcmp(argv[1], "capacity")) return capacity_check(); if (argc == 2 && !strcmp(argv[1], "limit")) return limit_check(); if (argc == 2 && !strcmp(argv[1], "lifecycle")) return lifecycle_check(NO, NO); diff --git a/tests/worker-pool.md b/tests/worker-pool.md index 4dacd8b3..896256bb 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -9,6 +9,7 @@ Use the matching ios_system session/stream and Dash terminal changes, then run t ```sh worker-pool-check worker-pool-check completion +worker-pool-check identity worker-pool-check capacity worker-pool-check limit worker-pool-check lifecycle @@ -20,6 +21,8 @@ Each command returns zero on success and prints assertions to its output stream. The completion check leaves output unread until polling reports status 7, checks that a second poll preserves it, then reads the exact pending output and EOF. +The identity check supplies stale worker markers and runs real Dash with a nested Dash command. Both shells must see positive worker and root markers through their own environment import, and the nested command must resolve through the host's packaged PATH. It also checks status, pending output and EOF through the public pane API. + The limit check requires the default cap to equal `min(hw.physicalcpu, ShellWorkerCount)`, then sets `worker_limit` to 2, to the bundled count and above it (clamped to the bundled count), repeats the capacity check under each and restores the setting. Build the host with more workers than cores to see the default and the raised cap differ. The lifecycle checks cancel or close one worker, ask a second worker to terminate itself with `SIGKILL`, verify the surviving worker's input/output/status, and repeat the full capacity check. The busy variants make the first command ignore EOF. iOS denies host-to-extension `kill` with `EPERM`, so process loss is injected by the normal disposable command inside the worker. Run these checks only in a disposable build: they deliberately terminate its worker processes. @@ -27,3 +30,9 @@ The lifecycle checks cancel or close one worker, ask a second worker to terminat Register the same consumer in an unmodified host for the baseline. It must print `worker pool unavailable: FAIL` and return one. A Release build must export the public C functions and callbacks loaded through `dlsym`; a consumer compiled into an executable with hidden symbols does not prove that interface usable by a dynamic command. The upstream configuration remains ten workers. Historical iOS 27 Simulator tests passed ten-slot capacity and lifecycle checks. A physical run with three provisioned identities qualifies three-worker behavior only; it does not qualify ten-worker device capacity, background lifetime or App Store acceptance. + +`worker-pool-check loss` starts the disposable crash command and requires `-EPIPE` with no fabricated command status. Explicit cancellation remains distinct from unexpected XPC loss. + +`worker-pool-check host` starts a real extension command, which calls `ashell_worker_host_spawn_ex` to run the payload back in the app process. Register `worker-pool-nested-host` and `worker-pool-host-payload` with entries `worker_pool_nested_host_main` and `worker_pool_host_payload_main` in the disposable catalogues. It checks the original app PID, absence of worker identity markers, plain streams, separate stderr, status, resource usage and `EBUSY` for a second host pane. The command admission policy and high-memory workload qualification belong to the caller. + +`worker-pool-check nested` exercises the public `spawn_ex` contract through two real extension processes. Register `worker-pool-nested` and `worker-pool-payload` in the disposable worker catalogues with entries `worker_pool_nested_main` and `worker_pool_payload_main` from the same checks framework and corresponding PATH markers. The outer command calls the host API; its worker calls `ashell_worker_spawn_ex` over the broker. The payload checks a distinct process, non-terminal output, preserved host HOME and a writable TMPDIR matching its own Foundation temporary directory. Both levels drain stdout and stderr independently, require exact bytes, exit status 7, descriptor close-on-exec and a final resource-usage snapshot. The baseline without the extended API must fail. No Herdr engine or terminal UI is involved. From b33ae540a18dc763b46aedbe4c227e5a5f071de2 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:31:34 +0300 Subject: [PATCH 09/16] Close pane descriptors when stream setup fails --- ShellWorkers/NativePane.m | 23 ++++++++++++--------- tests/pane-descriptors.m | 43 +++++++++++++++++++++++++++++++++++++++ tests/worker-pool.md | 2 ++ 3 files changed, 58 insertions(+), 10 deletions(-) create mode 100644 tests/pane-descriptors.m diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m index 920dee96..51e60221 100644 --- a/ShellWorkers/NativePane.m +++ b/ShellWorkers/NativePane.m @@ -611,7 +611,7 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un } int expected = 0; if (!atomic_compare_exchange_strong(&pane_in_flight, &expected, 1)) return EBUSY; - int error = ENOMEM, peer = -1; + int error = ENOMEM, peer = -1, child = -1, err_child = -1; pane_job *job = calloc(1, sizeof(*job)); if (!job) { atomic_store(&pane_in_flight, 0); return ENOMEM; } job->peer_control = -1; @@ -660,11 +660,11 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un } if (!wants_pty && socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) { error = errno; goto failed; } peer = fds[0]; - int child = fds[1]; + child = fds[1]; if (job->is_pty) { struct termios settings; - if (tcgetattr(child, &settings)) { error = errno; close(child); goto failed; } - if (settings.c_cc[VEOF] == _POSIX_VDISABLE) { error = ENOTSUP; close(child); goto failed; } + if (tcgetattr(child, &settings)) { error = errno; goto failed; } + if (settings.c_cc[VEOF] == _POSIX_VDISABLE) { error = ENOTSUP; goto failed; } job->eof_key = settings.c_cc[VEOF]; // Commands share an application process: never enable kernel process-group signals. settings.c_lflag &= ~ISIG; @@ -675,13 +675,12 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un error = socket_options(peer); if (!error) error = socket_options(child); } - if (error) { close(child); goto failed; } + if (error) goto failed; job->peer_control = dup(peer); - if (job->peer_control < 0) { error = errno; close(child); goto failed; } + if (job->peer_control < 0) { error = errno; goto failed; } error = job->is_pty ? (fcntl(job->peer_control, F_SETFD, FD_CLOEXEC) ? errno : 0) : socket_options(job->peer_control); if (!error && job->is_pty && fcntl(peer, F_SETFD, FD_CLOEXEC)) error = errno; - if (error) { close(child); goto failed; } - int err_child = -1; + if (error) goto failed; if (options->separate_stderr) { int pair[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair)) { error = errno; goto failed; } @@ -689,11 +688,13 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un err_child = pair[1]; error = socket_options(peer_err); if (!error) error = socket_options(err_child); - if (error) { close(err_child); goto failed; } + if (error) goto failed; } for (int i = 0; i < 3; i++) { - int fd = i == 0 ? child : i == 2 && err_child >= 0 ? err_child : dup(child); + int fd = i == 0 ? child : i == 2 && err_child >= 0 ? err_child : dup(fileno(job->streams[0])); if (fd < 0) { error = errno; goto failed; } + if (i == 0) child = -1; + if (i == 2) err_child = -1; job->streams[i] = fdopen(fd, i == 0 ? "r" : "w"); if (!job->streams[i]) { error = errno; close(fd); goto failed; } if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { error = errno; goto failed; } @@ -729,6 +730,8 @@ int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, un *job_out = job; return 0; failed: + if (child >= 0) close(child); + if (err_child >= 0) close(err_child); close_streams(job); if (peer >= 0) close(peer); if (peer_err >= 0) close(peer_err); diff --git a/tests/pane-descriptors.m b/tests/pane-descriptors.m new file mode 100644 index 00000000..7b857a60 --- /dev/null +++ b/tests/pane-descriptors.m @@ -0,0 +1,43 @@ +#import +#import +#include +#include +#include +#include +#include +#include "../ShellWorkers/NativePane.h" + +// Run in a disposable process: resource limits apply to every thread. +int main(void) { + @autoreleasepool { + thread_stdin = stdin; + thread_stdout = stdout; + thread_stderr = stderr; + (void)NSUUID.UUID.UUIDString; + struct rlimit original; + if (getrlimit(RLIMIT_NOFILE, &original) || original.rlim_cur < 64) return 64; + for (int budget = 0; budget <= 6; budget++) { + struct rlimit limited = original; + limited.rlim_cur = 64; + if (setrlimit(RLIMIT_NOFILE, &limited)) return 64; + int fillers[64], count = 0, fd; + while (count < 64 && (fd = open("/dev/null", O_RDONLY)) >= 0) fillers[count++] = fd; + if (count < budget) return 64; + for (int i = 0; i < budget; i++) close(fillers[--count]); + int before = 0; + for (int i = 0; i < 64; i++) if (fcntl(i, F_GETFD) >= 0) before++; + ashell_pane_options options = { .size = sizeof(options), .tty = 0, .separate_stderr = 1 }; + int output = -1; + void *job = NULL; + int error = ashell_pane_spawn_ex("true", "/tmp", 80, 24, NULL, &options, &output, &job); + int after = 0; + for (int i = 0; i < 64; i++) if (fcntl(i, F_GETFD) >= 0) after++; + int restored = setrlimit(RLIMIT_NOFILE, &original); + for (int i = 0; i < count; i++) close(fillers[i]); + BOOL passed = !restored && error == EMFILE && output == -1 && job == NULL && options.stderr_fd == -1 && before == after; + printf("descriptor budget=%d error=%d delta=%d: %s\n", budget, error, after - before, passed ? "PASS" : "FAIL"); + if (!passed) return 1; + } + return 0; + } +} diff --git a/tests/worker-pool.md b/tests/worker-pool.md index 896256bb..77bfad2e 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -31,6 +31,8 @@ Register the same consumer in an unmodified host for the baseline. It must print The upstream configuration remains ten workers. Historical iOS 27 Simulator tests passed ten-slot capacity and lifecycle checks. A physical run with three provisioned identities qualifies three-worker behavior only; it does not qualify ten-worker device capacity, background lifetime or App Store acceptance. +`pane-descriptors.m` is a standalone consumer of the public native pane API. Compile it together with `ShellWorkers/NativePane.m`, linking Foundation and the matching ios_system framework, for an owned Simulator and run it with `xcrun simctl spawn `. It limits only its disposable process to 64 descriptors, fills the table, and retries separate-stderr/plain-stream spawns with zero through six available descriptors. Every call must return `EMFILE`, leave all outputs empty and preserve the open-descriptor count. It restores the original limit before reporting. The baseline leaks one descriptor with three available slots; the fixed runner passes all seven budgets. Do not run it inside the app process. + `worker-pool-check loss` starts the disposable crash command and requires `-EPIPE` with no fabricated command status. Explicit cancellation remains distinct from unexpected XPC loss. `worker-pool-check host` starts a real extension command, which calls `ashell_worker_host_spawn_ex` to run the payload back in the app process. Register `worker-pool-nested-host` and `worker-pool-host-payload` with entries `worker_pool_nested_host_main` and `worker_pool_host_payload_main` in the disposable catalogues. It checks the original app PID, absence of worker identity markers, plain streams, separate stderr, status, resource usage and `EBUSY` for a second host pane. The command admission policy and high-memory workload qualification belong to the caller. From cf020ff553537563e9d2f23c6b9d25ef274606e3 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:41:23 +0300 Subject: [PATCH 10/16] Document host pane interrupt and usage contracts --- ShellWorkers/HostPane.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ShellWorkers/HostPane.h b/ShellWorkers/HostPane.h index b5f6c7f9..c9e7a863 100644 --- a/ShellWorkers/HostPane.h +++ b/ShellWorkers/HostPane.h @@ -12,8 +12,11 @@ extern "C" { // Uses the same streams, options and handle lifetime as NativePane.h. One live host // pane is admitted (EBUSY for another); it shares the app's process cwd and memory. // No extension allocation or automatic routing is performed. Do not forward worker -// identity environment overrides. Cancellation returns ENOTSUP while running; -// interrupt targets the foreground command, and release retains live cleanup. +// identity environment overrides. Cancellation returns ENOTSUP while running. +// Interrupt requires a Dash foreground command with ASHELL_IOS_SOCKET_INPUT=1 +// in envp; otherwise it can return ESRCH. Its PID hook is process-wide: unrelated +// Dash sessions must not enable that variable concurrently. Release retains live cleanup. +// poll_usage returns the app process RUSAGE_SELF at exit, not per-command usage. int ashell_host_pane_spawn(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **); int ashell_host_pane_spawn_ex(const char *, const char *, unsigned, unsigned, const char *const *, ashell_pane_options *, int *, void **); int ashell_host_pane_poll(void *, int *); From ad7d258acca9deaab3777bfa434bae0aca97daa2 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:09:39 +0300 Subject: [PATCH 11/16] Report individual worker completion assertion failures --- tests/worker-pool.m | 23 ++++++++++++++++++++--- tests/worker-pool.md | 2 +- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/tests/worker-pool.m b/tests/worker-pool.m index dc9394a1..8e3fac44 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -215,13 +215,30 @@ static int completion_check(BOOL identity) { result = pollJob(job, &status); if (!result) usleep(10000); } + int first_status = status, repeated_result = 0, repeated_status = -1; BOOL passed = result == 1 && status == 7; status = -1; - passed = passed && pollJob(job, &status) == 1 && status == 7; + if (passed) { + repeated_result = pollJob(job, &status); + repeated_status = status; + passed = repeated_result == 1 && status == 7; + } char output[64] = {0}; ssize_t count = passed ? read(descriptor, output, sizeof(output) - 1) : -1; - passed = passed && count == 14 && !strcmp(output, "pending-output"); - if (passed) passed = read(descriptor, output, 1) == 0; + int read_error = passed && count < 0 ? errno : 0; + BOOL output_matches = count == 14 && !strcmp(output, "pending-output"); + passed = passed && output_matches; + ssize_t eof = -1; + if (passed) { + eof = read(descriptor, output, 1); + if (eof < 0) read_error = errno; + passed = eof == 0; + } + if (!passed) { + struct pollfd ready = {.fd = descriptor, .events = POLLIN}; + int ready_result = poll(&ready, 1, 0); + fprintf(thread_stdout, "completion result=%d status=%d repeated_result=%d repeated_status=%d bytes=%zd output_matches=%d eof=%zd read_errno=%d readiness=%d revents=%#x\n", result, first_status, repeated_result, repeated_status, count, output_matches, eof, read_error, ready_result, ready.revents); + } release(job); close(descriptor); fprintf(thread_stdout, "%s: %s\n", identity ? "Dash identity and nested command lookup" : "status before output drain and repeated status", passed ? "PASS" : "FAIL"); diff --git a/tests/worker-pool.md b/tests/worker-pool.md index 77bfad2e..d2ec2d24 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -19,7 +19,7 @@ worker-pool-check lifecycle-close Each command returns zero on success and prints assertions to its output stream. The capacity check asks the host for the effective cap (`ashell_pane_capacity`: the `worker_limit` setting, or the physical core count when unset, at most `ShellWorkerCount` from the host Info.plist), keeps that many commands open, requires distinct real process IDs and independent cwd/environment, rejects one additional request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. It compares directory device/inode pairs because the phone can return `/private/var/...` for a cwd requested through its `/var/...` alias. -The completion check leaves output unread until polling reports status 7, checks that a second poll preserves it, then reads the exact pending output and EOF. +The completion check leaves output unread until polling reports status 7, checks that a second poll preserves it, then reads the exact pending output and EOF. On failure it prints the first and repeated poll results and statuses, byte count, output match, EOF result, read errno and socket readiness. A skipped repeated poll or read retains its initial sentinel; the diagnostic does not drain output before the status checks. The identity check supplies stale worker markers and runs real Dash with a nested Dash command. Both shells must see positive worker and root markers through their own environment import, and the nested command must resolve through the host's packaged PATH. It also checks status, pending output and EOF through the public pane API. From 97551c93cee6d4d4489043ca817608438cb15213 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:44:23 +0300 Subject: [PATCH 12/16] Keep worker fixtures independent of Dash login profiles --- tests/worker-pool.m | 15 +++++++++------ tests/worker-pool.md | 2 ++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/worker-pool.m b/tests/worker-pool.m index 8e3fac44..4bb3fe1f 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -13,6 +13,9 @@ #define MAX_WORKERS 64 +// Dash fixture commands must not source the user's login profile. +static const char *const nonlogin_environment[] = {"_DASH_LOGIN_SHELL=1", NULL}; + // Keep each command alive at its public stdin boundary while the other slots start. static int capacity_check(void) { int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); @@ -37,7 +40,7 @@ static int capacity_check(void) { if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil]) { passed = NO; break; } char value[32], command[256]; snprintf(value, sizeof(value), "POOL_VALUE=slot-%d", i); - const char *environment[] = {value, NULL}; + const char *environment[] = {value, "_DASH_LOGIN_SHELL=1", NULL}; snprintf(command, sizeof(command), "dash -c 'printf \"READY=%%s,%%s\\n\" \"$ASHELL_WORKER_PID\" \"$POOL_VALUE\"; pwd; read value; printf \"END=%%s\\n\" \"$value\"; exit %d'", i); int error = spawn(command, directory.fileSystemRepresentation, 80, 24, environment, &descriptors[i], &jobs[i]); if (error) { fprintf(thread_stdout, "slot=%d startup error=%d: FAIL\n", i, error); passed = NO; break; } @@ -77,7 +80,7 @@ static int capacity_check(void) { if (passed) { int descriptor = -1; void *job = NULL; - int error = spawn("dash -c 'exit 0'", root.fileSystemRepresentation, 80, 24, NULL, &descriptor, &job); + int error = spawn("dash -c 'exit 0'", root.fileSystemRepresentation, 80, 24, nonlogin_environment, &descriptor, &job); BOOL full = error == ENOSPC && descriptor == -1 && job == NULL; fprintf(thread_stdout, "worker=%d error=%d: %s\n", capacity + 1, error, full ? "PASS" : "FAIL"); if (job) release(job); @@ -128,7 +131,7 @@ static int lifecycle_check(BOOL busy, BOOL closeOnly) { BOOL passed = YES; for (int i = 0; i < 3; i++) { const char *command = i == 1 ? "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; read value; worker-pool-crash'" : busy && i == 0 ? "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; while :; do :; done'" : "dash -c 'printf \"READY=%s\\n\" \"$ASHELL_WORKER_PID\"; read value; printf \"DONE=%s\\n\" \"$value\"; exit 7'"; - int error = spawn(command, directory.fileSystemRepresentation, 80, 24, NULL, &descriptors[i], &jobs[i]); + int error = spawn(command, directory.fileSystemRepresentation, 80, 24, nonlogin_environment, &descriptors[i], &jobs[i]); if (error) { fprintf(thread_stdout, "lifecycle slot=%d startup=%d: FAIL\n", i, error); passed = NO; break; } struct pollfd ready = {.fd = descriptors[i], .events = POLLIN}; char output[128] = {0}; @@ -206,9 +209,9 @@ static int completion_check(BOOL identity) { NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; int descriptor = -1, status = -1, result = 0; void *job = NULL; - const char *environment[] = {"ASHELL_WORKER_PID=-1", "ASHELL_WORKER_ROOT_PID=-1", NULL}; + const char *environment[] = {"ASHELL_WORKER_PID=-1", "ASHELL_WORKER_ROOT_PID=-1", "_DASH_LOGIN_SHELL=1", NULL}; const char *command = identity ? "dash -c 'test \"$ASHELL_WORKER_PID\" -gt 0 && test \"$ASHELL_WORKER_ROOT_PID\" -gt 0 && dash -c \"test \\\"\\$ASHELL_WORKER_PID\\\" -gt 0 && test \\\"\\$ASHELL_WORKER_ROOT_PID\\\" -gt 0\" && printf pending-output; exit 7'" : "dash -c 'printf pending-output; exit 7'"; - int error = spawn(command, directory.fileSystemRepresentation, 80, 24, identity ? environment : NULL, &descriptor, &job); + int error = spawn(command, directory.fileSystemRepresentation, 80, 24, identity ? environment : nonlogin_environment, &descriptor, &job); if (error) { fprintf(thread_stdout, "completion startup=%d: FAIL\n", error); return 1; } NSTimeInterval deadline = NSProcessInfo.processInfo.systemUptime + 10; while (!result && NSProcessInfo.processInfo.systemUptime < deadline) { @@ -420,7 +423,7 @@ int worker_pool_check_main(int argc, char **argv) { return 1; } NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; - const char *environment[] = {"POOL_VALUE=isolated", NULL}; + const char *environment[] = {"POOL_VALUE=isolated", "_DASH_LOGIN_SHELL=1", NULL}; int descriptor = -1; void *job = NULL; int error = spawn("dash -c 'printf \"WORKER=%s\\n\" \"$POOL_VALUE\"'", directory.fileSystemRepresentation, 80, 24, environment, &descriptor, &job); diff --git a/tests/worker-pool.md b/tests/worker-pool.md index d2ec2d24..7468375a 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -19,6 +19,8 @@ worker-pool-check lifecycle-close Each command returns zero on success and prints assertions to its output stream. The capacity check asks the host for the effective cap (`ashell_pane_capacity`: the `worker_limit` setting, or the physical core count when unset, at most `ShellWorkerCount` from the host Info.plist), keeps that many commands open, requires distinct real process IDs and independent cwd/environment, rejects one additional request with `ENOSPC`, then sends input after six seconds and checks exact exit statuses and output EOF. It compares directory device/inode pairs because the phone can return `/private/var/...` for a cwd requested through its `/var/...` alias. +Dash fixture spawns pass `_DASH_LOGIN_SHELL=1` through the public environment argument. The published Dash otherwise treats its first invocation as a login shell, even with `-c`, and reads the user's profile; an `alias exit=clear` can turn the fixture's `exit 7` into an unresolved command returning 127. The fixture leaves the user's profile and production shell behavior unchanged. For a regression check, retain that alias in the disposable Simulator profile: the original fixture must return 127, while the explicit non-login environment must preserve status 7, exact pending output and EOF. + The completion check leaves output unread until polling reports status 7, checks that a second poll preserves it, then reads the exact pending output and EOF. On failure it prints the first and repeated poll results and statuses, byte count, output match, EOF result, read errno and socket readiness. A skipped repeated poll or read retains its initial sentinel; the diagnostic does not drain output before the status checks. The identity check supplies stale worker markers and runs real Dash with a nested Dash command. Both shells must see positive worker and root markers through their own environment import, and the nested command must resolve through the host's packaged PATH. It also checks status, pending output and EOF through the public pane API. From 41192c3610567462a0856890dd623ea2b1d58b2f Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:03:39 +0300 Subject: [PATCH 13/16] Compare worker fixture HOME by directory identity --- tests/worker-pool.m | 20 ++++++++++++++++---- tests/worker-pool.md | 2 +- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/tests/worker-pool.m b/tests/worker-pool.m index 4bb3fe1f..1ad39ff1 100644 --- a/tests/worker-pool.m +++ b/tests/worker-pool.m @@ -16,6 +16,13 @@ // Dash fixture commands must not source the user's login profile. static const char *const nonlogin_environment[] = {"_DASH_LOGIN_SHELL=1", NULL}; +// Host bookmarks can resolve /var and /private/var to the same HOME directory. +static BOOL same_directory(const char *left, const char *right) { + struct stat a, b; + return left && right && stat(left, &a) == 0 && stat(right, &b) == 0 && + S_ISDIR(a.st_mode) && S_ISDIR(b.st_mode) && a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + // Keep each command alive at its public stdin boundary while the other slots start. static int capacity_check(void) { int (*spawn)(const char *, const char *, unsigned, unsigned, const char *const *, int *, void **) = dlsym(RTLD_DEFAULT, "ashell_pane_spawn"); @@ -285,7 +292,8 @@ static int spawn_contract(BOOL nested, BOOL host) { int (*pollJob)(void *, int *, struct rusage *, int *) = dlsym(RTLD_DEFAULT, nested ? (host ? "ashell_worker_host_poll_usage" : "ashell_worker_poll_usage") : "ashell_pane_poll_usage"); void (*release)(void *) = dlsym(RTLD_DEFAULT, nested ? (host ? "ashell_worker_host_release" : "ashell_worker_release") : "ashell_pane_release"); if (!spawn || !pollJob || !release) { fputs("spawn contract unavailable: FAIL\n", thread_stdout); return 1; } - NSString *home = nested ? @(getenv("HOME")) : NSHomeDirectory(); + // Exercise a caller HOME spelling that the worker bookmark may normalize. + NSString *home = nested ? @(getenv("HOME")) : [NSHomeDirectory() stringByAppendingString:@"/."]; NSString *directory = [home stringByAppendingPathComponent:@"Documents"]; NSString *homeValue = [@"HOME=" stringByAppendingString:home]; NSString *expected = [@"POOL_EXPECTED_HOME=" stringByAppendingString:home]; @@ -333,7 +341,11 @@ static int spawn_contract(BOOL nested, BOOL host) { int worker_pool_nested_main(int argc, char **argv) { const char *home = getenv("HOME"), *expected = getenv("POOL_EXPECTED_HOME"); const char *root = ios_getenv("ASHELL_WORKER_ROOT_PID"); - if (!root || atoi(root) != ios_currentPid() || !home || !expected || strcmp(home, expected) || spawn_contract(YES, NO)) return 1; + if (!root || atoi(root) != ios_currentPid() || !same_directory(home, expected)) { + fprintf(thread_stderr, "nested context root=%s pid=%d home_same=%d home=%s expected=%s\n", root ?: "missing", ios_currentPid(), same_directory(home, expected), home ?: "missing", expected ?: "missing"); + return 1; + } + if (spawn_contract(YES, NO)) return 1; fputs("PAYLOAD\n", thread_stdout); fputs("ERROR\n", thread_stderr); return 7; @@ -386,9 +398,9 @@ int worker_pool_payload_main(int argc, char **argv) { const char *temporary = getenv("TMPDIR"); const char *parent = getenv("POOL_PARENT_PID"); const char *root = ios_getenv("ASHELL_WORKER_ROOT_PID"); - if (!root || atoi(root) != ios_currentPid() || !home || !expected || strcmp(home, expected) || !temporary || + if (!root || atoi(root) != ios_currentPid() || !home || !expected || !same_directory(home, expected) || !temporary || strcmp(temporary, NSTemporaryDirectory().fileSystemRepresentation) || !parent || getpid() == atoi(parent) || ios_isatty(1)) { - fprintf(thread_stderr, "payload root=%s pid=%d home=%d tmp_domain=%d process_distinct=%d tty=%d\n", root ?: "missing", ios_currentPid(), home && expected && !strcmp(home, expected), temporary && !strcmp(temporary, NSTemporaryDirectory().fileSystemRepresentation), parent && getpid() != atoi(parent), ios_isatty(1)); + fprintf(thread_stderr, "payload root=%s pid=%d home=%d tmp_domain=%d process_distinct=%d tty=%d\n", root ?: "missing", ios_currentPid(), home && expected && same_directory(home, expected), temporary && !strcmp(temporary, NSTemporaryDirectory().fileSystemRepresentation), parent && getpid() != atoi(parent), ios_isatty(1)); return 1; } NSString *file = [@(temporary) stringByAppendingPathComponent:NSUUID.UUID.UUIDString]; diff --git a/tests/worker-pool.md b/tests/worker-pool.md index 7468375a..685cdafb 100644 --- a/tests/worker-pool.md +++ b/tests/worker-pool.md @@ -39,4 +39,4 @@ The upstream configuration remains ten workers. Historical iOS 27 Simulator test `worker-pool-check host` starts a real extension command, which calls `ashell_worker_host_spawn_ex` to run the payload back in the app process. Register `worker-pool-nested-host` and `worker-pool-host-payload` with entries `worker_pool_nested_host_main` and `worker_pool_host_payload_main` in the disposable catalogues. It checks the original app PID, absence of worker identity markers, plain streams, separate stderr, status, resource usage and `EBUSY` for a second host pane. The command admission policy and high-memory workload qualification belong to the caller. -`worker-pool-check nested` exercises the public `spawn_ex` contract through two real extension processes. Register `worker-pool-nested` and `worker-pool-payload` in the disposable worker catalogues with entries `worker_pool_nested_main` and `worker_pool_payload_main` from the same checks framework and corresponding PATH markers. The outer command calls the host API; its worker calls `ashell_worker_spawn_ex` over the broker. The payload checks a distinct process, non-terminal output, preserved host HOME and a writable TMPDIR matching its own Foundation temporary directory. Both levels drain stdout and stderr independently, require exact bytes, exit status 7, descriptor close-on-exec and a final resource-usage snapshot. The baseline without the extended API must fail. No Herdr engine or terminal UI is involved. +`worker-pool-check nested` exercises the public `spawn_ex` contract through two real extension processes. Register `worker-pool-nested` and `worker-pool-payload` in the disposable worker catalogues with entries `worker_pool_nested_main` and `worker_pool_payload_main` from the same checks framework and corresponding PATH markers. The outer command calls the host API; its worker calls `ashell_worker_spawn_ex` over the broker. The caller supplies HOME with a trailing `/.` to exercise bookmark path normalization. The payload checks a distinct process, non-terminal output, HOME naming the same directory by device/inode, and a writable TMPDIR matching its own Foundation temporary directory. Literal HOME spelling can differ on the phone (`/var` versus `/private/var`); it must still name the same directory. The outer worker reports root identity and HOME context if its preconditions fail. Both levels drain stdout and stderr independently, require exact bytes, exit status 7, descriptor close-on-exec and a final resource-usage snapshot. The baseline without the extended API must fail. No Herdr engine or terminal UI is involved. From 04db79a011ef5b04772cf1c4ad826575103b69b0 Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:31:37 +0300 Subject: [PATCH 14/16] Add nested shell-worker requests and shared-container admission --- ShellWorkers/Host.swift | 103 +++++++++++---- ShellWorkers/NativePane.h | 30 +++++ ShellWorkers/NativePane.m | 105 ++++++++++++--- ShellWorkers/PaneWire.h | 18 ++- ShellWorkers/RemotePane.m | 161 +++++++++++++++++++++-- ShellWorkers/Worker.entitlements | 6 + ShellWorkers/Worker.m | 208 +++++++++++++++++++++++++----- ShellWorkers/Worker.xcconfig | 2 + a-Shell/a-Shell-Bridging-Header.h | 2 + 9 files changed, 551 insertions(+), 84 deletions(-) create mode 100644 ShellWorkers/Worker.entitlements diff --git a/ShellWorkers/Host.swift b/ShellWorkers/Host.swift index 9028e57e..c1ee5a88 100644 --- a/ShellWorkers/Host.swift +++ b/ShellWorkers/Host.swift @@ -15,25 +15,35 @@ final class ShellWorkerPool { static let shared = ShellWorkerPool() private enum Slot { case launching(UUID) - case connected(UUID, AppExtensionProcess, NSXPCConnection) + case connected(UUID, AppExtensionProcess, NSXPCConnection, DispatchSourceProcess?) + case retiring(UUID, DispatchSourceProcess?) var generation: UUID { switch self { - case .launching(let generation), .connected(let generation, _, _): generation + case .launching(let generation), .connected(let generation, _, _, _), .retiring(let generation, _): generation } } } private var slots: [String: Slot] = [:] - func connect() async throws -> NSXPCConnection { + func connect(requiredGroup: String?) async throws -> NSXPCConnection { guard Bundle.main.object(forInfoDictionaryKey: "ShellWorkerCount") != nil else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENOTSUP)) } let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: .shellWorker) + if let requiredGroup { + guard requiredGroup == Bundle.main.object(forInfoDictionaryKey: "AppGroupIdentifier") as? String else { + throw NSError(domain: NSPOSIXErrorDomain, code: Int(EACCES)) + } + } for _ in 0..<100 { let configured = Bundle.main.object(forInfoDictionaryKey: "ShellWorkerCount") let capacity = (configured as? NSNumber)?.intValue ?? Int(configured as? String ?? "") ?? 0 if capacity > 0 && slots.count >= capacity { + if slots.values.contains(where: { if case .retiring = $0 { return true }; return false }) { + try await Task.sleep(for: .milliseconds(100)) + continue + } throw NSError(domain: NSPOSIXErrorDomain, code: Int(ENOSPC), userInfo: [NSLocalizedDescriptionKey: "All shell workers are in use. Close a pane before opening another."]) } if let identity = monitor.identities.sorted(by: { $0.bundleIdentifier < $1.bundleIdentifier }).first(where: { slots[$0.bundleIdentifier] == nil }) { @@ -44,7 +54,10 @@ final class ShellWorkerPool { let process = try await AppExtensionProcess(configuration: .init(appExtensionIdentity: identity, onInterruption: { Task { @MainActor in guard self.slots[key]?.generation == generation else { return } - self.slots.removeValue(forKey: key) + // A connected worker is retired using its spawn-reply PID. + if case .launching = self.slots[key] { + self.slots.removeValue(forKey: key) + } } })) guard slots[key]?.generation == generation else { @@ -52,7 +65,9 @@ final class ShellWorkerPool { throw CancellationError() } let connection = try process.makeXPCConnection() - slots[key] = .connected(generation, process, connection) + connection.exportedInterface = NSXPCInterface(with: AShellSpawnBrokerWire.self) + connection.exportedObject = ashell_spawn_broker() + slots[key] = .connected(generation, process, connection, nil) return connection } catch { if slots[key]?.generation == generation { slots.removeValue(forKey: key) } @@ -61,38 +76,82 @@ final class ShellWorkerPool { } try await Task.sleep(for: .milliseconds(100)) } - throw NSError(domain: NSPOSIXErrorDomain, code: Int(ETIMEDOUT), userInfo: [NSLocalizedDescriptionKey: "shell worker discovery timed out"]) + throw NSError(domain: NSPOSIXErrorDomain, code: Int(ETIMEDOUT), userInfo: [NSLocalizedDescriptionKey: "Shell worker discovery timed out"]) + } + + func observe(_ connection: NSXPCConnection, pid: pid_t, registered: @escaping () -> Void) { + for (key, slot) in slots { + guard case .connected(let generation, let process, let stored, nil) = slot, stored === connection else { continue } + let exit = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: .main) + slots[key] = .connected(generation, process, connection, exit) + exit.setEventHandler { [weak self] in + Task { @MainActor in + guard let self, let current = self.slots[key], current.generation == generation else { return } + let source: DispatchSourceProcess? + switch current { + case .connected(_, _, _, let value), .retiring(_, let value): source = value + case .launching: return + } + source?.cancel() + connection.invalidate() + process.invalidate() + self.slots.removeValue(forKey: key) + } + } + // Arm observation while the admitted process is still alive. + exit.setRegistrationHandler(handler: registered) + exit.resume() + return + } + registered() } func disconnect(_ connection: NSXPCConnection) { for (key, slot) in slots { - guard case .connected(_, let process, let stored) = slot, stored === connection else { continue } - // Explicit invalidation does not guarantee an interruption callback. - // Release the reservation in this MainActor transaction; generation - // checks keep a late callback from removing a replacement process. - connection.invalidate() - process.invalidate() - slots.removeValue(forKey: key) + guard case .connected(let generation, let process, let stored, let exit) = slot, stored === connection else { continue } + if exit == nil { + connection.invalidate() + process.invalidate() + slots.removeValue(forKey: key) + return + } + slots[key] = .retiring(generation, exit) + // Keep the process assertion until exit, with a deadline if observation fails. + Task { @MainActor in + try? await Task.sleep(for: .seconds(2)) + guard case .retiring(let current, let source) = self.slots[key], current == generation else { return } + source?.cancel() + connection.invalidate() + process.invalidate() + self.slots.removeValue(forKey: key) + } return } } } +@_cdecl("ashell_extension_observe") +func shellExtensionObserve(_ connection: NSXPCConnection, _ pid: pid_t) { + if #available(iOS 26.0, *), pid > 0 { + let registered = DispatchSemaphore(value: 0) + Task { @MainActor in + ShellWorkerPool.shared.observe(connection, pid: pid) { registered.signal() } + } + _ = registered.wait(timeout: .now() + 1) + } +} + @_cdecl("ashell_extension_disconnect") func shellExtensionDisconnect(_ connection: NSXPCConnection) { - if #available(iOS 26.0, *) { - Task { @MainActor in ShellWorkerPool.shared.disconnect(connection) } - } + if #available(iOS 26.0, *) { Task { @MainActor in ShellWorkerPool.shared.disconnect(connection) } } } @_cdecl("ashell_extension_connect") -func shellExtensionConnect(_ callback: @escaping @convention(block) (NSXPCConnection?, NSError?) -> Void) { - guard #available(iOS 26.0, *) else { - callback(nil, NSError(domain: NSPOSIXErrorDomain, code: Int(ENOTSUP))) - return - } +func shellExtensionConnect(_ requiredGroup: UnsafePointer?, _ callback: @escaping @convention(block) (NSXPCConnection?, NSError?) -> Void) { + guard #available(iOS 26.0, *) else { callback(nil, NSError(domain: NSPOSIXErrorDomain, code: Int(ENOTSUP))); return } + let group = requiredGroup.map { String(cString: $0) } Task { @MainActor in - do { callback(try await ShellWorkerPool.shared.connect(), nil) } + do { callback(try await ShellWorkerPool.shared.connect(requiredGroup: group), nil) } catch { callback(nil, error as NSError) } } } diff --git a/ShellWorkers/NativePane.h b/ShellWorkers/NativePane.h index 0249cf84..a405450a 100644 --- a/ShellWorkers/NativePane.h +++ b/ShellWorkers/NativePane.h @@ -1,10 +1,16 @@ #ifndef ASHELL_NATIVE_PANE_H #define ASHELL_NATIVE_PANE_H +#include +#include + #ifdef __cplusplus extern "C" { #endif +// Keep the public C ABI discoverable in Release builds with hidden visibility. +#pragma GCC visibility push(default) + // command/cwd must be nonempty UTF-8; cwd must be an absolute accessible directory. // envp is NULL or a NULL-terminated list of UTF-8 key=value overrides, copied before return. // Dimensions are 1..9999. Returns 0 or positive errno; failure sets outputs to -1/NULL. @@ -15,10 +21,32 @@ extern "C" { int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out); +// Options for ashell_pane_spawn_ex. The caller sets size to sizeof(ashell_pane_options). +typedef struct ashell_pane_options { + size_t size; + // Nonzero: the command sees a terminal on stdin, stdout and stderr (isatty is true). + // Zero: it sees plain streams, as when the caller redirects them to a file or a pipe. + int tty; + // Nonzero: stderr is a separate stream; its read side is written to stderr_fd. + int separate_stderr; + // Output, -1 unless separate_stderr succeeded. The caller owns and closes it. Drain it + // as well as the main fd; a full unread stderr blocks the command like a full stdout. + int stderr_fd; +} ashell_pane_options; + +// ashell_pane_spawn with options. ashell_pane_spawn is this call with tty = 1 and +// separate_stderr = 0, so its behaviour is unchanged. Returns 0 or positive errno. +int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, + const char *const *envp, ashell_pane_options *options, + int *fd_out, void **job_out); + // Returns 0 running, 1 exited (writes final command status), or -errno. // Repeated polling after exit preserves status. Drain the returned fd to EOF independently. // A cleanup/restore error returns -errno after completion instead of hiding the failure. int ashell_pane_poll(void *job, int *status_out); +// Reports worker-process lifetime usage, not per-command CPU accounting. +// usage_available is zero when no process sample is available. +int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, int *usage_available); // These operations return 0 or POSITIVE errno, unlike poll. // Resize updates the worker command dimensions through ios_setWindowSize. @@ -39,6 +67,8 @@ int ashell_pane_interrupt(void *job); // The handle is opaque and is NOT an OS pid: never pass it to kill/waitpid/process APIs. void ashell_pane_release(void *job); +#pragma GCC visibility pop + #ifdef __cplusplus } #endif diff --git a/ShellWorkers/NativePane.m b/ShellWorkers/NativePane.m index 29db5b84..2cba8007 100644 --- a/ShellWorkers/NativePane.m +++ b/ShellWorkers/NativePane.m @@ -29,9 +29,13 @@ pthread_cond_t ready; unsigned refs; int initialized, startup_error, done, status, completion_error; + struct rusage usage; + int usage_available; int peer_control, input_closed, is_pty; unsigned char eof_key; FILE *streams[3]; + // Without a tty the session streams differ from the command streams, so stock isatty reports false. + FILE *session_in, *session_out, *session_err; void *registration; char key[64]; char *command, *cwd, *previous_cwd; @@ -48,7 +52,9 @@ // which can be a shell blocked in ios_waitpid rather than the running command. static _Atomic int foreground_command_pid; -__attribute__((used)) int ashell_pane_exchange_foreground_pid(int pid) { +__attribute__((used, visibility("default"))) int ashell_pane_exchange_foreground_pid(int pid) { + pane_job *job = atomic_load(&foreground_pane); + if (!job || ios_getContext() != job->key) return 0; return atomic_exchange(&foreground_command_pid, pid); } @@ -190,8 +196,18 @@ static int change_input(pane_input_relay *relay) { if (relay->command && (relay->command_eof || relay->input_eof) && !relay->command_queue.length) close_input_writer(&relay->command->writer); - if (relay->input_eof && !relay->editor_queue.length) - close_input_writer(&relay->editor_writer); + // A command lease can return typeahead, including bytes already in the + // editor pipe. Deliver EOF only after both places have drained. + int drain_editor = 0; + if (relay->input_eof && !relay->command && !relay->editor_queue.length && + relay->editor_writer >= 0) { + struct pollfd pending = {.fd = relay->editor_reader, .events = POLLIN}; + int available = poll(&pending, 1, 0); + if (available < 0 && errno != EINTR) { relay->error = errno; break; } + if (pending.revents & (POLLERR | POLLNVAL)) { relay->error = EIO; break; } + if (!available) close_input_writer(&relay->editor_writer); + else drain_editor = 1; + } // Backpressure bounds queued input. Each pipe also has its kernel // buffer; transition queues have room to drain that existing typeahead. int can_read = !relay->input_eof && relay->editor_queue.length < 61440 && @@ -204,7 +220,8 @@ static int change_input(pane_input_relay *relay) { .events = POLLOUT} }; pthread_mutex_unlock(&relay->mutex); - int result = poll(fds, 4, -1); + // Pipe readers do not wake this relay when they drain its final bytes. + int result = poll(fds, 4, drain_editor ? 100 : -1); int poll_error = errno; pthread_mutex_lock(&relay->mutex); if (result < 0) { @@ -260,6 +277,12 @@ static int request_input(pane_input_relay *relay, int request, command_input *co return error; } +static void baseline_streams(pane_job *job, FILE *input) { + ios_setStreams(job->session_in ? job->session_in : input, + job->session_out ? job->session_out : job->streams[1], + job->session_err ? job->session_err : job->streams[2]); +} + static int stop_input_relay(pane_job *job) { pane_input_relay *relay = job->input_relay; if (!relay) return 0; @@ -276,7 +299,7 @@ static int stop_input_relay(pane_job *job) { if (relay->command) { command_input *command = relay->command; ashell_wait_owned_streams(command->registration); - ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + baseline_streams(job, job->streams[0]); ios_settty(job->streams[0]); ashell_unregister_owned_streams(&command->registration); if (fclose(command->reader) && !error) error = errno; @@ -347,7 +370,7 @@ static int prepare_input_relay(pane_job *job) { // Wait on the editor's real input and resize event without changing process // signal handlers or inserting synthetic keys into the command stream. // Return 0 for an unrelated reader, 1 for input, 2 for resize, or -errno. -__attribute__((used)) int ashell_pane_wait_editor_input(FILE *input) { +__attribute__((used, visibility("default"))) int ashell_pane_wait_editor_input(FILE *input) { pane_job *job = atomic_load(&foreground_pane); if (!job || !job->input_relay || input != job->streams[0]) return 0; struct kevent event; @@ -360,7 +383,7 @@ static int prepare_input_relay(pane_job *job) { return event.filter == EVFILT_USER ? 2 : 1; } -__attribute__((used)) int ashell_pane_begin_foreground_input(FILE **input, void **token) { +__attribute__((used, visibility("default"))) int ashell_pane_begin_foreground_input(FILE **input, void **token) { if (!input || !token || *token) return EINVAL; pane_job *job = atomic_load(&foreground_pane); if (!job || !job->input_relay || *input != job->streams[0]) return 0; @@ -409,14 +432,14 @@ static int prepare_input_relay(pane_job *job) { *token = command; // Stock tty detection compares command streams against the session streams. // Keep baseline outputs so explicit redirects remain non-terminal streams. - ios_setStreams(command->reader, job->streams[1], job->streams[2]); + baseline_streams(job, command->reader); // Stock ios_opentty borrowers must receive this command's input as well. ios_settty(command->reader); pthread_setcancelstate(cancellation, NULL); return 0; } -__attribute__((used)) int ashell_pane_end_foreground_input(void *token) { +__attribute__((used, visibility("default"))) int ashell_pane_end_foreground_input(void *token) { command_input *command = token; if (!command) return EINVAL; int cancellation; @@ -427,7 +450,7 @@ static int prepare_input_relay(pane_job *job) { // Dash. Borrow counts include asynchronous children through their cleanup. ashell_wait_owned_streams(command->registration); pane_job *job = command->job; - ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + baseline_streams(job, job->streams[0]); ios_settty(job->streams[0]); int retired = request_input(command->relay, INPUT_RETIRE, command); if (!error) error = retired; @@ -467,6 +490,11 @@ static int close_streams(pane_job *job) { if (job->streams[i] && fclose(job->streams[i]) && !error) error = errno; job->streams[i] = NULL; } + FILE **session[3] = {&job->session_in, &job->session_out, &job->session_err}; + for (int i = 0; i < 3; i++) { + if (*session[i] && fclose(*session[i]) && !error) error = errno; + *session[i] = NULL; + } return error; } @@ -484,7 +512,7 @@ static int socket_options(int fd) { // This runner is new: no parent session or TLS streams are switched or overwritten. ios_switchSession(job->key); ios_setContext(job->key); - ios_setStreams(job->streams[0], job->streams[1], job->streams[2]); + baseline_streams(job, job->streams[0]); ios_settty(job->streams[0]); thread_stdin = job->streams[0]; thread_stdout = job->streams[1]; @@ -509,6 +537,14 @@ static int socket_options(int fd) { if (ios_setenv_pid(job->env[i], equals + 1, 1, pid)) error = EINVAL; *equals = '='; } +#ifndef ASHELL_HOST_PANE + // Identify this worker's root by its reserved command PID. Setup + // calls cannot consume it, and nested children have different PIDs. + char root_pid[32]; + snprintf(root_pid, sizeof(root_pid), "%d", pid); + if (ios_setenv_pid("ASHELL_WORKER_ROOT_PID", root_pid, 1, pid)) error = EINVAL; + if (setenv("ASHELL_WORKER_ROOT_PID", root_pid, 1)) error = errno; +#endif pthread_mutex_lock(&job->mutex); job->initialized = 1; pthread_cond_signal(&job->ready); @@ -543,6 +579,7 @@ static int socket_options(int fd) { job->startup_error = job->initialized ? 0 : error; job->completion_error = error; job->initialized = 1; + job->usage_available = getrusage(RUSAGE_SELF, &job->usage) == 0; job->done = 1; NSLog(@"Shell pane lifecycle: exit key=%s status=%d error=%d", job->key, job->status, error); // Close the retained peer before announcing exit so output EOF is observable. @@ -558,8 +595,18 @@ static int socket_options(int fd) { int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { + ashell_pane_options options = {.size = sizeof(options), .tty = 1}; + return ashell_pane_spawn_ex(command, cwd, cols, rows, envp, &options, fd_out, job_out); +} + +int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, + const char *const *envp, ashell_pane_options *options, + int *fd_out, void **job_out) { if (fd_out) *fd_out = -1; if (job_out) *job_out = NULL; + if (!options || options->size < sizeof(*options)) return EINVAL; + options->stderr_fd = -1; + int peer_err = -1, err_child = -1; if (!fd_out || !job_out || !command || !*command || !cwd || cwd[0] != '/' || !cols || cols > 9999 || !rows || rows > 9999) return EINVAL; @autoreleasepool { @@ -593,7 +640,7 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, job->refs = 1; job->cols = cols; job->rows = rows; - snprintf(job->key, sizeof(job->key), "shell-pane-%s", NSUUID.UUID.UUIDString.UTF8String); + snprintf(job->key, sizeof(job->key), "ashell-pane-%s", NSUUID.UUID.UUIDString.UTF8String); job->command = strdup(command); job->cwd = strdup(cwd); job->previous_cwd = getcwd(NULL, 0); @@ -647,8 +694,18 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, error = job->is_pty ? (fcntl(job->peer_control, F_SETFD, FD_CLOEXEC) ? errno : 0) : socket_options(job->peer_control); if (!error && job->is_pty && fcntl(peer, F_SETFD, FD_CLOEXEC)) error = errno; if (error) { close(child); goto failed; } + if (options->separate_stderr) { + int pair[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair)) { error = errno; close(child); goto failed; } + peer_err = pair[0]; + err_child = pair[1]; + error = socket_options(peer_err); + if (!error) error = socket_options(err_child); + if (error) { close(child); goto failed; } + } for (int i = 0; i < 3; i++) { - int fd = i == 0 ? child : dup(child); + int fd = i == 0 ? child : i == 2 && err_child >= 0 ? err_child : dup(child); + if (i == 2 && fd == err_child) err_child = -1; if (fd < 0) { error = errno; goto failed; } job->streams[i] = fdopen(fd, i == 0 ? "r" : "w"); if (!job->streams[i]) { error = errno; close(fd); goto failed; } @@ -657,6 +714,12 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, int buffering = !job->is_pty && i == 1 ? _IOLBF : _IONBF; if (setvbuf(job->streams[i], NULL, buffering, 0)) { error = EIO; goto failed; } } + if (!options->tty) { + job->session_in = fopen("/dev/null", "r"); + job->session_out = fopen("/dev/null", "w"); + job->session_err = fopen("/dev/null", "w"); + if (!job->session_in || !job->session_out || !job->session_err) { error = errno; goto failed; } + } if (!job->is_pty) error = prepare_input_relay(job); if (!error) error = ashell_register_owned_streams(job->streams[0], job->streams[1], job->streams[2], &job->registration); if (error) goto failed; @@ -673,13 +736,16 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, while (!job->initialized) pthread_cond_wait(&job->ready, &job->mutex); error = job->startup_error; pthread_mutex_unlock(&job->mutex); - if (error) { close(peer); drop_reference(job); return error; } + if (error) { close(peer); if (peer_err >= 0) close(peer_err); drop_reference(job); return error; } *fd_out = peer; + options->stderr_fd = peer_err; *job_out = job; return 0; failed: close_streams(job); + if (err_child >= 0) close(err_child); if (peer >= 0) close(peer); + if (peer_err >= 0) close(peer_err); drop_reference(job); atomic_store(&pane_in_flight, 0); return error; @@ -687,11 +753,20 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, } int ashell_pane_poll(void *handle, int *status_out) { + return ashell_pane_poll_usage(handle, status_out, NULL, NULL); +} + +int ashell_pane_poll_usage(void *handle, int *status_out, struct rusage *usage_out, int *usage_available) { + if (usage_available) *usage_available = 0; if (!handle || !status_out) return -EINVAL; pane_job *job = handle; pthread_mutex_lock(&job->mutex); int result = job->completion_error ? -job->completion_error : job->done; - if (job->done) *status_out = job->status; + if (job->done) { + *status_out = job->status; + if (usage_out && job->usage_available) *usage_out = job->usage; + if (usage_available) *usage_available = job->usage_available; + } pthread_mutex_unlock(&job->mutex); return result; } diff --git a/ShellWorkers/PaneWire.h b/ShellWorkers/PaneWire.h index a1b80a9c..6f80d089 100644 --- a/ShellWorkers/PaneWire.h +++ b/ShellWorkers/PaneWire.h @@ -2,8 +2,9 @@ // One connection owns one real process and one existing native pane handle. @protocol AShellPaneWire -- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int, NSFileHandle *, int))reply; +- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separateStderr reply:(void (^)(int, NSFileHandle *, NSFileHandle *, int))reply; - (void)poll:(void (^)(int, int))reply; +- (void)pollUsage:(void (^)(int, int, NSData *))reply; - (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply; - (void)closeInput:(void (^)(int))reply; - (void)interrupt:(void (^)(int))reply; @@ -13,3 +14,18 @@ @end NSObject *ashell_worker_service(void); + +// A worker asks its owning host to allocate another isolated process. +@protocol AShellSpawnBrokerWire +- (void)bookmarkedDirectory:(NSString * _Nonnull)path reply:(void (^ _Nonnull)(NSString * _Nonnull))reply; +- (void)spawnChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply; +- (void)pollChild:(NSString *)token reply:(void (^)(int, int))reply; +- (void)closeChildInput:(NSString *)token reply:(void (^)(int))reply; +- (void)cancelChild:(NSString *)token reply:(void (^)(int))reply; +- (void)pollChildUsage:(NSString *)token reply:(void (^)(int, int, NSData *))reply; +- (void)resizeChild:(NSString *)token cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply; +- (void)interruptChild:(NSString *)token reply:(void (^)(int))reply; +- (void)releaseChild:(NSString *)token; +@end + +NSObject * _Nonnull ashell_spawn_broker(void); diff --git a/ShellWorkers/RemotePane.m b/ShellWorkers/RemotePane.m index 09929eb1..cdb086ee 100644 --- a/ShellWorkers/RemotePane.m +++ b/ShellWorkers/RemotePane.m @@ -1,13 +1,17 @@ #import "PaneWire.h" +#import #include "NativePane.h" #include #include #include +#include #include #include -extern void ashell_extension_connect(void (^)(NSXPCConnection *, NSError *)); +extern void ashell_extension_connect(const char *, void (^)(NSXPCConnection *, NSError *)); extern void ashell_extension_disconnect(NSXPCConnection *); +extern void ashell_extension_observe(NSXPCConnection *, pid_t); + static void log_host_library(const char *phase) { int saved = errno; @@ -22,12 +26,17 @@ static void log_host_library(const char *phase) { @interface RemotePane : NSObject @property(nonatomic, strong) NSXPCConnection *connection; @property(nonatomic, strong) id proxy; +@property(nonatomic, strong) NSFileHandle *output; +@property(nonatomic, strong) NSFileHandle *errorOutput; @property(atomic) BOOL interrupted; +@property(atomic) BOOL cancelled; @property(nonatomic, strong) NSMutableArray *directories; @property(nonatomic, copy) NSString *probeDirectory; @end @implementation RemotePane - (void)dealloc { + [_output closeAndReturnError:NULL]; + [_errorOutput closeAndReturnError:NULL]; // Only remove our empty disposable directory, never a project tree. if (_probeDirectory) rmdir(_probeDirectory.fileSystemRepresentation); log_host_library("before_scope_release"); @@ -39,9 +48,89 @@ - (void)dealloc { } @end +// A connection owns its descendants; invalidation releases the whole subtree. +@interface BrokerChild : NSObject +@property(nonatomic) void *job; +@end +@implementation BrokerChild +- (void)dealloc { if (_job) ashell_pane_release(_job); } +@end + +@interface SpawnBroker : NSObject +@property(nonatomic, strong) NSMutableDictionary *children; +@end +@implementation SpawnBroker +- (void)bookmarkedDirectory:(NSString *)path reply:(void (^)(NSString *))reply { reply(@(ios_getBookmarkedVersion(path.UTF8String))); } +- (instancetype)init { + if ((self = [super init])) _children = [NSMutableDictionary new]; + return self; +} +- (void)spawnChild:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply { + [self spawn:command cwd:cwd env:env cols:cols rows:rows tty:tty separateStderr:separate reply:reply]; +} +- (void)spawn:(NSString *)command cwd:(NSString *)cwd env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separate reply:(void (^)(int, NSString *, NSFileHandle *, NSFileHandle *))reply { + const char **values = calloc(env.count + 2, sizeof(*values)); + if (!values) { reply(ENOMEM, nil, nil, nil); return; } + NSUInteger count = 0; + for (NSString *value in env) { + values[count++] = value.UTF8String; + } + int fd = -1; + BrokerChild *child = [BrokerChild new]; + ashell_pane_options options = { .size = sizeof(options), .tty = tty, .separate_stderr = separate }; + void *job = NULL; + int error = ashell_pane_spawn_ex(command.UTF8String, cwd.fileSystemRepresentation, cols, rows, values, &options, &fd, &job); + free(values); + if (error) { reply(error, nil, nil, nil); return; } + child.job = job; + NSString *token = NSUUID.UUID.UUIDString; + @synchronized (self) { self.children[token] = child; } + NSFileHandle *output = [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES]; + NSFileHandle *errors = options.stderr_fd >= 0 ? [[NSFileHandle alloc] initWithFileDescriptor:options.stderr_fd closeOnDealloc:YES] : nil; + reply(0, token, output, errors); +} +- (BrokerChild *)child:(NSString *)token { @synchronized (self) { return self.children[token]; } } +- (void)pollChild:(NSString *)token reply:(void (^)(int, int))reply { + [self pollChildUsage:token reply:^(int result, int status, NSData *usage) { reply(result, status); }]; +} +- (void)pollChildUsage:(NSString *)token reply:(void (^)(int, int, NSData *))reply { + BrokerChild *child = [self child:token]; + int status = 0; + int available = 0; + struct rusage usage; + int result = child ? ashell_pane_poll_usage(child.job, &status, &usage, &available) : -ESRCH; + reply(result, status, result == 1 && available ? [NSData dataWithBytes:&usage length:sizeof(usage)] : nil); +} +- (void)closeChildInput:(NSString *)token reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? ashell_pane_close_stdin(child.job) : ESRCH); +} +- (void)cancelChild:(NSString *)token reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? ashell_pane_cancel(child.job) : ESRCH); +} +- (void)resizeChild:(NSString *)token cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? ashell_pane_resize(child.job, cols, rows) : ESRCH); +} +- (void)interruptChild:(NSString *)token reply:(void (^)(int))reply { + BrokerChild *child = [self child:token]; + reply(child ? ashell_pane_interrupt(child.job) : ESRCH); +} +- (void)releaseChild:(NSString *)token { @synchronized (self) { [self.children removeObjectForKey:token]; } } +@end + + + int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, int *fd_out, void **job_out) { + ashell_pane_options options = {.size = sizeof(options), .tty = 1}; + return ashell_pane_spawn_ex(command, cwd, cols, rows, envp, &options, fd_out, job_out); +} +int ashell_pane_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { if (fd_out) *fd_out = -1; if (job_out) *job_out = NULL; + if (!options || options->size < sizeof(*options)) return EINVAL; + options->stderr_fd = -1; if (!command || !cwd || !fd_out || !job_out || !cols || !rows) return EINVAL; if (NSThread.isMainThread) return EDEADLK; @autoreleasepool { @@ -81,7 +170,7 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsig } // A real create/read/unlink in this host-owned disposable directory proves // the worker capability; bookmark resolution or access(W_OK) alone does not. - NSString *template = [documentsURL.path stringByAppendingPathComponent:@".ashell-worker-access.XXXXXX"]; + NSString *template = [documentsURL.path stringByAppendingPathComponent:@".ashell-pane-access.XXXXXX"]; char *probe = strdup(template.fileSystemRepresentation); if (!probe) return ENOMEM; if (!mkdtemp(probe)) { int code = errno; free(probe); return code; } @@ -90,7 +179,10 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsig NSTimeInterval started = NSProcessInfo.processInfo.systemUptime; dispatch_semaphore_t ready = dispatch_semaphore_create(0); __block int error = 0; - ashell_extension_connect(^(NSXPCConnection *connection, NSError *failure) { + const char *requiredGroup = NULL; + for (size_t i = 0; envp && envp[i]; i++) + if (!strncmp(envp[i], "ASHELL_REQUIRED_APP_GROUP=", 26)) requiredGroup = envp[i] + 26; + ashell_extension_connect(requiredGroup, ^(NSXPCConnection *connection, NSError *failure) { pane.connection = connection; // ExtensionFoundation and Cocoa error numbers are not POSIX errno. // In particular, framework code 1 must not masquerade as EPERM. @@ -102,39 +194,79 @@ int ashell_pane_spawn(const char *command, const char *cwd, unsigned cols, unsig if (error) return error; __weak RemotePane *weak = pane; pane.connection.interruptionHandler = ^{ weak.interrupted = YES; }; - pane.connection.invalidationHandler = ^{ weak.interrupted = YES; }; + NSXPCConnection *connection = pane.connection; + connection.invalidationHandler = ^{ + weak.interrupted = YES; + // Invalidation clears this handler, but retains exportedObject. + connection.exportedObject = nil; + }; pane.connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(AShellPaneWire)]; [pane.connection resume]; pane.proxy = [pane.connection synchronousRemoteObjectProxyWithErrorHandler:^(NSError *failure) { error = EPIPE; }]; NSMutableArray *env = [NSMutableArray array]; for (size_t i = 0; envp && envp[i]; i++) [env addObject:@(envp[i])]; - __block int fd = -1; - [pane.proxy spawn:@(command) cwd:cwdBookmark home:homeBookmark documents:documentsBookmark probe:pane.probeDirectory env:env cols:cols rows:rows reply:^(int code, NSFileHandle *handle, int pid) { + __block int fd = -1, err_fd = -1; + BOOL separate = options->separate_stderr != 0; + [pane.proxy spawn:@(command) cwd:cwdBookmark home:homeBookmark documents:documentsBookmark probe:pane.probeDirectory env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:separate reply:^(int code, NSFileHandle *handle, NSFileHandle *errorHandle, int pid) { + ashell_extension_observe(pane.connection, pid); error = code; - if (!code && !handle) error = EPROTO; + if (!code && (!handle || (separate && !errorHandle))) error = EPROTO; if (!error) { fd = dup(handle.fileDescriptor); if (fd < 0) error = errno; else if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { error = errno; close(fd); fd = -1; } + else pane.output = handle; + } + if (!error && separate) { + err_fd = dup(errorHandle.fileDescriptor); + if (err_fd < 0) error = errno; + else if (fcntl(err_fd, F_SETFD, FD_CLOEXEC)) { error = errno; close(err_fd); err_fd = -1; } + else pane.errorOutput = errorHandle; + if (error && fd >= 0) { close(fd); fd = -1; } } NSLog(@"Shell extension spawn: real_pid=%d error=%d startup_ms=%.3f", pid, error, (NSProcessInfo.processInfo.systemUptime - started) * 1000); }]; if (rmdir(pane.probeDirectory.fileSystemRepresentation) == 0) pane.probeDirectory = nil; if (!error && fd < 0) error = EPROTO; - if (error) { ashell_extension_disconnect(pane.connection); return error; } + if (error) { + int spawnError = error; + [pane.proxy terminate:^{}]; + ashell_extension_disconnect(pane.connection); + return spawnError; + } *fd_out = fd; + options->stderr_fd = err_fd; *job_out = (__bridge_retained void *)pane; return 0; } } int ashell_pane_poll(void *job, int *status_out) { + return ashell_pane_poll_usage(job, status_out, NULL, NULL); +} +int ashell_pane_poll_usage(void *job, int *status_out, struct rusage *usage_out, int *usage_available) { + if (usage_available) *usage_available = 0; RemotePane *pane = (__bridge RemotePane *)job; if (!pane || !status_out) return -EINVAL; - // 137 is this backend's lost-worker status, not a recovered waitpid status. - if (pane.interrupted) { *status_out = 137; return 1; } + if (pane.cancelled) { *status_out = 137; return 1; } + if (pane.interrupted) return -EPIPE; + // The worker closes its socket streams before publishing completion. A + // hangup is observable even with unread output; keep polling local until + // then instead of waking the worker with an XPC request on every poll. + struct pollfd output = {.fd = pane.output.fileDescriptor, .events = POLLIN}; + int ready = poll(&output, 1, 0); + if (ready < 0) return errno == EINTR ? 0 : -errno; + if (output.revents & POLLNVAL) return -EBADF; + if (!(output.revents & (POLLHUP | POLLERR))) return 0; __block int result = -EPIPE; - [pane.proxy poll:^(int value, int status) { result = value; *status_out = status; }]; - if (result == -EPIPE) { pane.interrupted = YES; *status_out = 137; return 1; } + [pane.proxy pollUsage:^(int value, int status, NSData *usage) { + result = value; + if (value == 1) *status_out = status; + if (value == 1 && usage.length == sizeof(struct rusage)) { + if (usage_out) memcpy(usage_out, usage.bytes, sizeof(struct rusage)); + if (usage_available) *usage_available = 1; + } + }]; + if (result == -EPIPE) pane.interrupted = YES; return result; } int ashell_pane_resize(void *job, unsigned cols, unsigned rows) { @@ -161,6 +293,7 @@ int ashell_pane_interrupt(void *job) { int ashell_pane_cancel(void *job) { RemotePane *pane = (__bridge RemotePane *)job; if (!pane) return EINVAL; + pane.cancelled = YES; pane.interrupted = YES; [pane.proxy terminate:^{}]; ashell_extension_disconnect(pane.connection); @@ -173,3 +306,7 @@ void ashell_pane_release(void *job) { [pane.proxy terminate:^{}]; ashell_extension_disconnect(pane.connection); } + +NSObject *ashell_spawn_broker(void) { + return [SpawnBroker new]; +} diff --git a/ShellWorkers/Worker.entitlements b/ShellWorkers/Worker.entitlements new file mode 100644 index 00000000..7c209182 --- /dev/null +++ b/ShellWorkers/Worker.entitlements @@ -0,0 +1,6 @@ + + + +com.apple.security.application-groups +group.$(APP_GROUP_PREFIX:default=AsheKube).a-Shell + diff --git a/ShellWorkers/Worker.m b/ShellWorkers/Worker.m index e215311c..38a0dca1 100644 --- a/ShellWorkers/Worker.m +++ b/ShellWorkers/Worker.m @@ -8,21 +8,31 @@ #include #include #include +#undef kill +#include // ios_system discovers these stock host callbacks with dlsym. Each extension // owns one shell; its socket already carries input directly to the command. static atomic_bool interactive_input; -__attribute__((used)) void startInteractive(void) { atomic_store(&interactive_input, true); } -__attribute__((used)) void stopInteractive(void) { atomic_store(&interactive_input, false); } -__attribute__((used)) int storeInteractive(void) { return atomic_load(&interactive_input); } +__attribute__((used, visibility("default"))) void startInteractive(void) { atomic_store(&interactive_input, true); } +__attribute__((used, visibility("default"))) void stopInteractive(void) { atomic_store(&interactive_input, false); } +__attribute__((used, visibility("default"))) int storeInteractive(void) { return atomic_load(&interactive_input); } // The stock host clear command calls its UIKit delegate. Workers clear through // the terminal stream, just like an external terminal command. -__attribute__((used)) int clear(int argc, char **argv) { +__attribute__((used, visibility("default"))) int clear(int argc, char **argv) { if (!thread_stdout) return 1; return fputs("\033[H\033[2J", thread_stdout) == EOF || fflush(thread_stdout) == EOF ? 1 : 0; } +// Query the extension's real entitlement through Foundation. The containing +// app's existing metadata names the shared container; no path is manufactured. +__attribute__((used, visibility("default"))) int ashell_worker_has_shared_container(void) { + NSBundle *app = [NSBundle bundleWithURL:NSBundle.mainBundle.bundleURL.URLByDeletingLastPathComponent.URLByDeletingLastPathComponent]; + NSString *group = [app objectForInfoDictionaryKey:@"AppGroupIdentifier"]; + return group.length && [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:group] != nil; +} + static int check_directory(NSURL *url) { DIR *directory = opendir(url.fileSystemRepresentation); if (!directory) return errno; @@ -32,7 +42,7 @@ static int check_directory(NSURL *url) { static int check_documents_write(NSURL *documents, NSString *probe) { NSString *parent = probe.stringByDeletingLastPathComponent.stringByResolvingSymlinksInPath; if (![parent isEqualToString:documents.path.stringByResolvingSymlinksInPath] || - ![probe.lastPathComponent hasPrefix:@".ashell-worker-access."]) return EINVAL; + ![probe.lastPathComponent hasPrefix:@".ashell-pane-access."]) return EINVAL; int directory = open(probe.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (directory < 0) return errno; int fd = openat(directory, "capability", O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); @@ -50,6 +60,122 @@ static int check_documents_write(NSURL *documents, NSString *probe) { return code; } +static id spawnBroker; + +// The host owns bookmark names; return a copy for the prompt renderer to free. +__attribute__((used, visibility("default"))) char *ashell_bookmarked_directory(const char *path) { + if (!spawnBroker || !path) return NULL; + __block NSString *display = nil; + [spawnBroker bookmarkedDirectory:@(path) reply:^(NSString *value) { display = value; }]; + return display ? strdup(display.UTF8String) : NULL; +} +@interface BrokerRemoteChild : NSObject +@property(nonatomic, strong) id broker; +@property(nonatomic, copy) NSString *token; +@property(nonatomic, strong) NSFileHandle *output; +@property(nonatomic, strong) NSFileHandle *errors; +@end +@implementation BrokerRemoteChild +- (void)dealloc { if (_token) [_broker releaseChild:_token]; } +@end + +static int broker_spawn( const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { + if (fd_out) *fd_out = -1; + if (job_out) *job_out = NULL; + if (!options || options->size < sizeof(*options)) return EINVAL; + options->stderr_fd = -1; + if (!command || !*command || !cwd || cwd[0] != '/' || !cols || cols > 9999 || !rows || rows > 9999 || !fd_out || !job_out) return EINVAL; + if (!spawnBroker) return ENOTSUP; + NSMutableArray *env = [NSMutableArray new]; + for (size_t i = 0; envp && envp[i]; i++) [env addObject:@(envp[i])]; + BrokerRemoteChild *child = [BrokerRemoteChild new]; + child.broker = spawnBroker; + __block int error = EPIPE; + void (^reply)(int, NSString *, NSFileHandle *, NSFileHandle *) = ^(int code, NSString *token, NSFileHandle *output, NSFileHandle *errors) { + error = code; + if (error) return; + child.token = token; + child.output = output; + child.errors = errors; + if (!token || !output || (options->separate_stderr && !errors)) { error = EPROTO; return; } + *fd_out = dup(output.fileDescriptor); + if (*fd_out < 0) { error = errno; return; } + if (fcntl(*fd_out, F_SETFD, FD_CLOEXEC)) { error = errno; close(*fd_out); *fd_out = -1; return; } + if (errors) { + options->stderr_fd = dup(errors.fileDescriptor); + if (options->stderr_fd < 0) error = errno; + else if (fcntl(options->stderr_fd, F_SETFD, FD_CLOEXEC)) { + error = errno; + close(options->stderr_fd); + options->stderr_fd = -1; + } + if (error) { close(*fd_out); *fd_out = -1; } + } + }; + [child.broker spawnChild:@(command) cwd:@(cwd) env:env cols:cols rows:rows tty:options->tty != 0 separateStderr:options->separate_stderr != 0 reply:reply]; + if (error) return error; + *job_out = (__bridge_retained void *)child; + return 0; +} +__attribute__((used, visibility("default"))) int ashell_worker_spawn_ex(const char *command, const char *cwd, unsigned cols, unsigned rows, const char *const *envp, ashell_pane_options *options, int *fd_out, void **job_out) { + return broker_spawn( command, cwd, cols, rows, envp, options, fd_out, job_out); +} +__attribute__((used, visibility("default"))) int ashell_worker_poll_usage(void *handle, int *status, struct rusage *usage_out, int *usage_available) { + if (usage_available) *usage_available = 0; + if (!handle || !status) return -EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)handle; + struct pollfd fd = { child.output.fileDescriptor, POLLIN, 0 }; + if (poll(&fd, 1, 0) < 0) return errno == EINTR ? 0 : -errno; + if (fd.revents & POLLNVAL) return -EBADF; + if (!(fd.revents & (POLLHUP | POLLERR))) return 0; + __block int result = -EPIPE; + [child.broker pollChildUsage:child.token reply:^(int value, int code, NSData *usage) { + result = value; + if (value == 1) *status = code; + if (value == 1 && usage.length == sizeof(struct rusage)) { + if (usage_out) memcpy(usage_out, usage.bytes, sizeof(struct rusage)); + if (usage_available) *usage_available = 1; + } + }]; + return result; +} +__attribute__((used, visibility("default"))) int ashell_worker_poll(void *handle, int *status) { + return ashell_worker_poll_usage(handle, status, NULL, NULL); +} +__attribute__((used, visibility("default"))) int ashell_worker_close_stdin(void *handle) { + if (!handle) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)handle; + __block int result = EPIPE; + [child.broker closeChildInput:child.token reply:^(int code) { result = code; }]; + return result; +} +__attribute__((used, visibility("default"))) int ashell_worker_cancel(void *handle) { + if (!handle) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)handle; + __block int result = EPIPE; + [child.broker cancelChild:child.token reply:^(int code) { result = code; }]; + return result; +} +__attribute__((used, visibility("default"))) void ashell_worker_release(void *handle) { + BrokerRemoteChild *child = (__bridge_transfer BrokerRemoteChild *)handle; + (void)child; +} + +__attribute__((used, visibility("default"))) int ashell_worker_resize(void *job, unsigned cols, unsigned rows) { + if (!job) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)job; + __block int result = EPIPE; + [child.broker resizeChild:child.token cols:cols rows:rows reply:^(int code) { result = code; }]; + return result; +} +__attribute__((used, visibility("default"))) int ashell_worker_interrupt(void *job) { + if (!job) return EINVAL; + BrokerRemoteChild *child = (__bridge BrokerRemoteChild *)job; + __block int result = EPIPE; + [child.broker interruptChild:child.token reply:^(int code) { result = code; }]; + return result; +} + @interface PaneService : NSObject @end @@ -57,9 +183,14 @@ @implementation PaneService { void *_pane; NSMutableArray *_directories; } -- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int, NSFileHandle *, int))reply { - if (_pane) { reply(EBUSY, nil, getpid()); return; } - if (!cwd || !home || !documents || !probe) { reply(EINVAL, nil, getpid()); return; } +- (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home documents:(NSData *)documents probe:(NSString *)probe env:(NSArray *)env cols:(unsigned)cols rows:(unsigned)rows tty:(BOOL)tty separateStderr:(BOOL)separateStderr reply:(void (^)(int, NSFileHandle *, NSFileHandle *, int))reply { + if (_pane) { reply(EBUSY, nil, nil, getpid()); return; } + NSXPCConnection *connection = NSXPCConnection.currentConnection; + connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(AShellSpawnBrokerWire)]; + spawnBroker = [connection synchronousRemoteObjectProxyWithErrorHandler:^(NSError *failure) { + NSLog(@"Shell worker spawn broker disconnected: %@", failure); + }]; + if (!cwd || !home || !documents || !probe) { reply(EINVAL, nil, nil, getpid()); return; } // Resolve the host's ephemeral grants explicitly and retain them for this // pane, including HOME for shared command configuration and authentication. _directories = [NSMutableArray array]; @@ -77,7 +208,7 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document if (!url) { NSLog(@"Shell worker directory bookmark failed: %@", failure); [self releasePane]; - reply([failure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)failure.code : EIO, nil, getpid()); + reply([failure.domain isEqualToString:NSPOSIXErrorDomain] ? (int)failure.code : EIO, nil, nil, getpid()); return; } BOOL scoped = [url startAccessingSecurityScopedResource]; @@ -94,20 +225,32 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document NSLog(@"Shell worker directory capability: url=%@ read_error=%d", url.path, code); if (code && !readError) readError = code; } - if (readError) { [self releasePane]; reply(readError, nil, getpid()); return; } + if (readError) { [self releasePane]; reply(readError, nil, nil, getpid()); return; } int capabilityError = check_documents_write(documentsURL, probe); NSLog(@"Shell worker Documents capability: real_pid=%d read_write_error=%d", getpid(), capabilityError); - if (capabilityError) { [self releasePane]; reply(capabilityError, nil, getpid()); return; } + if (capabilityError) { [self releasePane]; reply(capabilityError, nil, nil, getpid()); return; } // ios_system globals are private to this extension. The adapter keeps its // original dedicated pthread and stream ownership/cleanup barrier. NSString *temporaryDirectory = NSTemporaryDirectory(); - if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, getpid()); return; } + if (!temporaryDirectory.length) { [self releasePane]; reply(EIO, nil, nil, getpid()); return; } // The host's directory bookmark does not grant its tmp directory. Keep the // extension's stock Foundation/libc temp domain in both environment views. - NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 1]; + NSMutableArray *environment = [NSMutableArray arrayWithCapacity:env.count + 6]; for (NSString *value in env) - if (![value hasPrefix:@"TMPDIR="]) [environment addObject:value]; + if (![value hasPrefix:@"ASHELL_REQUIRED_APP_GROUP="] && ![value hasPrefix:@"TMPDIR="] && ![value hasPrefix:@"HOME="] && + ![value hasPrefix:@"ASHELL_WORKER_PID="] && ![value hasPrefix:@"ASHELL_WORKER_ROOT_PID="] && + ![value hasPrefix:@"ASHELL_IOS_PTY="] && ![value hasPrefix:@"LC_CTYPE="] && + ![value hasPrefix:@"ASHELL_IOS_SOCKET_INPUT="]) [environment addObject:value]; [environment addObject:[@"TMPDIR=" stringByAppendingString:temporaryDirectory]]; + // A home-root bookmark can resolve relative to the extension's own home. + // Documents retains the host path; nested spawns need that same host HOME. + [environment addObject:[@"HOME=" stringByAppendingString:documentsURL.URLByDeletingLastPathComponent.path]]; + // Dash imports libc environ when it initializes its own variable table. + [environment addObject:[NSString stringWithFormat:@"ASHELL_WORKER_PID=%d", getpid()]]; + // Use socket input on both SDKs; device workers cannot own a kernel PTY. + [environment addObject:@"ASHELL_IOS_PTY=0"]; + [environment addObject:@"LC_CTYPE=UTF-8"]; + [environment addObject:@"ASHELL_IOS_SOCKET_INPUT=1"]; env = environment; initializeEnvironment(); replaceCommand(@"clear", @"clear", true); @@ -115,38 +258,35 @@ - (void)spawn:(NSString *)command cwd:(NSData *)cwd home:(NSData *)home document // environment as well as ios_system's forked command environment. for (NSString *value in env) { NSRange separator = [value rangeOfString:@"="]; - if (separator.location == NSNotFound || separator.location == 0) { [self releasePane]; reply(EINVAL, nil, getpid()); return; } + if (separator.location == NSNotFound || separator.location == 0) { [self releasePane]; reply(EINVAL, nil, nil, getpid()); return; } if (setenv([value substringToIndex:separator.location].UTF8String, - [value substringFromIndex:separator.location + 1].UTF8String, 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } + [value substringFromIndex:separator.location + 1].UTF8String, 1)) { int error = errno; [self releasePane]; reply(error, nil, nil, getpid()); return; } } // Match stock SceneDelegate before libedit decodes Unicode or measures it. - if (setenv("LC_CTYPE", "UTF-8", 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } const char *locale = setlocale(LC_CTYPE, "UTF-8"); - if (!locale) { [self releasePane]; reply(EINVAL, nil, getpid()); return; } + if (!locale) { [self releasePane]; reply(EINVAL, nil, nil, getpid()); return; } NSLog(@"Shell worker locale: real_pid=%d ctype=%s", getpid(), locale); - // The physical device has no kernel tty. Use the same socket-backed route - // on Simulator so its acceptance cannot pass through a desktop-only PTY. - if (setenv("ASHELL_IOS_PTY", "0", 1)) { int error = errno; [self releasePane]; reply(error, nil, getpid()); return; } - const char **values = calloc(env.count + 4, sizeof(char *)); - if (!values) { [self releasePane]; reply(ENOMEM, nil, getpid()); return; } - for (NSUInteger i = 0; i < env.count; i++) - values[i] = [env[i] hasPrefix:@"ASHELL_IOS_PTY="] ? "ASHELL_IOS_PTY=0" : - [env[i] hasPrefix:@"LC_CTYPE="] ? "LC_CTYPE=UTF-8" : env[i].UTF8String; - NSString *identity = [NSString stringWithFormat:@"ASHELL_WORKER_PID=%d", getpid()]; - values[env.count] = identity.UTF8String; - values[env.count + 1] = "LC_CTYPE=UTF-8"; - values[env.count + 2] = "ASHELL_IOS_SOCKET_INPUT=1"; + const char **values = calloc(env.count + 1, sizeof(char *)); + if (!values) { [self releasePane]; reply(ENOMEM, nil, nil, getpid()); return; } + for (NSUInteger i = 0; i < env.count; i++) values[i] = env[i].UTF8String; int fd = -1; - int error = ashell_pane_spawn(command.UTF8String, directory.path.UTF8String, cols, rows, values, &fd, &_pane); + ashell_pane_options options = {.size = sizeof(options), .tty = tty, .separate_stderr = separateStderr}; + int error = ashell_pane_spawn_ex(command.UTF8String, directory.path.UTF8String, cols, rows, values, &options, &fd, &_pane); free(values); if (error) [self releasePane]; NSFileHandle *handle = error ? nil : [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES]; - reply(error, handle, getpid()); + NSFileHandle *errorHandle = !error && options.stderr_fd >= 0 ? [[NSFileHandle alloc] initWithFileDescriptor:options.stderr_fd closeOnDealloc:YES] : nil; + reply(error, handle, errorHandle, getpid()); } - (void)poll:(void (^)(int, int))reply { + [self pollUsage:^(int result, int status, NSData *usage) { reply(result, status); }]; +} +- (void)pollUsage:(void (^)(int, int, NSData *))reply { int status = 0; - int result = _pane ? ashell_pane_poll(_pane, &status) : -ESRCH; - reply(result, status); + int available = 0; + struct rusage usage; + int result = _pane ? ashell_pane_poll_usage(_pane, &status, &usage, &available) : -ESRCH; + reply(result, status, result == 1 && available ? [NSData dataWithBytes:&usage length:sizeof(usage)] : nil); } - (void)resize:(unsigned)cols rows:(unsigned)rows reply:(void (^)(int))reply { reply(_pane ? ashell_pane_resize(_pane, cols, rows) : ESRCH); diff --git a/ShellWorkers/Worker.xcconfig b/ShellWorkers/Worker.xcconfig index fda0cec8..19a1a143 100644 --- a/ShellWorkers/Worker.xcconfig +++ b/ShellWorkers/Worker.xcconfig @@ -20,3 +20,5 @@ SKIP_INSTALL = YES CURRENT_PROJECT_VERSION = 589 MARKETING_VERSION = 2.2.3 CODE_SIGN_STYLE = Automatic + +CODE_SIGN_ENTITLEMENTS = ShellWorkers/Worker.entitlements diff --git a/a-Shell/a-Shell-Bridging-Header.h b/a-Shell/a-Shell-Bridging-Header.h index 0282b277..f05c41ff 100644 --- a/a-Shell/a-Shell-Bridging-Header.h +++ b/a-Shell/a-Shell-Bridging-Header.h @@ -3,3 +3,5 @@ // #import "KBWebViewBase.h" + +#import "../ShellWorkers/PaneWire.h" From 0c59f8dd0a405f6ca46b22cc78fae06646e0e6ee Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:31:50 +0300 Subject: [PATCH 15/16] Add worker-backed tmux 3.8 to the mini app --- Resources_mini/bin/tmux | 0 Resources_mini/bin/tmux-acceptance | 0 Resources_mini/bin/tmux-native | 0 Resources_mini/commandDictionary.plist | 21 + a-Shell.xcodeproj/project.pbxproj | 12 + createFakeCommands_mini.sh | 3 + tmux/.gitignore | 1 + tmux/NCURSES-LICENSE | 29 + tmux/README.md | 46 + tmux/acceptance.m | 195 ++++ tmux/build.sh | 92 ++ tmux/host.m | 304 +++++++ tmux/ios-boundary.h | 39 + tmux/ios-engine.c | 160 ++++ tmux/ios-engine.h | 19 + tmux/ios.patch | 1129 ++++++++++++++++++++++++ tmux/phone-check.sh | 51 ++ tmux/socket-check.sh | 94 ++ tmux/sources.sha256 | 2 + tmux/terminal.terminfo | 66 ++ 20 files changed, 2263 insertions(+) create mode 100755 Resources_mini/bin/tmux create mode 100755 Resources_mini/bin/tmux-acceptance create mode 100755 Resources_mini/bin/tmux-native create mode 100644 tmux/.gitignore create mode 100644 tmux/NCURSES-LICENSE create mode 100644 tmux/README.md create mode 100644 tmux/acceptance.m create mode 100755 tmux/build.sh create mode 100644 tmux/host.m create mode 100644 tmux/ios-boundary.h create mode 100644 tmux/ios-engine.c create mode 100644 tmux/ios-engine.h create mode 100644 tmux/ios.patch create mode 100755 tmux/phone-check.sh create mode 100755 tmux/socket-check.sh create mode 100644 tmux/sources.sha256 create mode 100644 tmux/terminal.terminfo diff --git a/Resources_mini/bin/tmux b/Resources_mini/bin/tmux new file mode 100755 index 00000000..e69de29b diff --git a/Resources_mini/bin/tmux-acceptance b/Resources_mini/bin/tmux-acceptance new file mode 100755 index 00000000..e69de29b diff --git a/Resources_mini/bin/tmux-native b/Resources_mini/bin/tmux-native new file mode 100755 index 00000000..e69de29b diff --git a/Resources_mini/commandDictionary.plist b/Resources_mini/commandDictionary.plist index 64dad81d..212b6a47 100644 --- a/Resources_mini/commandDictionary.plist +++ b/Resources_mini/commandDictionary.plist @@ -954,5 +954,26 @@ 2346aAbBcCdDeEfgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwxXYyz# file + tmux + + TmuxHost.framework/TmuxHost + tmux_main + + thread + + tmux-native + + TmuxNative.framework/TmuxNative + tmux_native_main + + thread + + tmux-acceptance + + TmuxAcceptance.framework/TmuxAcceptance + tmux_acceptance + + thread + diff --git a/a-Shell.xcodeproj/project.pbxproj b/a-Shell.xcodeproj/project.pbxproj index 66a3e0a9..f04aec23 100644 --- a/a-Shell.xcodeproj/project.pbxproj +++ b/a-Shell.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + E70200000000000000000003 /* TmuxNative.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = E70200000000000000000001 /* TmuxNative.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + E70200000000000000000006 /* TmuxHost.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = E70200000000000000000004 /* TmuxHost.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + E70200000000000000000009 /* TmuxAcceptance.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = E70200000000000000000007 /* TmuxAcceptance.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; A2B1818A0000000000000001 /* Herdr LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = A2B1818A0000000000000002 /* Herdr LICENSE */; }; 2203367A28C4B8070027664C /* pico.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 2232245E289695A9001BAE04 /* pico.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 22068CC62F51C11A004307F7 /* TerminalView+KeyCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22068CC52F51BFCE004307F7 /* TerminalView+KeyCommands.swift */; }; @@ -1378,6 +1381,9 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( + E70200000000000000000006 /* TmuxHost.xcframework in Embed Frameworks */, + E70200000000000000000009 /* TmuxAcceptance.xcframework in Embed Frameworks */, + E70200000000000000000003 /* TmuxNative.xcframework in Embed Frameworks */, 2269076E2F97BBD20071F551 /* curl-impersonate.framework in Embed Frameworks */, 22D1424B2E62091700E76E2E /* Python.framework in Embed Frameworks */, 22D1424C2E62091700E76E2E /* Python-_cffi_backend.framework in Embed Frameworks */, @@ -2197,6 +2203,9 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + E70200000000000000000001 /* TmuxNative.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = "tmux/build/TmuxNative.xcframework"; sourceTree = SOURCE_ROOT; }; + E70200000000000000000004 /* TmuxHost.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = "tmux/build/TmuxHost.xcframework"; sourceTree = SOURCE_ROOT; }; + E70200000000000000000007 /* TmuxAcceptance.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = "tmux/build/TmuxAcceptance.xcframework"; sourceTree = SOURCE_ROOT; }; A2B1818A0000000000000002 /* Herdr LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; name = "Herdr LICENSE"; path = Herdr/LICENSE; sourceTree = SOURCE_ROOT; }; 22068CC52F51BFCE004307F7 /* TerminalView+KeyCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TerminalView+KeyCommands.swift"; sourceTree = ""; }; 2208ACBE22CCE57E003985D6 /* String+C.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "String+C.swift"; path = "Util/String+C.swift"; sourceTree = SOURCE_ROOT; }; @@ -3370,6 +3379,9 @@ 22984EE122C93DBC00069497 = { isa = PBXGroup; children = ( + E70200000000000000000004 /* TmuxHost.xcframework */, + E70200000000000000000007 /* TmuxAcceptance.xcframework */, + E70200000000000000000001 /* TmuxNative.xcframework */, A2B1818A0000000000000002 /* Herdr LICENSE */, 220F36512BC458C800842FEE /* PrivacyInfo.xcprivacy */, 223FC3CA2611F9C300CDC89F /* wasm.html */, diff --git a/createFakeCommands_mini.sh b/createFakeCommands_mini.sh index 0c7834b1..1ac90f86 100644 --- a/createFakeCommands_mini.sh +++ b/createFakeCommands_mini.sh @@ -101,3 +101,6 @@ touch Resources_mini/bin/mogrify touch Resources_mini/bin/montage touch Resources_mini/bin/stream +touch Resources_mini/bin/tmux +touch Resources_mini/bin/tmux-native +touch Resources_mini/bin/tmux-acceptance diff --git a/tmux/.gitignore b/tmux/.gitignore new file mode 100644 index 00000000..84c048a7 --- /dev/null +++ b/tmux/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/tmux/NCURSES-LICENSE b/tmux/NCURSES-LICENSE new file mode 100644 index 00000000..6182a3bc --- /dev/null +++ b/tmux/NCURSES-LICENSE @@ -0,0 +1,29 @@ +Copyright 2018-2024,2025 Thomas E. Dickey +Copyright 1998-2017,2018 Free Software Foundation, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, distribute with modifications, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name(s) of the above copyright +holders shall not be used in advertising or otherwise to promote the +sale, use or other dealings in this Software without prior written +authorization. + +-- vile:txtmode fc=72 +-- $Id: COPYING,v 1.14 2025/01/04 10:53:46 tom Exp $ diff --git a/tmux/README.md b/tmux/README.md new file mode 100644 index 00000000..20edccdc --- /dev/null +++ b/tmux/README.md @@ -0,0 +1,46 @@ +# tmux for a-Shell mini + +The native port keeps tmux 3.8's server, command parser, layouts, renderer and session state. Server and client engines run in isolated shell worker extensions. Pane commands use the nested worker broker and ios_system logical terminals. Resize messages carry logical terminal dimensions, so the bundled client and server use an iOS protocol variant. No kernel PTY or forked child is simulated. + +## Build + +This change follows the worker pool in a-shell#1089, the Herdr integration in a-shell#1090, and the nested-worker broker. It also requires the ios_system worker execution, targeted interruption, native lifecycle, worker ownership and command-environment snapshot changes, plus Dash socket input and foreground-input ownership support. + +Download [tmux 3.8](https://github.com/tmux/tmux/releases/download/3.8/tmux-3.8.tar.gz) and [libevent 2.1.13](https://github.com/libevent/libevent/releases/download/release-2.1.13-stable/libevent-2.1.13-stable.tar.gz) into `ARCHIVES`; their checksums are listed in `sources.sha256`. Supply the matching ios_system source headers and framework, and ncurses headers. Build each platform separately: + +```sh +bash tmux/build.sh iphoneos "$ARCHIVES" "$OUTPUT/iphoneos" "$IOS_SYSTEM_SOURCE" "$DEVICE_FRAMEWORKS" "$NCURSES_INCLUDE" +bash tmux/build.sh iphonesimulator "$ARCHIVES" "$OUTPUT/iphonesimulator" "$IOS_SYSTEM_SOURCE" "$SIMULATOR_FRAMEWORKS" "$NCURSES_INCLUDE" +``` + +The recipe verifies source checksums, applies the iOS boundary patch and builds static libevent with the native tmux framework. It produces `sdk/TmuxNative.framework`, `sdk/TmuxHost.framework` and the separate `sdk/TmuxAcceptance.framework`. Package both platform slices as XCFrameworks in `tmux/build` before building the mini app: + +```sh +for name in TmuxNative TmuxHost TmuxAcceptance; do + xcodebuild -create-xcframework -framework "$OUTPUT/iphoneos/sdk/$name.framework" -framework "$OUTPUT/iphonesimulator/sdk/$name.framework" -output "tmux/build/$name.xcframework" +done +``` + +The host framework carries its compiled terminal description. The default pane terminal is `screen.xterm-256color`, which the bundled Vim recognizes without additional flags. Socket pane output translates bare LF to CRLF before tmux parses it, retaining existing CRLF across read chunks and preserving redirected data. + +## Use and verification + +Run `tmux new -s t`. Split with `C-b %` and `C-b "`, detach with `C-b d`, and return with `tmux attach -t t`. The app retains the server independently of each client invocation. Start new servers from an app terminal; a command running inside a worker can attach to an existing server. + +`phone-check.sh` invokes the public `tmux` command through ios_system sessions. The mini app embeds and registers the acceptance command, which checks three panes, exact command/pipeline output, ordinary Vim with arrow keys and indexed colors, resize, detach/reattach, interruption and shutdown. It then repeats file/pipe/substitution/error cases 20 times. The `/dev/fd` glob is a diagnostic and is not an independent OS descriptor count. + +```sh +dash /absolute/path/to/phone-check.sh "$HOME/Documents/tmux-qualification-UNIQUE" +``` + +`socket-check.sh /absolute/unused/long-prefix` checks long sockets, stale-socket restart, command aliases and socket selection. The prefix must exceed 104 bytes and permit worker socket access. The labelled case uses a unique name in the App Group default directory; the unsuffixed cases use an owned `TMUX_TMPDIR`. Neither touches the user's default server. Successful completion removes its test files. + +Use an owned directory and exclusive access to the worker pool. Bound the invocation externally; a failed assertion can leave its test server alive. Expected markers are `TMUX_ACCEPTANCE_PASS` and `TMUX_PHONE_CHECK_PASS`. + +## Runtime boundaries + +The default Unix socket lives in the app's existing shared App Group. Host and engine workers require real membership; a bookmark granting file access to Documents does not grant Unix socket binding there. Explicit `-S` and `TMUX_TMPDIR` overrides need actual worker bind/connect permission. Long paths are handled by changing directory only for bind/connect and retaining the full path for discovery and cleanup. + +Each active server, client and pane consumes a worker slot. Other commands share that capacity. App or iOS termination loses sessions. Background jobs (`run-shell`, `if-shell`, `#(...)`), `pipe-pane`, popups, copy piping, daemonization, `-D`, `-CC`, kernel process introspection and arbitrary POSIX process/signals are unsupported. Some report errors; popup and copy-pipe operations can return without starting a job. Pane shells must already be registered in the app; this does not execute downloaded native binaries. + +The recipe copies the tmux and libevent licenses into the native framework and `NCURSES-LICENSE` beside the host framework's compiled terminal description. diff --git a/tmux/acceptance.m b/tmux/acceptance.m new file mode 100644 index 00000000..862f1d49 --- /dev/null +++ b/tmux/acceptance.m @@ -0,0 +1,195 @@ +// Register as tmux-acceptance in the app. Drive normal tmux commands through +// public ios_system sessions, with a socket standing in for terminal keystrokes. +#import +#import "ios_system/ios_system.h" +#include +#include +#include +#include + +@interface TmuxTerminal : NSObject +@property NSString *command; +@property NSString *key; +@property void *session_key; +@property void *registration; +@property int peer; +@property int command_fd; +@property int status; +@property BOOL done; +@property NSMutableData *output; +@end +@implementation TmuxTerminal +@end + +static void *run_terminal(void *cookie) { + TmuxTerminal *terminal = (__bridge_transfer TmuxTerminal *)cookie; + @autoreleasepool { + const void *key = terminal.session_key; + ios_switchSession(key); + ios_setContext(key); + FILE *input = fdopen(dup(terminal.command_fd), "r"); + FILE *output = fdopen(dup(terminal.command_fd), "w"); + FILE *error = fdopen(dup(terminal.command_fd), "w"); + void *registration = NULL; + terminal.status = ashell_register_owned_streams(input, output, error, ®istration); + if (!terminal.status) { + terminal.registration = registration; + ios_setStreams(input, output, error); + ios_settty(input); + ios_useNativeTTY(false); + thread_stdin = input; thread_stdout = output; thread_stderr = error; + ios_setWindowSize(95, 37, key); + pid_t pid = ios_fork(); + ios_system(terminal.command.UTF8String); + ios_waitpid(pid); + ashell_wait_owned_streams(registration); + terminal.status = ios_getCommandStatus(); + ios_releaseThreadId(pid); + ashell_unregister_owned_streams(®istration); + terminal.registration = NULL; + } + fclose(input); fclose(output); fclose(error); + close(terminal.command_fd); + ios_closeSession(key); + terminal.done = YES; + } + return NULL; +} + +static TmuxTerminal *start(NSString *command, pthread_t *thread) { + int pair[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair)) return nil; + TmuxTerminal *terminal = [TmuxTerminal new]; + terminal.command = command; + terminal.key = NSUUID.UUID.UUIDString; + terminal.session_key = strdup(terminal.key.UTF8String); + terminal.peer = pair[0]; terminal.command_fd = pair[1]; + terminal.output = [NSMutableData new]; + int one = 1; + setsockopt(pair[0], SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one); + if (pthread_create(thread, NULL, run_terminal, (__bridge_retained void *)terminal)) { + close(pair[0]); close(pair[1]); return nil; + } + return terminal; +} + +static void drain(TmuxTerminal *terminal, unsigned milliseconds) { + uint64_t deadline = clock_gettime_nsec_np(CLOCK_MONOTONIC) + (uint64_t)milliseconds * 1000000; + while (clock_gettime_nsec_np(CLOCK_MONOTONIC) < deadline) { + struct pollfd fd = {terminal.peer, POLLIN, 0}; + if (poll(&fd, 1, 20) > 0 && (fd.revents & POLLIN)) { + char buffer[16384]; ssize_t n = read(terminal.peer, buffer, sizeof buffer); + if (n > 0) [terminal.output appendBytes:buffer length:n]; + } + } +} + +static BOOL send_keys(TmuxTerminal *terminal, NSString *keys) { + NSData *bytes = [keys dataUsingEncoding:NSUTF8StringEncoding]; + const char *p = bytes.bytes; size_t left = bytes.length; + while (left) { + ssize_t n = write(terminal.peer, p, left); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return NO; + p += n; left -= n; + } + drain(terminal, 400); + return YES; +} + +static int finish(TmuxTerminal *terminal, pthread_t thread) { + for (unsigned i = 0; !terminal.done && i < 300; i++) drain(terminal, 100); + if (!terminal.done) return ETIMEDOUT; + pthread_join(thread, NULL); + close(terminal.peer); + free(terminal.session_key); + return terminal.status; +} + +static BOOL file_is(NSString *path, NSString *expected) { + return [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil] isEqual:expected]; +} + +__attribute__((visibility("default"))) int tmux_acceptance(int argc, char **argv) { + @autoreleasepool { + if (argc != 2 || argv[1][0] != '/') return 64; + NSString *directory = @(argv[1]); + NSError *error; + if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error]) return 1; + NSString *label = [@"a" stringByAppendingString:[NSUUID.UUID.UUIDString substringToIndex:4]]; + NSString *base = [NSString stringWithFormat:@"tmux -L %@", label]; + pthread_t thread; + TmuxTerminal *terminal = start([base stringByAppendingString:@" new -s t"], &thread); + if (!terminal) return 1; + for (unsigned i = 0; !terminal.output.length && !terminal.done && i < 600; i++) drain(terminal, 100); + fprintf(thread_stdout, "initial bytes=%lu done=%d\n", (unsigned long)terminal.output.length, terminal.done); + [terminal.output writeToFile:[directory stringByAppendingPathComponent:@"initial.ansi"] atomically:YES]; + if (terminal.output.length < 100) fwrite(terminal.output.bytes, 1, terminal.output.length, thread_stdout); + fflush(thread_stdout); + for (unsigned pane = 0; pane < 3; pane++) { + if (pane == 1) send_keys(terminal, @"\002%"); + if (pane == 2) send_keys(terminal, @"\002\""); + NSString *path = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"pane%u.txt", pane]]; + NSString *command = [NSString stringWithFormat:@"echo ok > '%@'; printf 'hello\\n' | tr a-z A-Z >> '%@'\r", path, path]; + if (!send_keys(terminal, command)) return 2; + for (unsigned i = 0; !file_is(path, @"ok\nHELLO\n") && i < 200; i++) drain(terminal, 100); + fprintf(thread_stdout, "pane%u file=%d bytes=%lu\n", pane, file_is(path, @"ok\nHELLO\n"), (unsigned long)terminal.output.length); + fflush(thread_stdout); + } + NSString *vim = [directory stringByAppendingPathComponent:@"vim.txt"]; + send_keys(terminal, [NSString stringWithFormat:@"vim '%@'\r", vim]); + drain(terminal, 1000); + send_keys(terminal, @":highlight Normal ctermfg=196 ctermbg=17\riTMUX_VIM_K\033[DO\033"); + ios_setWindowSize(111, 43, terminal.session_key); + int cols = 0, rows = 0; + int size_error = ios_getWindowSize(&cols, &rows, terminal.session_key); + fprintf(thread_stdout, "window size=%dx%d error=%d\n", cols, rows, size_error); + drain(terminal, 1000); + send_keys(terminal, @"oAFTER_RESIZE_K\033[DO\033:wq\r"); + for (unsigned i = 0; !file_is(vim, @"TMUX_VIM_OK\nAFTER_RESIZE_OK\n") && i < 100; i++) drain(terminal, 100); + send_keys(terminal, @"\002d"); + int status = finish(terminal, thread); + [terminal.output writeToFile:[directory stringByAppendingPathComponent:@"first.ansi"] atomically:YES]; + fprintf(thread_stdout, "detach status=%d bytes=%lu\n", status, (unsigned long)terminal.output.length); + if (status) return 3; + for (unsigned pane = 0; pane < 3; pane++) { + NSString *path = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"pane%u.txt", pane]]; + if (!file_is(path, @"ok\nHELLO\n")) { fprintf(thread_stdout, "FAIL pane%u output\n", pane); return 4; } + } + BOOL vim_ok = file_is(vim, @"TMUX_VIM_OK\nAFTER_RESIZE_OK\n"); + NSString *rendered = [[NSString alloc] initWithData:terminal.output encoding:NSUTF8StringEncoding]; + BOOL colors_ok = [rendered containsString:@"38;5;196"] || [rendered containsString:@"38;2;255;0;0"]; + fprintf(thread_stdout, "%s vim file\n", vim_ok ? "PASS" : "FAIL"); + fprintf(thread_stdout, "%s vim colors and arrow keys before/after resize\n", vim_ok && colors_ok ? "PASS" : "FAIL"); + fprintf(thread_stdout, "PASS three panes echo/pipeline\n"); + terminal = start([base stringByAppendingString:@" list-panes -t t -F '#{pane_id} #{window_width}x#{window_height}'"], &thread); + if (!terminal) return 1; + shutdown(terminal.peer, SHUT_WR); + status = finish(terminal, thread); + NSString *panes = [[NSString alloc] initWithData:terminal.output encoding:NSUTF8StringEncoding]; + fprintf(thread_stdout, "panes status=%d %s", status, panes.UTF8String); + if (status || ![panes containsString:@"111x42"]) return 6; + terminal = start([base stringByAppendingString:@" attach -t t"], &thread); + if (!terminal) return 1; + for (unsigned i = 0; !terminal.output.length && !terminal.done && i < 600; i++) drain(terminal, 100); + send_keys(terminal, [NSString stringWithFormat:@"echo reattached > '%@/reattached.txt'\r", directory]); + send_keys(terminal, @"\002d"); + status = finish(terminal, thread); + [terminal.output writeToFile:[directory stringByAppendingPathComponent:@"reattach.ansi"] atomically:YES]; + if (status || !file_is([directory stringByAppendingPathComponent:@"reattached.txt"], @"reattached\n")) return 7; + terminal = start([base stringByAppendingString:@" attach -t t"], &thread); + if (!terminal) return 1; + for (unsigned i = 0; !terminal.output.length && !terminal.done && i < 600; i++) drain(terminal, 100); + if (terminal.done || !terminal.registration || ashell_cancel_owned_streams(terminal.registration)) return 9; + status = finish(terminal, thread); + if (status == ETIMEDOUT) return 10; + fprintf(thread_stdout, "PASS interrupted client status=%d\n", status); + terminal = start([base stringByAppendingString:@" kill-server"], &thread); + if (!terminal) return 1; + shutdown(terminal.peer, SHUT_WR); + if (finish(terminal, thread)) return 8; + fprintf(thread_stdout, "PASS resize, detach/reattach and kill-server\n"); + if (vim_ok && colors_ok) fprintf(thread_stdout, "TMUX_ACCEPTANCE_PASS\n"); + return vim_ok && colors_ok ? 0 : 5; + } +} diff --git a/tmux/build.sh b/tmux/build.sh new file mode 100755 index 00000000..dae5405d --- /dev/null +++ b/tmux/build.sh @@ -0,0 +1,92 @@ +#!/bin/bash +set -euo pipefail +# Produce framework inputs. Xcode packages and signs the app. +if [ "$#" -ne 6 ]; then + echo "Usage: $0 " >&2 + exit 64 +fi +sdk=$1; archives=$2; output=$3; ios_source=$4; frameworks=$5; curses=$6 +case "$sdk" in + iphoneos) target=arm64-apple-ios14.0 ;; + iphonesimulator) target=arm64-apple-ios14.0-simulator ;; + *) echo "Unsupported SDK: $sdk" >&2; exit 64 ;; +esac +recipe=$(cd "$(dirname "$0")" && pwd) +pane_headers="$recipe/../ShellWorkers" +for path in "$ios_source/ios_error.h" "$ios_source/ios_system/ios_system.h" "$frameworks/ios_system.framework/ios_system" "$curses/ncurses.h" "$curses/term.h"; do + test -f "$path" || { echo "Missing input: $path" >&2; exit 1; } +done +(cd "$archives" && shasum -a 256 -c "$recipe/sources.sha256") +mkdir -p "$output" +output=$(cd "$output" && pwd) +archives=$(cd "$archives" && pwd) +ios_source=$(cd "$ios_source" && pwd) +frameworks=$(cd "$frameworks" && pwd) +curses=$(cd "$curses" && pwd) +receipt="$output/inputs.sha256" +shasum -a 256 "$recipe/build.sh" "$recipe/ios.patch" "$recipe/ios-engine.c" "$recipe/ios-engine.h" "$recipe/ios-boundary.h" "$recipe/host.m" "$recipe/acceptance.m" "$recipe/terminal.terminfo" "$recipe/sources.sha256" "$recipe/NCURSES-LICENSE" "$pane_headers/NativePane.h" "$ios_source/ios_error.h" "$ios_source/ios_system/ios_system.h" "$frameworks/ios_system.framework/ios_system" "$curses/ncurses.h" "$curses/term.h" > "$receipt.new" +{ + xcrun --sdk "$sdk" clang --version + xcrun --sdk "$sdk" --show-sdk-version + printf '%s\n' "$target" +} >> "$receipt.new" +if [ -f "$receipt" ] && ! cmp -s "$receipt" "$receipt.new"; then + echo "Build inputs changed; use a fresh output directory: $output" >&2 + rm "$receipt.new" + exit 1 +fi +mv "$receipt.new" "$receipt" +if [ ! -d "$output/libevent-2.1.13-stable" ]; then + staging=$(mktemp -d "$output/source.XXXXXX") + trap 'rm -rf "$staging"' EXIT + tar -xzf "$archives/libevent-2.1.13-stable.tar.gz" -C "$staging" + mv "$staging/libevent-2.1.13-stable" "$output/libevent-2.1.13-stable" + rmdir "$staging" + trap - EXIT +fi +if [ ! -d "$output/tmux-3.8" ]; then + staging=$(mktemp -d "$output/source.XXXXXX") + trap 'rm -rf "$staging"' EXIT + tar -xzf "$archives/tmux-3.8.tar.gz" -C "$staging" + (cd "$staging/tmux-3.8" && patch -p1 < "$recipe/ios.patch") + mv "$staging/tmux-3.8" "$output/tmux-3.8" + rmdir "$staging" + trap - EXIT +fi +cp "$recipe/ios-engine.c" "$recipe/ios-engine.h" "$recipe/ios-boundary.h" "$output/tmux-3.8/" +sysroot=$(xcrun --sdk "$sdk" --show-sdk-path) +cmake -S "$output/libevent-2.1.13-stable" -B "$output/event-build" -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT="$sysroot" -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=14.0 '-DCMAKE_C_FLAGS=-Oz -Werror=unguarded-availability-new' -DEVENT__HAVE_PIPE2=OFF -DEVENT__DISABLE_OPENSSL=ON -DEVENT__DISABLE_TESTS=ON -DEVENT__DISABLE_REGRESS=ON -DEVENT__DISABLE_SAMPLES=ON -DEVENT__LIBRARY_TYPE=STATIC -DCMAKE_INSTALL_PREFIX="$output/event" +nice -n 15 cmake --build "$output/event-build" --parallel 2 +cmake --install "$output/event-build" +(cd "$output/tmux-3.8" && autoreconf -fi) +mkdir -p "$output/engine" "$output/sdk" "$output/share/terminfo" +/usr/bin/tic -x -o "$output/share/terminfo" "$recipe/terminal.terminfo" +(cd "$output/engine" && "$output/tmux-3.8/configure" --host=aarch64-apple-ios --with-TERM=screen.xterm-256color --disable-utf8proc --disable-sixel --disable-jemalloc CC="xcrun --sdk $sdk clang -target $target" CFLAGS="-Oz -fvisibility=hidden -Werror=unguarded-availability-new" CPPFLAGS="-I$output/event/include -I$curses -I$ios_source -I$pane_headers -F$frameworks" LDFLAGS="-L$output/event/lib -F$frameworks -framework ios_system" PKG_CONFIG_LIBDIR="$output/event/lib/pkgconfig") +nice -n 15 make -C "$output/engine" -j2 +for name in TmuxNative TmuxHost TmuxAcceptance; do + framework="$output/sdk/$name.framework" + mkdir -p "$framework" + if [ "$name" = TmuxNative ]; then + cp "$output/engine/tmux" "$framework/$name" + cp "$output/tmux-3.8/COPYING" "$framework/TMUX-LICENSE" + cp "$output/libevent-2.1.13-stable/LICENSE" "$framework/LIBEVENT-LICENSE" + else + source="$recipe/host.m" + if [ "$name" = TmuxAcceptance ]; then source="$recipe/acceptance.m"; fi + xcrun --sdk "$sdk" clang -target "$target" -Oz -fvisibility=hidden -Werror=unguarded-availability-new -dynamiclib -fobjc-arc -fblocks -I"$ios_source" -I"$pane_headers" -F"$frameworks" -framework Foundation -framework ios_system -install_name "@rpath/$name.framework/$name" "$source" -o "$framework/$name" + fi + if [ "$name" = TmuxHost ]; then + cp -R "$output/share/terminfo" "$framework/" + cp "$recipe/NCURSES-LICENSE" "$framework/NCURSES-LICENSE" + fi + xcrun --sdk "$sdk" strip -x "$framework/$name" + cat > "$framework/Info.plist" < + +CFBundleExecutable$nameCFBundleIdentifierlocal.tmux.$nameCFBundleName$nameCFBundlePackageTypeFMWKCFBundleVersion1CFBundleShortVersionString3.8MinimumOSVersion14.0 +PLIST + file "$framework/$name" + shasum -a 256 "$framework/$name" + wc -c < "$framework/$name" + gzip -c "$framework/$name" | wc -c +done diff --git a/tmux/host.m b/tmux/host.m new file mode 100644 index 00000000..21cee03e --- /dev/null +++ b/tmux/host.m @@ -0,0 +1,304 @@ +#import +#include +#include +#include +#include +#include +#include +#include "NativePane.h" +#include "ios_error.h" +#include "ios-engine.h" +#undef write + +typedef int (*spawn_fn)(const char *, const char *, unsigned, unsigned, + const char *const *, ashell_pane_options *, int *, void **); +typedef int (*poll_fn)(void *, int *); +typedef int (*resize_fn)(void *, unsigned, unsigned); +typedef int (*close_fn)(void *); +typedef void (*release_fn)(void *); + +static NSString *quote(NSString *text) { + return [NSString stringWithFormat:@"'%@'", [text stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]]; +} + +@interface TmuxServer : NSObject +@property void *job; +@property int fd; +@property BOOL exited; +@property BOOL cancel; +@property BOOL ready; +@property NSMutableData *diagnostic; +@end +@implementation TmuxServer +@end + +static NSMutableDictionary *servers; + +// Only the app owns server handles. A client extension may disappear on detach. +static int start_server(NSString *socket, NSString *cwd, NSArray *options, + const char *const *env, TmuxServer **created) { + spawn_fn spawn = (spawn_fn)dlsym(RTLD_DEFAULT, "ashell_pane_spawn_ex"); + if (!spawn) return ENOTSUP; + TmuxServer *server; + BOOL launched = NO; + @synchronized (servers) { + server = servers[socket]; + if (!server || server.exited) { + NSMutableString *command = [NSMutableString stringWithString:@"tmux-native -D -S "]; + [command appendString:quote(socket)]; + for (NSString *option in options) [command appendFormat:@" %@", quote(option)]; + server = [TmuxServer new]; + server.diagnostic = [NSMutableData new]; + ashell_pane_options config = {.size = sizeof(config), .tty = 0}; + int fd; + void *job; + int error = spawn(command.UTF8String, cwd.UTF8String, 80, 24, env, + &config, &fd, &job); + if (error) return error; + server.fd = fd; + server.job = job; + servers[socket] = server; + *created = server; + launched = YES; + } + } + // Drain and reap independently of any foreground invocation, including detach. + if (launched) dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ + poll_fn poll_child = (poll_fn)dlsym(RTLD_DEFAULT, "ashell_pane_poll"); + close_fn cancel = (close_fn)dlsym(RTLD_DEFAULT, "ashell_pane_cancel"); + release_fn release = (release_fn)dlsym(RTLD_DEFAULT, "ashell_pane_release"); + for (;;) { + if (server.cancel) { cancel(server.job); break; } + struct pollfd fd = {server.fd, POLLIN, 0}; + poll(&fd, 1, 100); + if (fd.revents & POLLIN) { + char buffer[4096]; + ssize_t count = read(server.fd, buffer, sizeof buffer); + if (count > 0) @synchronized (server) { + if (server.diagnostic.length < 8192) + [server.diagnostic appendBytes:buffer length:count]; + NSData *marker = [@"ASHELL_TMUX_READY\n" dataUsingEncoding:NSUTF8StringEncoding]; + if ([server.diagnostic rangeOfData:marker options:0 range:NSMakeRange(0, server.diagnostic.length)].location != NSNotFound) + server.ready = YES; + } + } + int status; + if (poll_child(server.job, &status) != 0) break; + } + release(server.job); + close(server.fd); + @synchronized (servers) { + server.exited = YES; + if (servers[socket] == server) [servers removeObjectForKey:socket]; + } + }); + for (unsigned retry = 0; retry != 200; retry++) { + if (server.ready) return 0; + if (server.exited) break; + usleep(25000); + } + @synchronized (server) { + if (server.diagnostic.length) + fwrite(server.diagnostic.bytes, 1, server.diagnostic.length, thread_stderr); + } + server.cancel = YES; + return server.exited ? ECHILD : ETIMEDOUT; +} + +static unsigned dimension(const char *name, unsigned fallback) { + const char *value = ios_getenv(name); + if (!value) return fallback; + char *end; + unsigned long n = strtoul(value, &end, 10); + return *end || n < 1 || n > 9999 ? fallback : (unsigned)n; +} + +static int write_all(int fd, const char *data, size_t size) { + while (size) { + ssize_t count = write(fd, data, size); + if (count < 0 && errno == EINTR) continue; + if (count <= 0) return errno ? errno : EIO; + data += count; + size -= count; + } + return 0; +} + +typedef struct client_cleanup { + void *job; + int fd; + release_fn release; + int previous_interactive; +} client_cleanup; + +static void finish_client(void *cookie) { + client_cleanup *client = cookie; + client->release(client->job); + close(client->fd); + if (!client->previous_interactive) ios_stopInteractive(); +} + +__attribute__((visibility("default"))) int tmux_main(int argc, char **argv) { + @autoreleasepool { + static dispatch_once_t once; + dispatch_once(&once, ^{ servers = [NSMutableDictionary new]; }); + BOOL nested = dlsym(RTLD_DEFAULT, "ashell_worker_spawn_ex") != NULL; + NSBundle *app = nested ? [NSBundle bundleWithURL:NSBundle.mainBundle.bundleURL.URLByDeletingLastPathComponent.URLByDeletingLastPathComponent] : NSBundle.mainBundle; + NSString *group = [app objectForInfoDictionaryKey:@"AppGroupIdentifier"]; + if (!group.length) { fprintf(thread_stderr, "tmux: shared App Group identifier unavailable\n"); return 1; } + const char *prefix = nested ? "ashell_worker_" : "ashell_pane_"; + spawn_fn spawn = (spawn_fn)dlsym(RTLD_DEFAULT, [[NSString stringWithFormat:@"%sspawn_ex", prefix] UTF8String]); + poll_fn poll_child = (poll_fn)dlsym(RTLD_DEFAULT, [[NSString stringWithFormat:@"%spoll", prefix] UTF8String]); + resize_fn resize = (resize_fn)dlsym(RTLD_DEFAULT, [[NSString stringWithFormat:@"%sresize", prefix] UTF8String]); + close_fn close_input = (close_fn)dlsym(RTLD_DEFAULT, [[NSString stringWithFormat:@"%sclose_stdin", prefix] UTF8String]); + release_fn release = (release_fn)dlsym(RTLD_DEFAULT, [[NSString stringWithFormat:@"%srelease", prefix] UTF8String]); + if (!spawn || !poll_child || !resize || !close_input || !release) { + fprintf(thread_stderr, "tmux: interactive worker broker unavailable\n"); + return 1; + } + NSMutableArray *args = [NSMutableArray new], *server_options = [NSMutableArray new]; + NSString *socket = nil, *label = nil; + BOOL no_start = NO, version = NO; + int opt; + optind = 1; optreset = 1; opterr = 0; + while ((opt = getopt(argc, argv, "2c:CDdf:hlL:NqS:T:uUvV")) != -1) { + const char *option_argument = optarg; + NSString *argument = option_argument ? @(option_argument) : nil; + if (!argument && strchr("cfLST", opt)) { fprintf(thread_stderr, "tmux: option -%c requires an argument\n", opt); return 1; } + if (opt == 'D') { fprintf(thread_stderr, "tmux: the app owns server lifetime; -D is internal\n"); return 1; } + if (opt == '?' || opt == ':') { fprintf(thread_stderr, "usage: tmux [-2CDNquvV] [-c shell-command] [-f file] [-L socket-name] [-S socket-path] [command [flags]]\n"); return 1; } + if (opt == 'S') { socket = argument; continue; } + if (opt == 'L') { label = argument; continue; } + if (opt == 'N') { no_start = YES; continue; } + version |= opt == 'V' || opt == 'h'; + NSString *flag = [NSString stringWithFormat:@"-%c", opt]; + [args addObject:flag]; + if (opt == 'f' || opt == 'T' || opt == 'c') [args addObject:argument]; + if (opt == 'f' || opt == 'v') { + [server_options addObject:flag]; + if (opt == 'f') [server_options addObject:argument]; + } + } + // ios_system can reset getopt globals while sockets and environment are resolved. + int command_start = optind; + if (command_start < 1 || command_start > argc) { fprintf(thread_stderr, "tmux: argument parsing failed\n"); return 1; } + for (int i = command_start; i < argc; i++) [args addObject:@(argv[i])]; + // Version/help are handled by the stock engine without resolving a socket. + if (!version) { + if (!socket && !label) { + const char *inherited_socket = ios_getenv("TMUX"); + if (inherited_socket && *inherited_socket && *inherited_socket != ',') + socket = [@(inherited_socket) componentsSeparatedByString:@","][0]; + } + if (!socket) { + if (!label) label = @"default"; + if ([label containsString:@"/"] || [label isEqual:@"."] || [label isEqual:@".."]) return 1; + const char *temporary = ios_getenv("TMUX_TMPDIR"); + NSString *root = temporary && *temporary ? @(temporary) : nil; + if (!root) { + NSURL *container = group ? [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:group] : nil; + if (!container) { + fprintf(thread_stderr, "tmux: shared app group container unavailable\n"); return 1; + } + root = container.path; + } + NSString *directory = [root stringByAppendingPathComponent:@"tmux-ios"]; + NSError *error; + if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions: @0700} error:&error]) { + fprintf(thread_stderr, "tmux: socket directory: %s\n", error.localizedDescription.UTF8String); return 1; + } + socket = [directory stringByAppendingPathComponent:label]; + } + if (![socket isAbsolutePath]) { + fprintf(thread_stderr, "tmux: socket requires an absolute path\n"); return 1; + } + if ([server_options containsObject:@"-v"]) + fprintf(thread_stderr, "tmux: socket path=%s bytes=%zu\n", socket.fileSystemRepresentation, strlen(socket.fileSystemRepresentation)); + } + NSString *cwd = [[NSFileManager defaultManager] currentDirectoryPath]; + char **inherited = environmentVariables(ios_currentPid()); + NSMutableArray *values = [NSMutableArray new]; + for (size_t i = 0; inherited && inherited[i]; i++) + if (strncmp(inherited[i], "TERM=", 5) && strncmp(inherited[i], "TERMINFO_DIRS=", 14) && strncmp(inherited[i], "ASHELL_REQUIRED_APP_GROUP=", 26) && strncmp(inherited[i], "ASHELL_TMUX_START=", 18)) [values addObject:@(inherited[i])]; + [values addObject:[@"ASHELL_REQUIRED_APP_GROUP=" stringByAppendingString:group]]; + [values addObject:@"TERM=xterm-256color"]; + Dl_info image; + if (!dladdr((const void *)tmux_main, &image) || !image.dli_fname) return 1; + NSString *terminfo = [[@(image.dli_fname) stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"terminfo"]; + const char *directories = ios_getenv("TERMINFO_DIRS"); + [values addObject:[NSString stringWithFormat:@"TERMINFO_DIRS=%@:%s", terminfo, directories ? directories : ""]]; + BOOL starts = !no_start && !version; + TmuxServer *created = nil, *previous; + @synchronized (servers) { previous = servers[socket]; } + NSMutableString *command = version ? [NSMutableString stringWithString:@"tmux-native"] : + [NSMutableString stringWithFormat:@"tmux-native -N -S %@", quote(socket)]; + for (NSString *arg in args) [command appendFormat:@" %@", quote(arg)]; + unsigned cols = dimension("COLUMNS", 80), rows = dimension("LINES", 24); + for (unsigned attempt = 0; attempt < 2; attempt++) { + const char **environment = calloc(values.count + 2, sizeof(*environment)); + if (!environment) return 1; + for (NSUInteger i = 0; i < values.count; i++) environment[i] = values[i].UTF8String; + if (starts) environment[values.count] = "ASHELL_TMUX_START=1"; + if (attempt) { + if (nested) { + fprintf(thread_stderr, "tmux: start a new server from the app terminal; workers may attach to existing servers\n"); + free(environment); + return 1; + } + for (unsigned retry = 0; previous && !previous.exited && retry < 200; retry++) usleep(25000); + if (previous && !previous.exited) { fprintf(thread_stderr, "tmux: previous server has not exited\n"); free(environment); return 1; } + int error = start_server(socket, cwd, server_options, environment, &created); + if (error) { fprintf(thread_stderr, "tmux: start server: %s\n", strerror(error)); free(environment); return 1; } + } + ashell_pane_options config = {.size = sizeof(config), .tty = ios_isatty(0)}; + void *job = NULL; + int fd = -1; + int error = spawn(command.UTF8String, cwd.UTF8String, cols, rows, environment, &config, &fd, &job); + free(environment); + if (error) { + if (created) { + created.cancel = YES; + for (unsigned retry = 0; !created.exited && retry < 200; retry++) usleep(25000); + } + fprintf(thread_stderr, "tmux: client worker: %s%s\n", strerror(error), error == EACCES ? "; shared App Group membership required" : error == ENOSPC ? "; all shell workers are in use; close a pane or session first" : ""); + return 1; + } + int old_interactive = ios_storeInteractive(); + if (config.tty) ios_startInteractive(); + client_cleanup cleanup = {job, fd, release, old_interactive}; + BOOL eof = NO, output_eof = NO; + int status = 1, result = 0; + pthread_cleanup_push(finish_client, &cleanup); + while (!output_eof || result == 0) { + struct pollfd fds[] = {{output_eof ? -1 : fd, POLLIN, 0}, {eof ? -1 : fileno(thread_stdin), POLLIN, 0}}; + int ready = poll(fds, 2, 20); + if (ready < 0 && errno != EINTR) break; + char buffer[16384]; + if (fds[0].revents & (POLLIN|POLLHUP)) { + ssize_t n = read(fd, buffer, sizeof buffer); + if (n <= 0) output_eof = YES; + else if (write_all(fileno(thread_stdout), buffer, n)) break; + } + if (fds[1].revents & (POLLIN|POLLHUP)) { + ssize_t n = read(fileno(thread_stdin), buffer, sizeof buffer); + if (n <= 0) { eof = YES; close_input(job); } + else if (write_all(fd, buffer, n)) break; + } + unsigned x = dimension("COLUMNS", cols), y = dimension("LINES", rows); + if (x != cols || y != rows) { + int resize_error = resize(job, x, y); + if (resize_error && (resize_error != ESRCH || poll_child(job, &status) != 1)) { + fprintf(thread_stderr, "tmux: resize: %s\n", strerror(resize_error)); break; + } + cols = x; rows = y; + } + result = poll_child(job, &status); + if (result < 0) break; + } + pthread_cleanup_pop(1); + if (result == 1 && status == ASHELL_TMUX_NO_SERVER && starts && attempt == 0) continue; + return result == 1 ? (status == ASHELL_TMUX_NO_SERVER ? 1 : status) : 1; + } + return 1; + } +} diff --git a/tmux/ios-boundary.h b/tmux/ios-boundary.h new file mode 100644 index 00000000..1b5642d4 --- /dev/null +++ b/tmux/ios-boundary.h @@ -0,0 +1,39 @@ +#ifndef ASHELL_TMUX_BOUNDARY_H +#define ASHELL_TMUX_BOUNDARY_H +#include +#include +#include +#include +#include +#undef getopt +#undef getopt_long +#undef getopt_long_only +#undef optind +#undef opterr +#undef optopt +#undef optreset +#undef optarg +#include "ios_error.h" + +// Each tmux engine runs in a dedicated extension process. Keep its event-loop +// signals local to that process; only its command streams and exit use ios_system. +#undef signal +#undef kill +#undef killpg +#undef iswprint +#undef optional_argument +#undef stdout +#undef stderr +#undef stdin +#define stdout thread_stdout +#define stderr thread_stderr +#define stdin thread_stdin +#undef STDIN_FILENO +#undef STDOUT_FILENO +#undef STDERR_FILENO +#define STDIN_FILENO fileno(thread_stdin) +#define STDOUT_FILENO fileno(thread_stdout) +#define STDERR_FILENO fileno(thread_stderr) +#define isatty ios_isatty +#define printf(...) fprintf(thread_stdout, __VA_ARGS__) +#endif diff --git a/tmux/ios-engine.c b/tmux/ios-engine.c new file mode 100644 index 00000000..be16afc0 --- /dev/null +++ b/tmux/ios-engine.c @@ -0,0 +1,160 @@ +#include +#include +#include +#include +#include +#include +#include "tmux.h" +#include "ios-engine.h" +#include "NativePane.h" +#include + +int +tmux_ios_check_shared_container(void) +{ + int (*available)(void) = (int (*)(void))dlsym(RTLD_DEFAULT, "ashell_worker_has_shared_container"); + if (available && available()) return 0; + fprintf(thread_stderr, "tmux: shared App Group membership required for native engines\n"); + return 1; +} + +// The engine owns an isolated worker process. Change its native cwd only for +// bind/connect, then restore it before servicing commands or spawning panes. +// Keep the full socket_path for tmux discovery, locks, cleanup and $TMUX. +#undef fchdir +int +tmux_ios_socket(int fd, const char *path, int binding) +{ + const char *name = strrchr(path, '/'); + struct sockaddr_un address = {.sun_family = AF_UNIX}; + if (name == NULL || name[1] == '\0') { errno = EINVAL; return -1; } + if (strlen(++name) >= sizeof address.sun_path) { errno = ENAMETOOLONG; return -1; } + char *directory = strndup(path, name - path); + if (directory == NULL) return -1; + int previous = open(".", O_RDONLY | O_DIRECTORY); + if (previous == -1) { free(directory); return -1; } + int result = chdir(directory); + free(directory); + if (result == 0) { + strlcpy(address.sun_path, name, sizeof address.sun_path); + result = binding ? bind(fd, (struct sockaddr *)&address, sizeof address) : + connect(fd, (struct sockaddr *)&address, sizeof address); + } + int saved = errno; + if (fchdir(previous) == -1) { result = -1; saved = errno; } + close(previous); + errno = saved; + return result; +} + +typedef int (*spawn_fn)(const char *, const char *, unsigned, unsigned, + const char *const *, ashell_pane_options *, int *, void **); +typedef int (*poll_fn)(void *, int *); +typedef int (*resize_fn)(void *, unsigned, unsigned); +typedef void (*release_fn)(void *); + +void +tmux_ios_send_resize(struct tmuxpeer *peer) +{ + const char *cols = ios_getenv("COLUMNS"), *rows = ios_getenv("LINES"); + unsigned size[2] = { + cols ? strtonum(cols, 1, 9999, NULL) : 80, + rows ? strtonum(rows, 1, 9999, NULL) : 24 + }; + static unsigned previous[2]; + if (size[0] && size[1] && memcmp(previous, size, sizeof size)) { + proc_send(peer, MSG_RESIZE, -1, size, sizeof size); + memcpy(previous, size, sizeof size); + } +} + +static void +pane_poll(int fd, short events, void *data) +{ + struct window_pane *wp = data; + poll_fn poll_child = (poll_fn)dlsym(RTLD_DEFAULT, "ashell_worker_poll"); + int status = 0, result = poll_child(wp->ios_job, &status); + struct timeval interval = {.tv_usec = 20000}; + if (result == 0) { + evtimer_add(&wp->ios_poll, &interval); + return; + } + if (result < 0) { + log_debug("pane worker poll failed: %s", strerror(-result)); + status = 255; + } + tmux_ios_pane_exited(wp, status << 8); +} + +int +tmux_ios_spawn_pane(struct spawn_context *sc, struct window_pane *wp, + struct environ *environment, struct winsize *size, char **cause) +{ + spawn_fn spawn = (spawn_fn)dlsym(RTLD_DEFAULT, "ashell_worker_spawn_ex"); + if (!spawn || !dlsym(RTLD_DEFAULT, "ashell_worker_resize") || + !dlsym(RTLD_DEFAULT, "ashell_worker_poll") || + !dlsym(RTLD_DEFAULT, "ashell_worker_release")) { + xasprintf(cause, "interactive worker broker unavailable"); + return ENOTSUP; + } + tmux_ios_release_pane(wp); + struct environ_entry *entry; + size_t count = 0; + for (entry = environ_first(environment); entry; entry = environ_next(entry)) + if (entry->value && !(entry->flags & ENVIRON_HIDDEN)) count++; + char **env = xcalloc(count + 1, sizeof(*env)); + count = 0; + for (entry = environ_first(environment); entry; entry = environ_next(entry)) + if (entry->value && !(entry->flags & ENVIRON_HIDDEN)) + xasprintf(&env[count++], "%s=%s", entry->name, entry->value); + char *command; + const char *shell = strrchr(wp->shell, '/'); + shell = shell ? shell + 1 : wp->shell; + // a-Shell's interactive shell is Dash; its "sh" entry is not interactive. + if (!strcmp(shell, "sh")) shell = "dash"; + // cmd_stringify_argv quotes arguments for the shell, including embedded quotes. + if (wp->argc == 1) { + char *args[] = {(char *)shell, "-c", wp->argv[0]}; + command = cmd_stringify_argv(3, args); + } else if (wp->argc > 1) + command = cmd_stringify_argv(wp->argc, wp->argv); + else { + char *args[] = {(char *)shell, "-i", "-E"}; + command = cmd_stringify_argv(!strcmp(shell, "dash") ? 3 : 2, args); + } + ashell_pane_options options = {.size = sizeof(options), .tty = 1}; + int error = spawn(command, wp->cwd, size->ws_col, size->ws_row, + (const char *const *)env, &options, &wp->fd, &wp->ios_job); + free(command); + for (size_t i = 0; env[i]; i++) free(env[i]); + free(env); + if (error) { + xasprintf(cause, "pane worker: %s%s", strerror(error), error == ENOSPC ? "; all shell workers are in use; close a pane or session first" : ""); + return error; + } + wp->pid = -1; // The opaque worker handle is not a kernel child PID. + wp->tty[0] = '\0'; + evtimer_set(&wp->ios_poll, pane_poll, wp); + struct timeval interval = {.tv_usec = 20000}; + evtimer_add(&wp->ios_poll, &interval); + return 0; +} + +void +tmux_ios_release_pane(struct window_pane *wp) +{ + if (!wp->ios_job) return; + evtimer_del(&wp->ios_poll); + release_fn release = (release_fn)dlsym(RTLD_DEFAULT, "ashell_worker_release"); + release(wp->ios_job); + wp->ios_job = NULL; +} + +void +tmux_ios_resize_pane(struct window_pane *wp, unsigned cols, unsigned rows) +{ + if (!wp->ios_job) return; + resize_fn resize = (resize_fn)dlsym(RTLD_DEFAULT, "ashell_worker_resize"); + int error = resize(wp->ios_job, cols, rows); + if (error && error != ESRCH) log_debug("pane worker resize failed: %s", strerror(error)); +} diff --git a/tmux/ios-engine.h b/tmux/ios-engine.h new file mode 100644 index 00000000..dcb896b1 --- /dev/null +++ b/tmux/ios-engine.h @@ -0,0 +1,19 @@ +#ifndef ASHELL_TMUX_ENGINE_H +#define ASHELL_TMUX_ENGINE_H +// Private engine result: no listener accepted the initial client connection. +#define ASHELL_TMUX_NO_SERVER 75 +int tmux_ios_check_shared_container(void); +int tmux_ios_socket(int, const char *, int); +struct window_pane; +struct spawn_context; +struct environ; +struct winsize; +struct tmuxpeer; +struct client_files; +int tmux_ios_spawn_pane(struct spawn_context *, struct window_pane *, struct environ *, struct winsize *, char **); +void tmux_ios_release_pane(struct window_pane *); +void tmux_ios_resize_pane(struct window_pane *, unsigned, unsigned); +void tmux_ios_pane_exited(struct window_pane *, int); +void tmux_ios_send_resize(struct tmuxpeer *); +void tmux_ios_close_files(struct client_files *); +#endif diff --git a/tmux/ios.patch b/tmux/ios.patch new file mode 100644 index 00000000..1bece8d7 --- /dev/null +++ b/tmux/ios.patch @@ -0,0 +1,1129 @@ +--- a/Makefile.am ++++ b/Makefile.am +@@ -1,5 +1,7 @@ + # Obvious program stuff. + bin_PROGRAMS = tmux ++tmux_LDFLAGS = -dynamiclib -Wl,-install_name,@rpath/TmuxNative.framework/TmuxNative ++tmux_SOURCES = ios-engine.c + CLEANFILES = tmux.1.mdoc tmux.1.man cmd-parse.c + + # Distribution tarball options. +--- a/configure.ac ++++ b/configure.ac +@@ -998,6 +998,12 @@ + *aix*) + AC_MSG_RESULT(aix) + PLATFORM=aix ++ ;; ++ *ios*) ++ AC_MSG_RESULT(ios) ++ PLATFORM=unknown ++ AC_DEFINE(BROKEN___DEAD) ++ AC_DEFINE(BROKEN_CMSG_FIRSTHDR) + ;; + *darwin*) + AC_MSG_RESULT(darwin) +--- a/tmux.h ++++ b/tmux.h +@@ -1302,6 +1302,9 @@ + + /* Child window structure. */ + struct window_pane { ++ void *ios_job; ++ int ios_previous_cr; ++ struct event ios_poll; + u_int id; + int references; + u_int active_point; +@@ -2308,6 +2310,7 @@ + #define CLIENT_WRITE_ACK 0x4000000000ULL + #define CLIENT_NO_DETACH_ON_DESTROY 0x8000000000ULL + #define CLIENT_CONTROL_DISCARD 0x10000000000ULL ++#define CLIENT_IOS_TERMINAL 0x20000000000ULL + #define CLIENT_ALLREDRAWFLAGS \ + (CLIENT_REDRAWWINDOW| \ + CLIENT_REDRAWSTATUS| \ +@@ -4310,4 +4313,6 @@ + int json_find_array(struct json_node *, const char *, + struct json_node **, char **); + ++#include "ios-boundary.h" ++#include "ios-engine.h" + #endif /* TMUX_H */ +--- a/tmux.c ++++ b/tmux.c +@@ -390,7 +390,7 @@ + } + + int +-main(int argc, char **argv) ++__attribute__((visibility("default"))) tmux_native_main(int argc, char **argv) + { + char *path = NULL, *label = NULL; + char *cause, **var; +@@ -400,6 +400,9 @@ + const struct options_table_entry *oe; + u_int i; + ++ if (tmux_ios_check_shared_container()) ++ return (1); ++ + if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL && + setlocale(LC_CTYPE, "C.UTF-8") == NULL) { + if (setlocale(LC_CTYPE, "") == NULL) +@@ -416,7 +419,7 @@ + flags = CLIENT_LOGIN; + + global_environ = environ_create(); +- for (var = environ; *var != NULL; var++) ++ for (var = environmentVariables(ios_currentPid()); var != NULL && *var != NULL; var++) + environ_put(global_environ, *var, 0); + if ((cwd = find_cwd()) != NULL) + environ_set(global_environ, "PWD", 0, "%s", cwd); +--- a/client.c ++++ b/client.c +@@ -34,6 +34,15 @@ + + static struct tmuxproc *client_proc; + static struct tmuxpeer *client_peer; ++static struct event client_resize_timer; ++ ++static void ++client_resize_poll(int fd, short events, void *data) ++{ ++ tmux_ios_send_resize(client_peer); ++ struct timeval interval = {.tv_usec = 100000}; ++ evtimer_add(&client_resize_timer, &interval); ++} + static uint64_t client_flags; + static int client_suspended; + static enum { +@@ -104,18 +113,9 @@ + static int + client_connect(struct event_base *base, const char *path, uint64_t flags) + { +- struct sockaddr_un sa; +- size_t size; + int fd, lockfd = -1, locked = 0; + char *lockfile = NULL; + +- memset(&sa, 0, sizeof sa); +- sa.sun_family = AF_UNIX; +- size = strlcpy(sa.sun_path, path, sizeof sa.sun_path); +- if (size >= sizeof sa.sun_path) { +- errno = ENAMETOOLONG; +- return (-1); +- } + log_debug("socket is %s", path); + + retry: +@@ -123,7 +123,7 @@ + return (-1); + + log_debug("trying connect"); +- if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == -1) { ++ if (tmux_ios_socket(fd, path, 0) == -1) { + log_debug("connect failed: %s", strerror(errno)); + if (errno != ECONNREFUSED && errno != ENOENT) + goto failed; +@@ -288,6 +288,10 @@ + #endif + fd = client_connect(base, socket_path, client_flags); + if (fd == -1) { ++ if ((errno == ECONNREFUSED || errno == ENOENT) && ++ (client_flags & CLIENT_STARTSERVER) && ++ ios_getenv("ASHELL_TMUX_START") != NULL) ++ return (ASHELL_TMUX_NO_SERVER); + if (errno == ECONNREFUSED) { + fprintf(stderr, "no server running on %s\n", + socket_path); +@@ -303,7 +307,7 @@ + if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL) + cwd = "/"; + if ((ttynam = ttyname(STDIN_FILENO)) == NULL) +- ttynam = ""; ++ ttynam = "ios-terminal"; + if ((termname = getenv("TERM")) == NULL) + termname = ""; + +@@ -321,6 +325,7 @@ + NULL) != 0) + fatal("pledge failed"); + ++ if (ios_isatty(STDIN_FILENO)) ios_startInteractive(); + /* Load terminfo entry if any. */ + if (isatty(STDIN_FILENO) && + *termname != '\0' && +@@ -341,23 +346,8 @@ + + /* Set up control mode. */ + if (client_flags & CLIENT_CONTROLCONTROL) { +- if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) { +- fprintf(stderr, "tcgetattr failed: %s\n", +- strerror(errno)); +- return (1); +- } +- cfmakeraw(&tio); +- tio.c_iflag = ICRNL|IXANY; +- tio.c_oflag = OPOST|ONLCR; +-#ifdef NOKERNINFO +- tio.c_lflag = NOKERNINFO; +-#endif +- tio.c_cflag = CREAD|CS8|HUPCL; +- tio.c_cc[VMIN] = 1; +- tio.c_cc[VTIME] = 0; +- cfsetispeed(&tio, cfgetispeed(&saved_tio)); +- cfsetospeed(&tio, cfgetospeed(&saved_tio)); +- tcsetattr(STDIN_FILENO, TCSANOW, &tio); ++ fprintf(stderr, "tmux: -CC requires a kernel terminal\n"); ++ return (1); + } + + /* Send identify messages. */ +@@ -396,8 +386,10 @@ + } else if (msg == MSG_SHELL) + proc_send(client_peer, msg, -1, NULL, 0); + +- /* Start main loop. */ ++ /* ios_system terminal sizes are session data, not kernel TTY ioctls. */ ++ evtimer_set(&client_resize_timer, client_resize_poll, NULL); + proc_loop(client_proc, NULL); ++ evtimer_del(&client_resize_timer); + + /* Run command if user requested exec, instead of exiting. */ + if (client_exittype == MSG_EXEC) { +@@ -422,11 +414,6 @@ + fflush(stdout); + if (client_flags & CLIENT_CONTROL_WAITEXIT) + control_wait_exit(STDIN_FILENO); +- if (client_flags & CLIENT_CONTROLCONTROL) { +- printf("\033\\"); +- fflush(stdout); +- tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio); +- } + } else if (client_exitreason != CLIENT_EXIT_NONE) + fprintf(stderr, "%s\n", client_exit_message()); + +@@ -435,6 +422,8 @@ + setblocking(STDOUT_FILENO, 1); + setblocking(STDERR_FILENO, 1); + ++ tmux_ios_close_files(&client_files); ++ proc_remove_peer(client_peer); + return (client_exitval); + } + +@@ -447,6 +436,7 @@ + size_t sslen; + int fd; + uint64_t flags = client_flags; ++ if (ios_isatty(STDIN_FILENO)) flags |= CLIENT_IOS_TERMINAL; + pid_t pid; + u_int i; + +@@ -477,7 +467,7 @@ + pid = getpid(); + proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid); + +- for (ss = environ; *ss != NULL; ss++) { ++ for (ss = environmentVariables(ios_currentPid()); ss != NULL && *ss != NULL; ss++) { + sslen = strlen(*ss) + 1; + if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE) + continue; +@@ -491,21 +481,7 @@ + static __dead void + client_exec(const char *shell, const char *shellcmd) + { +- char *argv0; +- +- log_debug("shell %s, command %s", shell, shellcmd); +- argv0 = shell_argv0(shell, !!(client_flags & CLIENT_LOGIN)); +- setenv("SHELL", shell, 1); +- +- proc_clear_signals(client_proc, 1); +- +- setblocking(STDIN_FILENO, 1); +- setblocking(STDOUT_FILENO, 1); +- setblocking(STDERR_FILENO, 1); +- closefrom(STDERR_FILENO + 1); +- +- execl(shell, argv0, "-c", shellcmd, (char *) NULL); +- fatal("execl failed"); ++ fatalx("tmux -c/exec requires an unsupported process replacement"); + } + + /* Callback to handle signals in the client. */ +@@ -546,7 +522,7 @@ + proc_send(client_peer, MSG_EXITING, -1, NULL, 0); + break; + case SIGWINCH: +- proc_send(client_peer, MSG_RESIZE, -1, NULL, 0); ++ tmux_ios_send_resize(client_peer); + break; + case SIGCONT: + memset(&sigact, 0, sizeof sigact); +@@ -654,7 +630,7 @@ + fatalx("bad MSG_READY size"); + + client_attached = 1; +- proc_send(client_peer, MSG_RESIZE, -1, NULL, 0); ++ client_resize_poll(-1, 0, NULL); + break; + case MSG_VERSION: + if (datalen != 0) +--- a/file.c ++++ b/file.c +@@ -220,7 +220,7 @@ + evbuffer_add_vprintf(cf->buffer, fmt, ap); + + msg.stream = 1; +- msg.fd = STDOUT_FILENO; ++ msg.fd = 1; + msg.flags = 0; + proc_send(c->peer, MSG_WRITE_OPEN, -1, &msg, sizeof msg); + } else { +@@ -247,7 +247,7 @@ + evbuffer_add(cf->buffer, data, size); + + msg.stream = 1; +- msg.fd = STDOUT_FILENO; ++ msg.fd = 1; + msg.flags = 0; + proc_send(c->peer, MSG_WRITE_OPEN, -1, &msg, sizeof msg); + } else { +@@ -277,7 +277,7 @@ + evbuffer_add_vprintf(cf->buffer, fmt, ap); + + msg.stream = 2; +- msg.fd = STDERR_FILENO; ++ msg.fd = 2; + msg.flags = 0; + proc_send(c->peer, MSG_WRITE_OPEN, -1, &msg, sizeof msg); + } else { +@@ -305,7 +305,7 @@ + cf = file_create_with_client(c, stream, cb, cbdata); + cf->path = xstrdup("-"); + +- fd = STDOUT_FILENO; ++ fd = 1; + if (c == NULL || + (c->flags & CLIENT_ATTACHED) || + (c->flags & CLIENT_CONTROL)) { +@@ -379,7 +379,7 @@ + cf = file_create_with_client(c, stream, cb, cbdata); + cf->path = xstrdup("-"); + +- fd = STDIN_FILENO; ++ fd = 0; + if (c == NULL || + (c->flags & CLIENT_ATTACHED) || + (c->flags & CLIENT_CONTROL)) { +@@ -634,12 +634,11 @@ + if (msg->fd == -1) + cf->fd = open(path, msg->flags|flags, 0644); + else if (allow_streams) { +- if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO) ++ if (msg->fd != 1 && msg->fd != 2) + errno = EBADF; + else { +- cf->fd = dup(msg->fd); +- if (close_received) +- close(msg->fd); /* can only be used once */ ++ cf->fd = dup(msg->fd == 0 ? STDIN_FILENO : msg->fd == 1 ? STDOUT_FILENO : STDERR_FILENO); ++ /* The session owns its FILE descriptors; only the duplicate is ours. */ + } + } else + errno = EBADF; +@@ -791,12 +790,11 @@ + if (msg->fd == -1) + cf->fd = open(path, flags); + else if (allow_streams) { +- if (msg->fd != STDIN_FILENO) ++ if (msg->fd != 0) + errno = EBADF; + else { +- cf->fd = dup(msg->fd); +- if (close_received) +- close(msg->fd); /* can only be used once */ ++ cf->fd = dup(msg->fd == 0 ? STDIN_FILENO : msg->fd == 1 ? STDOUT_FILENO : STDERR_FILENO); ++ /* The session owns its FILE descriptors; only the duplicate is ours. */ + } + } else + errno = EBADF; +@@ -925,3 +923,14 @@ + file_fire_done(cf); + return (0); + } ++ ++void ++tmux_ios_close_files(struct client_files *files) ++{ ++ struct client_file *cf, *next; ++ RB_FOREACH_SAFE(cf, client_files, files, next) { ++ if (cf->event) bufferevent_free(cf->event); ++ if (cf->fd >= 0) close(cf->fd); ++ file_free(cf); ++ } ++} +--- a/tty.c ++++ b/tty.c +@@ -104,7 +104,7 @@ + int + tty_init(struct tty *tty, struct client *c) + { +- if (!isatty(c->fd)) ++ if (!(c->flags & CLIENT_IOS_TERMINAL)) + return (-1); + + memset(tty, 0, sizeof *tty); +@@ -115,8 +115,7 @@ + tty->fg = tty->bg = -1; + tty->mouse_last_pane = -1; + +- if (tcgetattr(c->fd, &tty->tio) != 0) +- return (-1); ++ /* ios_system owns terminal mode; no kernel termios is claimed. */ + return (0); + } + +@@ -127,7 +126,12 @@ + struct winsize ws; + u_int sx, sy, xpixel, ypixel; + +- if (ioctl(c->fd, TIOCGWINSZ, &ws) != -1) { ++ struct environ_entry *cols = environ_find(c->environ, "COLUMNS"); ++ struct environ_entry *rows = environ_find(c->environ, "LINES"); ++ memset(&ws, 0, sizeof ws); ++ ws.ws_col = cols && cols->value ? strtonum(cols->value, 1, 9999, NULL) : 80; ++ ws.ws_row = rows && rows->value ? strtonum(rows->value, 1, 9999, NULL) : 24; ++ if (ws.ws_col && ws.ws_row) { + sx = ws.ws_col; + if (sx == 0) { + sx = 80; +@@ -252,7 +256,7 @@ + size_t size = EVBUFFER_LENGTH(tty->out); + int nwrite; + +- nwrite = evbuffer_write(tty->out, c->fd); ++ nwrite = evbuffer_write(tty->out, c->out_fd); + if (nwrite == -1) + return; + log_debug("%s: wrote %d bytes (of %zu)", c->name, nwrite, size); +@@ -292,7 +296,7 @@ + if (tty->in == NULL) + fatal("out of memory"); + +- event_set(&tty->event_out, c->fd, EV_WRITE, tty_write_callback, tty); ++ event_set(&tty->event_out, c->out_fd, EV_WRITE, tty_write_callback, tty); + tty->out = evbuffer_new(); + if (tty->out == NULL) + fatal("out of memory"); +@@ -341,6 +345,7 @@ + u_int i; + + setblocking(c->fd, 0); ++ setblocking(c->out_fd, 0); + event_add(&tty->event_in, NULL); + + memcpy(&tio, &tty->tio, sizeof tio); +@@ -351,8 +356,7 @@ + ECHOKE|ISIG); + tio.c_cc[VMIN] = 1; + tio.c_cc[VTIME] = 0; +- if (tcsetattr(c->fd, TCSANOW, &tio) == 0) +- tcflush(c->fd, TCOFLUSH); ++ /* The host forwards raw terminal bytes on this logical terminal. */ + + if (options_get_number(global_options, "clear-on-attach")) { + tty_putcode(tty, TTYC_SMCUP); +@@ -474,10 +478,9 @@ + * because the fd is invalid. Things like ssh -t can easily leave us + * with a dead tty. + */ +- if (ioctl(c->fd, TIOCGWINSZ, &ws) == -1) +- return; +- if (tcsetattr(c->fd, TCSANOW, &tty->tio) == -1) +- return; ++ memset(&ws, 0, sizeof ws); ++ ws.ws_col = tty->sx; ++ ws.ws_row = tty->sy; + + tty_raw(tty, tty_term_string_ii(tty->term, TTYC_CSR, 0, ws.ws_row - 1)); + if (tty_acs_needed(tty)) +@@ -518,6 +521,7 @@ + tty_raw(tty, "\033[?2031l"); + + setblocking(c->fd, 1); ++ setblocking(c->out_fd, 1); + } + + void +@@ -582,7 +586,7 @@ + + slen = strlen(s); + for (i = 0; i < 5; i++) { +- n = write(c->fd, s, slen); ++ n = write(c->out_fd, s, slen); + if (n >= 0) { + s += n; + slen -= n; +--- a/spawn.c ++++ b/spawn.c +@@ -464,20 +464,7 @@ + } + new_wp->flags &= ~PANE_EMPTY; + +- /* Store current working directory and change to new one. */ +- if (getcwd(path, sizeof path) != NULL) { +- if (chdir(new_wp->cwd) == 0) +- actual_cwd = new_wp->cwd; +- else if (home != NULL && chdir(home) == 0) +- actual_cwd = home; +- else if (chdir("/") == 0) +- actual_cwd = "/"; +- } +- +- /* Fork the new process. */ +- new_wp->pid = fdforkpty(ptm_fd, &new_wp->fd, new_wp->tty, NULL, &ws); +- if (new_wp->pid == -1) { +- xasprintf(cause, "fork failed: %s", strerror(errno)); ++ if (tmux_ios_spawn_pane(sc, new_wp, child, &ws, cause) != 0) { + new_wp->fd = -1; + if (~sc->flags & SPAWN_RESPAWN) { + server_client_remove_pane(new_wp); +@@ -488,91 +475,6 @@ + environ_free(child); + return (NULL); + } +- +- /* +- * In the parent process, everything is done now. Change the working +- * directory back. +- */ +- if (new_wp->pid != 0) { +- if (actual_cwd != NULL && +- chdir(path) != 0 && +- (home == NULL || chdir(home) != 0)) +- chdir("/"); +- goto complete; +- } +- +-#if defined(HAVE_SYSTEMD) && defined(ENABLE_CGROUPS) +- /* +- * Move the child process into a new cgroup for systemd-oomd isolation. +- */ +- if (systemd_move_to_new_cgroup(cause) < 0) { +- log_debug("%s: moving pane to new cgroup failed: %s", +- __func__, *cause); +- free (*cause); +- } +-#endif +- /* +- * Child process. Set PWD to the working directory. +- */ +- if (actual_cwd != NULL) +- environ_set(child, "PWD", 0, "%s", actual_cwd); +- +- /* +- * Update terminal escape characters from the session if available and +- * force VERASE to tmux's backspace. +- */ +- if (tcgetattr(STDIN_FILENO, &now) != 0) +- _exit(1); +- if (s->tio != NULL) +- memcpy(now.c_cc, s->tio->c_cc, sizeof now.c_cc); +- key = options_get_number(global_options, "backspace"); +- if (key >= 0x7f) +- now.c_cc[VERASE] = '\177'; +- else +- now.c_cc[VERASE] = key; +-#ifdef IUTF8 +- now.c_iflag |= IUTF8; +-#endif +- if (tcsetattr(STDIN_FILENO, TCSANOW, &now) != 0) +- _exit(1); +- +- /* Clean up file descriptors and signals and update the environment. */ +- proc_clear_signals(server_proc, 1); +- closefrom(STDERR_FILENO + 1); +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- log_close(); +- environ_push(child); +- +- /* +- * If given multiple arguments, use execvp(). Copy the arguments to +- * ensure they end in a NULL. +- */ +- if (new_wp->argc != 0 && new_wp->argc != 1) { +- argvp = cmd_copy_argv(new_wp->argc, new_wp->argv); +- execvp(argvp[0], argvp); +- _exit(1); +- } +- +- /* +- * If one argument, pass it to $SHELL -c. Otherwise create a login +- * shell. +- */ +- cp = strrchr(new_wp->shell, '/'); +- if (new_wp->argc == 1) { +- tmp = new_wp->argv[0]; +- if (cp != NULL && cp[1] != '\0') +- xasprintf(&argv0, "%s", cp + 1); +- else +- xasprintf(&argv0, "%s", new_wp->shell); +- execl(new_wp->shell, argv0, "-c", tmp, (char *)NULL); +- _exit(1); +- } +- if (cp != NULL && cp[1] != '\0') +- xasprintf(&argv0, "-%s", cp + 1); +- else +- xasprintf(&argv0, "-%s", new_wp->shell); +- execl(new_wp->shell, argv0, (char *)NULL); +- _exit(1); + + complete: + #ifdef HAVE_UTEMPTER +--- a/window.c ++++ b/window.c +@@ -596,30 +596,8 @@ + void + window_pane_send_resize(struct window_pane *wp, u_int sx, u_int sy) + { +- struct window *w = wp->window; +- struct winsize ws; +- +- if (wp->fd == -1) +- return; +- +- log_debug("%s: %%%u resize to %u,%u", __func__, wp->id, sx, sy); +- +- memset(&ws, 0, sizeof ws); +- ws.ws_col = sx; +- ws.ws_row = sy; +- ws.ws_xpixel = w->xpixel * ws.ws_col; +- ws.ws_ypixel = w->ypixel * ws.ws_row; +- if (ioctl(wp->fd, TIOCSWINSZ, &ws) == -1) +-#ifdef __sun +- /* +- * Some versions of Solaris apparently can return an error when +- * resizing; don't know why this happens, can't reproduce on +- * other platforms and ignoring it doesn't seem to cause any +- * issues. +- */ +- if (errno != EINVAL && errno != ENXIO) +-#endif +- fatal("ioctl failed"); ++ if (wp->fd != -1) ++ tmux_ios_resize_pane(wp, sx, sy); + } + + int +@@ -1567,6 +1545,7 @@ + static void + window_pane_destroy(struct window_pane *wp) + { ++ tmux_ios_release_pane(wp); + window_pane_wait_finish(wp); + spawn_editor_finish(wp); + +--- a/server.c ++++ b/server.c +@@ -106,19 +106,10 @@ + int + server_create_socket(uint64_t flags, char **cause) + { +- struct sockaddr_un sa; +- size_t size; + mode_t mask; + int fd, saved_errno; + +- memset(&sa, 0, sizeof sa); +- sa.sun_family = AF_UNIX; +- size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path); +- if (size >= sizeof sa.sun_path) { +- errno = ENAMETOOLONG; +- goto fail; +- } +- unlink(sa.sun_path); ++ unlink(socket_path); + + if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) + goto fail; +@@ -127,7 +118,7 @@ + mask = umask(S_IXUSR|S_IXGRP|S_IRWXO); + else + mask = umask(S_IXUSR|S_IRWXG|S_IRWXO); +- if (bind(fd, (struct sockaddr *)&sa, sizeof sa) == -1) { ++ if (tmux_ios_socket(fd, socket_path, 1) == -1) { + saved_errno = errno; + umask(mask); + close(fd); +@@ -144,6 +135,8 @@ + } + setblocking(fd, 0); + ++ fputs("ASHELL_TMUX_READY\n", thread_stdout); ++ fflush(thread_stdout); + return (fd); + + fail: +@@ -229,8 +222,6 @@ + server_update_socket(); + if (~flags & CLIENT_NOFORK) + c = server_client_create(fd); +- else +- options_set_number(global_options, "exit-empty", 0); + + if (lockfd >= 0) { + unlink(lockfile); +@@ -514,6 +505,16 @@ + job_check_died(pid, status); + } + ++void ++tmux_ios_pane_exited(struct window_pane *wp, int status) ++{ ++ wp->status = status; ++ wp->flags |= PANE_STATUSREADY|PANE_EXITED; ++ window_pane_wait_finish(wp); ++ spawn_editor_finish(wp); ++ if (window_pane_destroy_ready(wp)) server_destroy_pane(wp, 1); ++} ++ + /* Handle stopped children. */ + static void + server_child_stopped(pid_t pid, int status) +--- a/server-client.c ++++ b/server-client.c +@@ -2710,9 +2710,15 @@ + if (server_client_dispatch_command(c, imsg) != 0) + goto bad; + break; +- case MSG_RESIZE: +- if (datalen != 0) +- goto bad; ++ case MSG_RESIZE: { ++ unsigned size[2]; ++ if (!(c->flags & CLIENT_TERMINAL)) break; ++ if (datalen != sizeof size) goto bad; ++ memcpy(size, imsg->data, sizeof size); ++ if (!size[0] || size[0] > 9999 || !size[1] || size[1] > 9999) goto bad; ++ environ_set(c->environ, "COLUMNS", 0, "%u", size[0]); ++ environ_set(c->environ, "LINES", 0, "%u", size[1]); ++ } + + if (c->flags & CLIENT_CONTROL) + break; +@@ -3035,9 +3041,10 @@ + tty_resize(&c->tty); + c->flags |= CLIENT_TERMINAL; + } +- if (c->out_fd != -1) +- close(c->out_fd); +- c->out_fd = -1; ++ if (!(c->flags & CLIENT_TERMINAL)) { ++ if (c->out_fd != -1) close(c->out_fd); ++ c->out_fd = -1; ++ } + } + if (c->flags & (CLIENT_CONTROL|CLIENT_TERMINAL)) + events_fire_client("client-created", c); +--- a/job.c ++++ b/job.c +@@ -74,167 +74,8 @@ + job_complete_cb completecb, job_free_cb freecb, void *data, int flags, + int sx, int sy) + { +- struct job *job; +- struct environ *env; +- pid_t pid; +- int nullfd, out[2], master, do_close = 1; +- const char *home, *shell; +- sigset_t set, oldset; +- struct winsize ws; +- char **argvp, tty[TTY_NAME_MAX], *argv0; +- struct options *oo; +- +- /* +- * Do not set TERM during .tmux.conf (second argument here), it is nice +- * to be able to use if-shell to decide on default-terminal based on +- * outside TERM. +- */ +- env = environ_for_session(s, !cfg_finished); +- if (e != NULL) +- environ_copy(e, env); +- +- if (~flags & JOB_DEFAULTSHELL) +- shell = _PATH_BSHELL; +- else { +- if (s != NULL) +- oo = s->options; +- else +- oo = global_s_options; +- shell = options_get_string(oo, "default-shell"); +- if (!checkshell(shell)) +- shell = _PATH_BSHELL; +- } +- argv0 = shell_argv0(shell, 0); +- +- sigfillset(&set); +- sigprocmask(SIG_BLOCK, &set, &oldset); +- +- if (flags & JOB_PTY) { +- memset(&ws, 0, sizeof ws); +- ws.ws_col = sx; +- ws.ws_row = sy; +- pid = fdforkpty(ptm_fd, &master, tty, NULL, &ws); +- } else { +- if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, out) != 0) +- goto fail; +- pid = fork(); +- } +- if (cmd == NULL) { +- cmd_log_argv(argc, argv, "%s:", __func__); +- log_debug("%s: cwd=%s, shell=%s", __func__, +- cwd == NULL ? "" : cwd, shell); +- } else { +- log_debug("%s: cmd=%s, cwd=%s, shell=%s", __func__, cmd, +- cwd == NULL ? "" : cwd, shell); +- } +- +- switch (pid) { +- case -1: +- if (~flags & JOB_PTY) { +- close(out[0]); +- close(out[1]); +- } +- goto fail; +- case 0: +- proc_clear_signals(server_proc, 1); +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- +- if (cwd != NULL) { +- if (chdir(cwd) == 0) +- environ_set(env, "PWD", 0, "%s", cwd); +- else if ((home = find_home()) != NULL && chdir(home) == 0) +- environ_set(env, "PWD", 0, "%s", home); +- else if (chdir("/") == 0) +- environ_set(env, "PWD", 0, "/"); +- else +- _exit(1); +- } +- +- environ_push(env); +- environ_free(env); +- +- if (~flags & JOB_PTY) { +- if (dup2(out[1], STDIN_FILENO) == -1) +- _exit(1); +- do_close = do_close && out[1] != STDIN_FILENO; +- if (dup2(out[1], STDOUT_FILENO) == -1) +- _exit(1); +- do_close = do_close && out[1] != STDOUT_FILENO; +- if (flags & JOB_SHOWSTDERR) { +- if (dup2(out[1], STDERR_FILENO) == -1) +- _exit(1); +- do_close = do_close && out[1] != STDERR_FILENO; +- } else { +- nullfd = open(_PATH_DEVNULL, O_RDWR); +- if (nullfd == -1) +- _exit(1); +- if (dup2(nullfd, STDERR_FILENO) == -1) +- _exit(1); +- if (nullfd != STDERR_FILENO) +- close(nullfd); +- } +- if (do_close) +- close(out[1]); +- close(out[0]); +- } +- closefrom(STDERR_FILENO + 1); +- +- if (cmd != NULL) { +- if (flags & JOB_DEFAULTSHELL) +- setenv("SHELL", shell, 1); +- execl(shell, argv0, "-c", cmd, (char *)NULL); +- _exit(1); +- } else { +- argvp = cmd_copy_argv(argc, argv); +- execvp(argvp[0], argvp); +- _exit(1); +- } +- } +- +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- environ_free(env); +- free(argv0); +- +- job = xcalloc(1, sizeof *job); +- job->state = JOB_RUNNING; +- job->flags = flags; +- +- if (cmd != NULL) +- job->cmd = xstrdup(cmd); +- else +- job->cmd = cmd_stringify_argv(argc, argv); +- job->pid = pid; +- if (flags & JOB_PTY) +- strlcpy(job->tty, tty, sizeof job->tty); +- job->status = 0; +- +- LIST_INSERT_HEAD(&all_jobs, job, entry); +- +- job->updatecb = updatecb; +- job->completecb = completecb; +- job->freecb = freecb; +- job->data = data; +- +- if (~flags & JOB_PTY) { +- close(out[1]); +- job->fd = out[0]; +- } else +- job->fd = master; +- setblocking(job->fd, 0); +- +- job->event = bufferevent_new(job->fd, job_read_callback, +- job_write_callback, job_error_callback, job); +- if (job->event == NULL) +- fatalx("out of memory"); +- bufferevent_enable(job->event, EV_READ|EV_WRITE); +- +- log_debug("run job %p: %s, pid %ld", job, job->cmd, (long)job->pid); +- return (job); +- +-fail: +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- environ_free(env); +- free(argv0); ++ /* Background shell jobs need a separate worker adapter. */ ++ errno = ENOTSUP; + return (NULL); + } + +--- a/proc.c ++++ b/proc.c +@@ -374,25 +374,7 @@ + pid_t + proc_fork_and_daemon(int *fd) + { +- pid_t pid; +- int pair[2]; +- +- if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0) +- fatal("socketpair failed"); +- switch (pid = fork()) { +- case -1: +- fatal("fork failed"); +- case 0: +- close(pair[0]); +- *fd = pair[1]; +- if (daemon(1, 0) != 0) +- fatal("daemon failed"); +- return (0); +- default: +- close(pair[1]); +- *fd = pair[0]; +- return (pid); +- } ++ fatalx("tmux engine must be started by its worker host (-D or -N)"); + } + + uid_t +--- a/cmd-new-session.c ++++ b/cmd-new-session.c +@@ -197,9 +197,8 @@ + "unset $TMUX to force"); + goto fail; + } +- if (tcgetattr(c->fd, &tio) != 0) +- fatal("tcgetattr failed"); +- tiop = &tio; ++ /* Terminal settings belong to ios_system's logical terminal. */ ++ tiop = NULL; + } else + tiop = NULL; + +--- a/cmd-pipe-pane.c ++++ b/cmd-pipe-pane.c +@@ -55,139 +55,8 @@ + static enum cmd_retval + cmd_pipe_pane_exec(struct cmd *self, struct cmdq_item *item) + { +- struct args *args = cmd_get_args(self); +- struct cmd_find_state *target = cmdq_get_target(item); +- struct client *tc = cmdq_get_target_client(item); +- struct window_pane *wp = target->wp; +- struct session *s = target->s; +- struct winlink *wl = target->wl; +- struct window_pane_offset *wpo = &wp->pipe_offset; +- char *cmd; +- int old_fd, pipe_fd[2], null_fd, in, out; +- struct format_tree *ft; +- sigset_t set, oldset; +- +- /* Do nothing if pane is dead. */ +- if (window_pane_exited(wp)) { +- cmdq_error(item, "target pane has exited"); +- return (CMD_RETURN_ERROR); +- } +- +- /* Destroy the old pipe. */ +- old_fd = wp->pipe_fd; +- if (wp->pipe_fd != -1) { +- bufferevent_free(wp->pipe_event); +- close(wp->pipe_fd); +- wp->pipe_fd = -1; +- +- if (window_pane_destroy_ready(wp)) { +- server_destroy_pane(wp, 1); +- return (CMD_RETURN_NORMAL); +- } +- } +- +- /* If no pipe command, that is enough. */ +- if (args_count(args) == 0 || *args_string(args, 0) == '\0') +- return (CMD_RETURN_NORMAL); +- +- /* +- * With -o, only open the new pipe if there was no previous one. This +- * allows a pipe to be toggled with a single key, for example: +- * +- * bind ^p pipep -o 'cat >>~/output' +- */ +- if (args_has(args, 'o') && old_fd != -1) +- return (CMD_RETURN_NORMAL); +- +- /* What do we want to do? Neither -I or -O is -O. */ +- if (args_has(args, 'I')) { +- in = 1; +- out = args_has(args, 'O'); +- } else { +- in = 0; +- out = 1; +- } +- +- /* Open the new pipe. */ +- if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_fd) != 0) { +- cmdq_error(item, "socketpair error: %s", strerror(errno)); +- return (CMD_RETURN_ERROR); +- } +- +- /* Expand the command. */ +- ft = format_create(cmdq_get_client(item), item, FORMAT_NONE, 0); +- format_defaults(ft, tc, s, wl, wp); +- cmd = format_expand_time(ft, args_string(args, 0)); +- format_free(ft); +- +- /* Fork the child. */ +- sigfillset(&set); +- sigprocmask(SIG_BLOCK, &set, &oldset); +- switch ((wp->pipe_pid = fork())) { +- case -1: +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- cmdq_error(item, "fork error: %s", strerror(errno)); +- +- close(pipe_fd[0]); +- close(pipe_fd[1]); +- free(cmd); +- return (CMD_RETURN_ERROR); +- case 0: +- /* Child process. */ +- proc_clear_signals(server_proc, 1); +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- close(pipe_fd[0]); +- +- if (setpgid(0, 0) == -1) +- _exit(1); +- +- null_fd = open(_PATH_DEVNULL, O_WRONLY); +- if (out) { +- if (dup2(pipe_fd[1], STDIN_FILENO) == -1) +- _exit(1); +- } else { +- if (dup2(null_fd, STDIN_FILENO) == -1) +- _exit(1); +- } +- if (in) { +- if (dup2(pipe_fd[1], STDOUT_FILENO) == -1) +- _exit(1); +- if (pipe_fd[1] != STDOUT_FILENO) +- close(pipe_fd[1]); +- } else { +- if (dup2(null_fd, STDOUT_FILENO) == -1) +- _exit(1); +- } +- if (dup2(null_fd, STDERR_FILENO) == -1) +- _exit(1); +- closefrom(STDERR_FILENO + 1); +- +- execl(_PATH_BSHELL, "sh", "-c", cmd, (char *) NULL); +- _exit(1); +- default: +- /* Parent process. */ +- sigprocmask(SIG_SETMASK, &oldset, NULL); +- close(pipe_fd[1]); +- +- wp->pipe_fd = pipe_fd[0]; +- memcpy(wpo, &wp->offset, sizeof *wpo); +- +- setblocking(wp->pipe_fd, 0); +- wp->pipe_event = bufferevent_new(wp->pipe_fd, +- cmd_pipe_pane_read_callback, +- cmd_pipe_pane_write_callback, +- cmd_pipe_pane_error_callback, +- wp); +- if (wp->pipe_event == NULL) +- fatalx("out of memory"); +- if (out) +- bufferevent_enable(wp->pipe_event, EV_WRITE); +- if (in) +- bufferevent_enable(wp->pipe_event, EV_READ); +- +- free(cmd); +- return (CMD_RETURN_NORMAL); +- } ++ cmdq_error(item, "pipe-pane requires an unsupported background worker adapter"); ++ return (CMD_RETURN_ERROR); + } + + static void +--- a/compat/fdforkpty.c ++++ b/compat/fdforkpty.c +@@ -17,6 +17,7 @@ + #include + + #include ++#include + + #include "compat.h" + +@@ -30,5 +31,6 @@ + fdforkpty(__unused int ptmfd, int *master, char *name, struct termios *tio, + struct winsize *ws) + { +- return (forkpty(master, name, tio, ws)); ++ errno = ENOTSUP; ++ return (-1); + } +--- a/input.c ++++ b/input.c +@@ -1035,7 +1035,18 @@ + new_data = window_pane_get_new_data(wp, &wp->offset, &new_size); + if (new_size != 0) + wp->last_output_time = time(NULL); +- input_parse_buffer(wp, new_data, new_size); ++ /* Reuse Herdr's socket ONLCR rule, including CRLF across read chunks. */ ++ u_char *normalized = xreallocarray(NULL, new_size ? new_size : 1, 2); ++ size_t length = 0; ++ for (size_t i = 0; i < new_size; i++) { ++ u_char byte = ((u_char *)new_data)[i]; ++ if (byte == '\n' && !wp->ios_previous_cr) ++ normalized[length++] = '\r'; ++ normalized[length++] = byte; ++ wp->ios_previous_cr = byte == '\r'; ++ } ++ input_parse_buffer(wp, normalized, length); ++ free(normalized); + window_pane_update_used_data(wp, &wp->offset, new_size); + } + diff --git a/tmux/phone-check.sh b/tmux/phone-check.sh new file mode 100755 index 00000000..dc280844 --- /dev/null +++ b/tmux/phone-check.sh @@ -0,0 +1,51 @@ +#!/bin/dash +set -eu +test "$#" -eq 1 || exit 64 +directory=$1 +case "$directory" in /*) ;; *) exit 64 ;; esac +mkdir -p "$directory" +# A short-lived detached client may finish during the initial terminal resize. +label="short-client-${directory##*/}" +tmux -L "$label" new-session -d -s short-client 'cat' +# Ordinary control clients detach and reattach with status 0. +printf 'detach-client\n' | tmux -L "$label" -C attach-session -t short-client > "$directory/control-first" || { tmux -L "$label" kill-server || :; exit 1; } +printf 'detach-client\n' | tmux -L "$label" -C attach-session -t short-client > "$directory/control-second" || { tmux -L "$label" kill-server || :; exit 1; } +echo TMUX_CONTROL_CLIENT_STATUS_PASS +# Respawning a live pane must release its old worker before allocating another. +i=0 +while test "$i" -lt 12; do + tmux -L "$label" respawn-pane -k -t short-client cat || { tmux -L "$label" kill-server || :; exit 1; } + i=$((i + 1)) +done +tmux -L "$label" send-keys -t short-client RESPAWN_LIVE_OK Enter || { tmux -L "$label" kill-server || :; exit 1; } +sleep 1 +tmux -L "$label" capture-pane -p -t short-client > "$directory/respawn-capture" || { tmux -L "$label" kill-server || :; exit 1; } +grep -q RESPAWN_LIVE_OK "$directory/respawn-capture" || { tmux -L "$label" kill-server || :; exit 1; } +echo TMUX_RESPAWN_LIVE_PASS +tmux -L "$label" kill-server +echo TMUX_SHORT_CLIENT_STATUS_PASS +tmux-acceptance "$directory/interactive" +# Warm the worker pool before measuring repeated CLI descriptor ownership. +tmux -V > "$directory/version" +sleep 1 +set -- /dev/fd/* +baseline=$# +i=0 +while test "$i" -lt 20; do + tmux -V < "$directory/version" > "$directory/file" + cat "$directory/version" | tmux -V > "$directory/pipe-in" + tmux -V | cat > "$directory/pipe-out" + version=$(tmux -V) + test "$version" = 'tmux 3.8' + if tmux -N -L tmux-acceptance-absent list-sessions > "$directory/error" 2>&1; then + echo 'FAIL missing-server exit status' + exit 1 + fi + i=$((i + 1)) +done +sleep 1 +set -- /dev/fd/* +final=$# +echo "descriptor glob warm=$baseline final=$final" +test "$final" -le "$((baseline + 2))" +echo TMUX_PHONE_CHECK_PASS diff --git a/tmux/socket-check.sh b/tmux/socket-check.sh new file mode 100755 index 00000000..f67b9141 --- /dev/null +++ b/tmux/socket-check.sh @@ -0,0 +1,94 @@ +#!/bin/sh +set -eu +unset TMUX TMUX_TMPDIR +# Exercise the shipped CLI with an iOS container-length socket path. +root=${1:?Usage: socket-check.sh /absolute/long-prefix} +case "$root" in /*) ;; *) exit 64 ;; esac +socket="$root/tmux.sock" +[ "${#socket}" -gt 104 ] || { echo 'Socket test prefix must exceed 104 bytes' >&2; exit 64; } +[ ! -e "$root" ] || { echo 'Socket test requires an unused directory' >&2; exit 64; } +mkdir -p "${root%/*}" +tmux -S "$socket" -V > "$root.version" +IFS= read -r version < "$root.version" +[ "$version" = 'tmux 3.8' ] +[ ! -e "$root" ] +tmux -S "$socket" -h > "$root.help" 2>&1 +[ ! -e "$root" ] +echo TMUX_SOCKETLESS_VERSION_HELP_PASS +echo "TMUX_SOCKET_PATH_BYTES=${#socket}" +mkdir -p "$root" +tmux -S "$socket" start-server \; set-option -g exit-empty off +tmux -S "$socket" show-options -gv exit-empty > "$root.option" +IFS= read -r option < "$root.option" +[ "$option" = off ] +tmux -S "$socket" kill-server +if tmux -N -S "$socket" show-options -g >/dev/null 2>&1; then + echo 'Server still accepts commands after kill-server' >&2 + exit 1 +fi +# Restart without removing the stale socket, using the stock command abbreviation. +tmux -S "$socket" new-s -d -s restarted 'cat' +tmux -S "$socket" has-session -t restarted +tmux -S "$socket" show-options -gv exit-empty > "$root/restart.option" +IFS= read -r option < "$root/restart.option" +[ "$option" = on ] +tmux -S "$socket" kill-session -t restarted +attempt=0 +while tmux -N -S "$socket" show-options -g >/dev/null 2>&1; do + [ "$attempt" -lt 10 ] || { echo 'Empty server did not exit' >&2; exit 1; } + attempt=$((attempt + 1)) + sleep 1 +done +echo TMUX_EXIT_EMPTY_PASS +echo TMUX_STALE_SOCKET_RESTART_PASS +rm -f "$socket" +echo TMUX_LONG_SOCKET_PASS +label="socketcheck-${root##*/}" +tmux -L "$label" start-server \; set-option -g exit-empty off +tmux -L "$label" display-message -p '#{socket_path}' > "$root/default.socket" +IFS= read -r socket_path < "$root/default.socket" +case "$socket_path" in + *"/tmux-ios/$label") ;; + *) cat "$root/default.socket" >&2; exit 1 ;; +esac +tmux -L "$label" show-options -gv exit-empty > "$root/default.option" +IFS= read -r option < "$root/default.option" +[ "$option" = off ] +tmux -L "$label" kill-server +if tmux -N -L "$label" show-options -g >/dev/null 2>&1; then + echo 'Default server still accepts commands after kill-server' >&2 + exit 1 +fi +case "$socket_path" in "$HOME"/*) echo 'Default socket is inside the host container' >&2; exit 1 ;; esac +rm -f "$socket_path" +echo TMUX_LONG_DEFAULT_SOCKET_PASS +# Use an owned temporary domain: never stop the user's real default server. +TMUX_TMPDIR="$root" +export TMUX_TMPDIR +# The unsuffixed command retains the stock default socket name. +tmux start-server \; set-option -g exit-empty off +tmux display-message -p '#{socket_path}' > "$root/stock-default.socket" +IFS= read -r socket_path < "$root/stock-default.socket" +[ "$socket_path" = "$root/tmux-ios/default" ] +tmux show-options -gv exit-empty > "$root/stock-default.option" +IFS= read -r option < "$root/stock-default.option" +[ "$option" = off ] +# Explicit -L wins over inherited TMUX; empty/malformed TMUX uses default. +TMUX="$root/missing,0,0" tmux -L default show-options -gv exit-empty > "$root/explicit-default.option" +TMUX= tmux show-options -gv exit-empty > "$root/empty-tmux.option" +TMUX=',0,0' tmux show-options -gv exit-empty > "$root/malformed-tmux.option" +for result in explicit-default empty-tmux malformed-tmux; do + IFS= read -r option < "$root/$result.option" + [ "$option" = off ] +done +echo TMUX_SOCKET_SELECTION_PASS +tmux kill-server +if tmux -N show-options -g >/dev/null 2>&1; then + echo 'Stock default server still accepts commands after kill-server' >&2 + exit 1 +fi +case "$socket_path" in "$HOME"/*) echo 'Default socket is inside the host container' >&2; exit 1 ;; esac +rm -f "$socket_path" +echo TMUX_ISOLATED_DEFAULT_SOCKET_PASS +rm -f "$root.version" "$root.help" "$root.option" "$root/default.socket" "$root/default.option" "$root/stock-default.socket" "$root/stock-default.option" "$root/explicit-default.option" "$root/empty-tmux.option" "$root/malformed-tmux.option" "$root/restart.option" +rmdir "$root/tmux-ios" "$root" diff --git a/tmux/sources.sha256 b/tmux/sources.sha256 new file mode 100644 index 00000000..293c2a67 --- /dev/null +++ b/tmux/sources.sha256 @@ -0,0 +1,2 @@ +e79c699c7e949dccd0a4a125e17b8d1261e311b16979dbc8eb34542f3966d82e tmux-3.8.tar.gz +f7e9383b8c0baa81b687e5b5eecc01beefaf1b19b64151d95ed61647fe7a315c libevent-2.1.13-stable.tar.gz diff --git a/tmux/terminal.terminfo b/tmux/terminal.terminfo new file mode 100644 index 00000000..abb74b68 --- /dev/null +++ b/tmux/terminal.terminfo @@ -0,0 +1,66 @@ +# Reconstructed via infocmp from file: /usr/share/terminfo/73/screen.xterm-256color +screen.xterm-256color|GNU Screen with xterm using 256 colors, + OTbs, am, bw, km, mc5i, mir, msgr, npc, xenl, AX, XT, + colors#256, cols#80, it#8, lines#24, pairs#32767, + acsc=``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~, + bel=^G, blink=\E[5m, bold=\E[1m, cbt=\E[Z, civis=\E[?25l, + clear=\E[H\E[2J, cnorm=\E[?12l\E[?25h, cr=^M, + csr=\E[%i%p1%d;%p2%dr, cub=\E[%p1%dD, cub1=^H, + cud=\E[%p1%dB, cud1=^J, cuf=\E[%p1%dC, cuf1=\E[C, + cup=\E[%i%p1%d;%p2%dH, cuu=\E[%p1%dA, cuu1=\E[A, + cvvis=\E[?12;25h, dch=\E[%p1%dP, dch1=\E[P, dim=\E[2m, + dl=\E[%p1%dM, dl1=\E[M, ech=\E[%p1%dX, ed=\E[J, el=\E[K, + el1=\E[1K, flash=\E[?5h$<100/>\E[?5l, home=\E[H, + hpa=\E[%i%p1%dG, ht=^I, hts=\EH, ich=\E[%p1%d@, + il=\E[%p1%dL, il1=\E[L, ind=^J, indn=\E[%p1%dS, + is2=\E[!p\E[?3;4l\E[4l\E>, kDC=\E[3;2~, kEND=\E[1;2F, + kHOM=\E[1;2H, kLFT=\E[1;2D, kRIT=\E[1;2C, kb2=\EOE, kbs=^H, + kcbt=\E[Z, kcub1=\EOD, kcud1=\EOB, kcuf1=\EOC, kcuu1=\EOA, + kdch1=\E[3~, kend=\E[4~, kent=\EOM, kf1=\EOP, kf10=\E[21~, + kf11=\E[23~, kf12=\E[24~, kf13=\E[1;2P, kf14=\E[1;2Q, + kf15=\E[1;2R, kf16=\E[1;2S, kf17=\E[15;2~, kf18=\E[17;2~, + kf19=\E[18;2~, kf2=\EOQ, kf20=\E[19;2~, kf21=\E[20;2~, + kf22=\E[21;2~, kf23=\E[23;2~, kf24=\E[24;2~, + kf25=\E[1;5P, kf26=\E[1;5Q, kf27=\E[1;5R, kf28=\E[1;5S, + kf29=\E[15;5~, kf3=\EOR, kf30=\E[17;5~, kf31=\E[18;5~, + kf32=\E[19;5~, kf33=\E[20;5~, kf34=\E[21;5~, + kf35=\E[23;5~, kf36=\E[24;5~, kf37=\E[1;6P, kf38=\E[1;6Q, + kf39=\E[1;6R, kf4=\EOS, kf40=\E[1;6S, kf41=\E[15;6~, + kf42=\E[17;6~, kf43=\E[18;6~, kf44=\E[19;6~, + kf45=\E[20;6~, kf46=\E[21;6~, kf47=\E[23;6~, + kf48=\E[24;6~, kf49=\E[1;3P, kf5=\E[15~, kf50=\E[1;3Q, + kf51=\E[1;3R, kf52=\E[1;3S, kf53=\E[15;3~, kf54=\E[17;3~, + kf55=\E[18;3~, kf56=\E[19;3~, kf57=\E[20;3~, + kf58=\E[21;3~, kf59=\E[23;3~, kf6=\E[17~, kf60=\E[24;3~, + kf61=\E[1;4P, kf62=\E[1;4Q, kf63=\E[1;4R, kf7=\E[18~, + kf8=\E[19~, kf9=\E[20~, khome=\E[1~, kich1=\E[2~, + kind=\E[1;2B, kmous=\E[M, knp=\E[6~, kpp=\E[5~, + kri=\E[1;2A, mc0=\E[i, mc4=\E[4i, mc5=\E[5i, op=\E[39;49m, + rc=\E8, rev=\E[7m, ri=\EM, rin=\E[%p1%dT, rmacs=\E(B, + rmam=\E[?7l, rmcup=\E[?1049l, rmir=\E[4l, rmkx=\E[?1l\E>, + rmm=\E[?1034l, rmso=\E[27m, rmul=\E[24m, rs1=\Ec, + rs2=\E[!p\E[?3;4l\E[4l\E>, sc=\E7, + setab=\E[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m, + setaf=\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m, + sgr=%?%p9%t\E(0%e\E(B%;\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p1%p3%|%t;7%;%?%p4%t;5%;%?%p5%t;2%;m, + sgr0=\E(B\E[m, smacs=\E(0, smam=\E[?7h, smcup=\E[?1049h, + smir=\E[4h, smkx=\E[?1h\E=, smm=\E[?1034h, smso=\E[7m, + smul=\E[4m, tbc=\E[3g, u6=\E[%i%d;%dR, u7=\E[6n, + u8=\E[?1;2c, u9=\E[c, vpa=\E[%i%p1%dd, Cr=\E]112\007, + Cs=\E]12;%p1%s\007, Ms=\E]52;%p1%s;%p2%s\007, + Se=\E[2 q, Ss=\E[%p1%d q, kDC3=\E[3;3~, kDC4=\E[3;4~, + kDC5=\E[3;5~, kDC6=\E[3;6~, kDC7=\E[3;7~, kDN=\E[1;2B, + kDN3=\E[1;3B, kDN4=\E[1;4B, kDN5=\E[1;5B, kDN6=\E[1;6B, + kDN7=\E[1;7B, kEND3=\E[1;3F, kEND4=\E[1;4F, + kEND5=\E[1;5F, kEND6=\E[1;6F, kEND7=\E[1;7F, + kHOM3=\E[1;3H, kHOM4=\E[1;4H, kHOM5=\E[1;5H, + kHOM6=\E[1;6H, kHOM7=\E[1;7H, kIC3=\E[2;3~, kIC4=\E[2;4~, + kIC5=\E[2;5~, kIC6=\E[2;6~, kIC7=\E[2;7~, kLFT3=\E[1;3D, + kLFT4=\E[1;4D, kLFT5=\E[1;5D, kLFT6=\E[1;6D, + kLFT7=\E[1;7D, kNXT3=\E[6;3~, kNXT4=\E[6;4~, + kNXT5=\E[6;5~, kNXT6=\E[6;6~, kNXT7=\E[6;7~, + kPRV3=\E[5;3~, kPRV4=\E[5;4~, kPRV5=\E[5;5~, + kPRV6=\E[5;6~, kPRV7=\E[5;7~, kRIT3=\E[1;3C, + kRIT4=\E[1;4C, kRIT5=\E[1;5C, kRIT6=\E[1;6C, + kRIT7=\E[1;7C, kUP=\E[1;2A, kUP3=\E[1;3A, kUP4=\E[1;4A, + kUP5=\E[1;5A, kUP6=\E[1;6A, kUP7=\E[1;7A, From 872f30fab7cc37da7e1b402e964f2128e75b4b1e Mon Sep 17 00:00:00 2001 From: demrom <47463752+demrom@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:49:07 +0300 Subject: [PATCH 16/16] Point the noPython libpng reference at the downloaded xcframework --- a-Shell.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/a-Shell.xcodeproj/project.pbxproj b/a-Shell.xcodeproj/project.pbxproj index 9e57fbed..df512acb 100644 --- a/a-Shell.xcodeproj/project.pbxproj +++ b/a-Shell.xcodeproj/project.pbxproj @@ -2871,7 +2871,7 @@ A22600000000000000000002 /* codex/codex.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = codex/codex.xcframework; sourceTree = SOURCE_ROOT; }; A53600000000000000000001 /* freetype.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = freetype.xcframework; path = xcfs/.build/artifacts/xcfs/freetype/freetype.xcframework; sourceTree = SOURCE_ROOT; }; A53600000000000000000002 /* harfbuzz.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = harfbuzz.xcframework; path = xcfs/.build/artifacts/xcfs/harfbuzz/harfbuzz.xcframework; sourceTree = SOURCE_ROOT; }; - A53600000000000000000003 /* libpng.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = libpng.xcframework; path = "cpython/Python-aux/libpng.xcframework"; sourceTree = SOURCE_ROOT; }; + A53600000000000000000003 /* libpng.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = libpng.xcframework; path = xcfs/.build/artifacts/xcfs/libpng/libpng.xcframework; sourceTree = SOURCE_ROOT; }; A59100000000000000000004 /* Relay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Relay.swift; sourceTree = ""; }; A83EA8C808E52262F507587D /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; AE1100000000000000000002 /* helix/helix.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = helix/helix.xcframework; sourceTree = SOURCE_ROOT; };