From e778836788b70c54e6187ab87ae8fb571c375c41 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 21:53:58 -0500 Subject: [PATCH 1/2] Retire GTK on macOS now that AppKit passes The AppKit provider passes its contract against a real window server session on both hosted architectures, 93 checks each, so the macOS GTK path has nothing left to do. It was also never viable: a GTK process on macOS never runs -[NSApplication run], and AppKit answers accessibility requests from the main run loop, so every accessibility query against one fails -- including the application element's own role -- and the process is invisible to assistive technology and to directed input. Removed: the macOS half of the GTK provider, the private provider build, runtime and directed-probe scripts with their control tests, the provider lock file, and the macos-gtk-provider workflow. ui_runtime.cpp is now the Linux provider only, and since CMake selects Win32 on Windows and AppKit on macOS it carries no platform conditionals at all; the remaining conditionals were removed by evaluating them rather than by editing line ranges. docs/standard-library/ui.md no longer asks macOS users for NIL_UI_GTK_DIRECTORY and a GTK runtime, and platform support records the AppKit result. Linux is unchanged at 572 registered, 0 failed and 3 environment skips. Co-Authored-By: Claude Opus 5 --- .github/workflows/macos-gtk-provider.yml | 121 ---- docs/platform-support.md | 7 +- docs/standard-library/ui.md | 39 +- nilcompiler/src/ui_runtime.cpp | 123 +--- notebook/2026-11-04-macos-parity-plan.md | 42 ++ scripts/ci/macos-gtk-directed-probes.mm | 478 ------------- scripts/ci/macos-gtk-directed-probes.py | 423 ------------ scripts/ci/macos-gtk-provider-lock.json | 405 ----------- scripts/ci/macos-gtk-provider-smoke.mm | 341 ---------- scripts/ci/macos-gtk-provider.py | 668 ------------------- scripts/ci/macos-gtk-runtime.py | 341 ---------- scripts/ci/test_macos_gtk_directed_probes.py | 301 --------- scripts/ci/test_macos_gtk_provider.py | 297 --------- scripts/ci/test_macos_gtk_runtime.py | 157 ----- 14 files changed, 72 insertions(+), 3671 deletions(-) delete mode 100644 .github/workflows/macos-gtk-provider.yml delete mode 100644 scripts/ci/macos-gtk-directed-probes.mm delete mode 100644 scripts/ci/macos-gtk-directed-probes.py delete mode 100644 scripts/ci/macos-gtk-provider-lock.json delete mode 100644 scripts/ci/macos-gtk-provider-smoke.mm delete mode 100644 scripts/ci/macos-gtk-provider.py delete mode 100644 scripts/ci/macos-gtk-runtime.py delete mode 100644 scripts/ci/test_macos_gtk_directed_probes.py delete mode 100644 scripts/ci/test_macos_gtk_provider.py delete mode 100644 scripts/ci/test_macos_gtk_runtime.py diff --git a/.github/workflows/macos-gtk-provider.yml b/.github/workflows/macos-gtk-provider.yml deleted file mode 100644 index 9c142601..00000000 --- a/.github/workflows/macos-gtk-provider.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: macOS GTK development checks - -"on": - workflow_dispatch: - inputs: - architecture: - description: Native private provider architecture - type: choice - options: [both, x86_64, arm64] - default: both - -permissions: - contents: read - -concurrency: - group: macos-gtk-provider-${{ github.ref }}-${{ inputs.architecture }} - cancel-in-progress: false - -# Build an isolated GTK prefix and exercise its public API and product runtime. -# No Homebrew/global Python updates, SDK activation or release publication. -jobs: - provider: - name: macOS ${{ matrix.host.arch }} private GTK - runs-on: ${{ matrix.host.runner }} - timeout-minutes: 50 - strategy: - fail-fast: false - max-parallel: 2 - matrix: - host: ${{ fromJSON(inputs.architecture == 'arm64' && '[{"runner":"macos-15","arch":"arm64"}]' || inputs.architecture == 'x86_64' && '[{"runner":"macos-15-intel","arch":"x86_64"}]' || '[{"runner":"macos-15-intel","arch":"x86_64"},{"runner":"macos-15","arch":"arm64"}]') }} - defaults: - run: - shell: bash - env: - NIL_CI_ARCH: ${{ matrix.host.arch }} - PYTHONDONTWRITEBYTECODE: "1" - HOMEBREW_NO_AUTO_UPDATE: "1" - HOMEBREW_NO_INSTALL_CLEANUP: "1" - steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - with: - persist-credentials: false - - name: Check private provider controls - timeout-minutes: 2 - run: | - mkdir -p build/macos-gtk-evidence - set -o pipefail - python3 -B scripts/ci/test_macos_gtk_provider.py -v \ - 2>&1 | tee build/macos-gtk-evidence/controls.log - python3 -B scripts/ci/test_macos_gtk_runtime.py -v \ - 2>&1 | tee build/macos-gtk-evidence/runtime-controls.log - python3 -B scripts/ci/test_macos_gtk_directed_probes.py -v \ - 2>&1 | tee build/macos-gtk-evidence/directed-controls.log - - name: Build pinned provider and run owned public-API smoke - id: provider - timeout-minutes: 32 - run: | - set -o pipefail - python3 -B scripts/ci/macos-gtk-provider.py \ - --output "$GITHUB_WORKSPACE/build/macos-gtk-evidence/provider" \ - --work-dir "$RUNNER_TEMP/nil-private-gtk" \ - --revision "$GITHUB_SHA" --architecture "$NIL_CI_ARCH" \ - 2>&1 | tee build/macos-gtk-evidence/provider.log - - name: Check product runtime against the sealed private provider - timeout-minutes: 4 - run: | - set -o pipefail - python3 -B scripts/ci/macos-gtk-runtime.py \ - --provider-report "$GITHUB_WORKSPACE/build/macos-gtk-evidence/provider/report.json" \ - --output "$GITHUB_WORKSPACE/build/macos-gtk-evidence/runtime" \ - --work-dir "$RUNNER_TEMP/nil-gtk-runtime" \ - --revision "$GITHUB_SHA" --architecture "$NIL_CI_ARCH" \ - 2>&1 | tee build/macos-gtk-evidence/runtime.log - - name: Observe directed input to an owned GTK child - if: ${{ !cancelled() && steps.provider.outcome == 'success' }} - timeout-minutes: 4 - run: | - set -o pipefail - python3 -B scripts/ci/macos-gtk-directed-probes.py \ - --provider-report "$GITHUB_WORKSPACE/build/macos-gtk-evidence/provider/report.json" \ - --output "$GITHUB_WORKSPACE/build/macos-gtk-evidence/directed" \ - --work-dir "$RUNNER_TEMP/nil-gtk-directed" \ - --revision "$GITHUB_SHA" --architecture "$NIL_CI_ARCH" \ - 2>&1 | tee build/macos-gtk-evidence/directed.log - - name: Seal complete or partial provider evidence - if: always() - timeout-minutes: 2 - run: | - python3 -B - <<'PY' - import hashlib, json, os, stat, subprocess - from pathlib import Path - root = Path('build/macos-gtk-evidence'); root.mkdir(parents=True, exist_ok=True) - files = {} - for path in sorted(root.rglob('*')): - mode = path.lstat().st_mode - assert stat.S_ISDIR(mode) or stat.S_ISREG(mode), str(path) - if stat.S_ISREG(mode): - digest = hashlib.sha256() - with path.open('rb') as stream: - while block := stream.read(1024**2): digest.update(block) - files[path.relative_to(root).as_posix()] = { - 'bytes': path.stat().st_size, 'sha256': digest.hexdigest()} - dirty = subprocess.check_output(['git', 'status', '--porcelain', '--untracked-files=no'], - text=True, timeout=15) - (root / 'evidence.json').write_text(json.dumps({ - 'revision': os.environ['GITHUB_SHA'], 'architecture': os.environ['NIL_CI_ARCH'], - 'run_id': os.environ['GITHUB_RUN_ID'], 'attempt': os.environ['GITHUB_RUN_ATTEMPT'], - 'source_unchanged': not dirty, 'tracked_changes': dirty, - 'files': files, 'qualification': False, 'sdk_replaced': False}, indent=2) + '\n') - assert not dirty - PY - - name: Upload private provider evidence - if: always() - timeout-minutes: 4 - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: macos-gtk-provider-${{ matrix.host.arch }}-${{ github.sha }}-${{ github.run_attempt }} - path: build/macos-gtk-evidence/ - if-no-files-found: error - retention-days: 14 - compression-level: 1 diff --git a/docs/platform-support.md b/docs/platform-support.md index b577e799..3bbcf382 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -175,8 +175,11 @@ the complete admission rules. interactive session -- provider contract, lifecycle release observation, the Matrix desktop suite and the interaction suite that drives real keyboard input -- while a session without an interactive window station still skips. - macOS UI/provider support and live desktop acceptance remain open; AppKit - replaces the retired GTK-on-macOS work. Both hosted Mac architectures + On macOS the provider is AppKit: its published contract passes against a + real window server session on both hosted architectures, 93 checks each. + Language-level macOS desktop acceptance remains open. GTK on macOS is + retired, because a GTK process there never runs the AppKit event loop and so + has no accessibility hierarchy at all. Both hosted Mac architectures now pass the prerequisite GLib, Cairo-Quartz and HarfBuzz/CoreText compile, link and runtime checks, plus exact own-process AppKit key dispatch, view delivery and window closure. Directed keyboard input to a verified child and diff --git a/docs/standard-library/ui.md b/docs/standard-library/ui.md index cac8456a..a02c4155 100644 --- a/docs/standard-library/ui.md +++ b/docs/standard-library/ui.md @@ -57,23 +57,28 @@ prove a desktop is usable. Win32 supplies no box or grid container, so the provider owns the layout pass for rows, columns and grids; sizes therefore come from measuring text with the system message font rather than from the toolkit. -The macOS source provider requires `NIL_UI_GTK_DIRECTORY` to name an existing -absolute trusted directory containing `libgtk-4.1.dylib`, -`libgobject-2.0.0.dylib` and `libglib-2.0.0.dylib`. Curated symlinks may point to -the selected external runtime files. Resolved symbols and GTK's direct core -dependency lookups must match those selected files. There is no implicit -current-directory or `PATH` lookup, and the provider does not change loader -settings. GTK remains an external prerequisite; this does not create a portable -GTK bundle or validate every transitive dependency of an embedding host. - -On macOS, creation and polling must run on the process main thread, including -the first GTK initialization. The provider requires the native Macos/Quartz -display backend. Ordinary interpreter, JIT and native entry routes use the main -thread; UI behavior through these routes still needs the desktop acceptance -campaign. DAP currently executes the debuggee on a worker, so DAP with macOS UI -is outside this port. Pausing a text/JSON debug session also does not automatically -pump window events. The recorded private toolkit profile uses Cairo rendering; -other renderer and accessibility configurations remain unqualified. +macOS needs no external toolkit either. The provider is AppKit, so +`available with nothing` is always true there and GTK is neither used nor +loaded; `NIL_UI_GTK_DIRECTORY` has no meaning on macOS. Window creation +requires a window server session and returns a display error without one. +Because the provider calls Cocoa and CoreGraphics directly, every linked +program carries those frameworks, which is why they appear in the Darwin link +lines alongside the runtime. + +GTK is no longer a macOS provider. A GTK process on macOS never runs +`-[NSApplication run]`, and AppKit answers accessibility requests from the main +run loop, so such a process has no accessibility hierarchy at all: every +accessibility query against it fails, including the application element's own +role, which makes it invisible to assistive technology and to directed input. + +On macOS, creation and polling must run on the process main thread, which is +where AppKit requires its windows to be used. Ordinary interpreter, JIT and +native entry routes use the main thread; UI behaviour through these routes +still needs the desktop acceptance campaign. DAP currently executes the +debuggee on a worker, so DAP with macOS UI is outside this port, and pausing a +text or JSON debug session does not automatically pump window events. AppKit +supplies no box or grid container, so, as on Win32, the provider owns the +layout pass and sizes come from each control's fitting size. ## Windows and widgets diff --git a/nilcompiler/src/ui_runtime.cpp b/nilcompiler/src/ui_runtime.cpp index 66f1d4e9..a8f15ac8 100644 --- a/nilcompiler/src/ui_runtime.cpp +++ b/nilcompiler/src/ui_runtime.cpp @@ -2,6 +2,9 @@ * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. * SPDX-License-Identifier: MIT */ +// GTK 4 provider for the ui.v1 contract, and the Linux provider only: CMake +// selects Win32 on Windows and AppKit on macOS, so this translation unit is +// never compiled elsewhere and carries no platform conditionals. #include "ui_runtime.hpp" #include "ui_runtime_shared.hpp" @@ -15,15 +18,7 @@ #include #include #include -#if defined(__linux__) || defined(__APPLE__) #include -#if defined(__APPLE__) -#include -#include -#include -#include -#endif -#endif namespace ny::ui { namespace { @@ -38,35 +33,6 @@ using ClosureNotify = void (*)(void *, GClosure *); enum ConnectFlags { connect_default = 0 }; -#if defined(__APPLE__) -// Darwin has no ambient GTK runtime. A trusted provider directory names the -// three exact ABI files; curated aliases may select canonical external files. -std::filesystem::path gtk_directory() { - const char *selected = std::getenv("NIL_UI_GTK_DIRECTORY"); - if (!selected || !*selected || std::strlen(selected) > 4096) return {}; - const std::filesystem::path path(selected); - std::error_code error; - if (!path.is_absolute() || !std::filesystem::is_directory(path, error) || error) return {}; - const auto canonical = std::filesystem::canonical(path, error); - return error ? std::filesystem::path{} : canonical; -} - -std::filesystem::path gtk_library(const std::filesystem::path &directory, const char *name) { - std::error_code error; - const auto file = std::filesystem::canonical(directory / name, error); - if (error || !std::filesystem::is_regular_file(file, error) || error) return {}; - return file; -} - -bool gtk_symbol_matches(void *symbol, const std::filesystem::path &expected) { - Dl_info info{}; - if (!symbol || !dladdr(symbol, &info) || !info.dli_fname) return false; - const std::filesystem::path path(info.dli_fname); - if (!path.is_absolute()) return false; - std::error_code error; - return std::filesystem::equivalent(path, expected, error) && !error; -} -#endif struct Api { bool loaded = false; @@ -132,13 +98,7 @@ struct Api { #define DECLARE_SYMBOL(result, name, arguments) result (*name) arguments = nullptr; UI_SYMBOLS(DECLARE_SYMBOL) #undef DECLARE_SYMBOL -#if defined(__APPLE__) - void *(*gdk_display_get_default)() = nullptr; - unsigned long (*gdk_macos_display_get_type)() = nullptr; - int (*g_type_check_instance_is_a)(void *, unsigned long) = nullptr; -#endif Api() noexcept { -#if defined(__linux__) // Keep these libraries loaded: GTK owns process-wide types, callbacks and // caches which must not outlive their code. No display is opened here. void *gtk = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); @@ -153,70 +113,6 @@ struct Api { UI_SYMBOLS(LOAD_SYMBOL) #undef LOAD_SYMBOL loaded = gtk_get_major_version() == 4; -#elif defined(__APPLE__) - unavailable = "GTK 4 provider is unavailable; set NIL_UI_GTK_DIRECTORY to an absolute trusted macOS GTK 4 runtime directory"; - try { - const auto directory = gtk_directory(); - if (directory.empty()) { - unavailable = "GTK 4 provider is unavailable: NIL_UI_GTK_DIRECTORY must name an existing absolute directory"; - return; - } - const auto gtk_path = gtk_library(directory, "libgtk-4.1.dylib"); - const auto object_path = gtk_library(directory, "libgobject-2.0.0.dylib"); - const auto glib_path = gtk_library(directory, "libglib-2.0.0.dylib"); - if (gtk_path.empty() || object_path.empty() || glib_path.empty()) { - unavailable = "GTK 4 provider is unavailable: the selected directory must contain the GTK 4, GObject and GLib dylib set"; - return; - } - // Keep all handles for process lifetime, including incomplete attempts: - // registered toolkit types/callbacks must never outlive their code. - // Inspect an already loaded selected stack before introducing another - // core library. RTLD_NOLOAD cannot bring a competing provider into it. - void *existing_gtk = dlopen(gtk_path.c_str(), RTLD_NOLOAD | RTLD_NOW | RTLD_LOCAL); - void *existing_object = dlopen(object_path.c_str(), RTLD_NOLOAD | RTLD_NOW | RTLD_LOCAL); - if ((existing_gtk && - (!gtk_symbol_matches(dlsym(existing_gtk, "gtk_get_major_version"), gtk_path) || - !gtk_symbol_matches(dlsym(existing_gtk, "g_object_ref"), object_path) || - !gtk_symbol_matches(dlsym(existing_gtk, "g_signal_connect_data"), object_path) || - !gtk_symbol_matches(dlsym(existing_gtk, "g_main_context_iteration"), glib_path))) || - (existing_object && - (!gtk_symbol_matches(dlsym(existing_object, "g_object_ref"), object_path) || - !gtk_symbol_matches(dlsym(existing_object, "g_main_context_iteration"), glib_path)))) { - unavailable = "GTK 4 provider is unavailable: missing or mismatched macOS symbol in the already loaded dependency stack"; - return; - } - void *glib = dlopen(glib_path.c_str(), RTLD_NOW | RTLD_LOCAL); - void *object = glib ? dlopen(object_path.c_str(), RTLD_NOW | RTLD_LOCAL) : nullptr; - void *gtk = object ? dlopen(gtk_path.c_str(), RTLD_NOW | RTLD_LOCAL) : nullptr; - if (!gtk || !object || !glib) { - unavailable = "GTK 4 provider is unavailable: the selected macOS dylibs or their declared dependencies could not load"; - return; - } - const auto symbol = [&](const char *name) -> void * { - const bool toolkit = std::strncmp(name, "gtk_", 4) == 0 || std::strncmp(name, "gdk_", 4) == 0; - const bool main_context = std::strncmp(name, "g_main_", 7) == 0; - void *owner = toolkit ? gtk : main_context ? glib : object; - const auto &expected = toolkit ? gtk_path : main_context ? glib_path : object_path; - void *value = dlsym(owner, name); - // Also inspect GTK's dependency lookup. Separately opening a selected - // library would not prove that GTK actually resolves that same stack. - if (!gtk_symbol_matches(value, expected) || - !gtk_symbol_matches(dlsym(gtk, name), expected) || - (main_context && !gtk_symbol_matches(dlsym(object, name), glib_path))) return nullptr; - return value; - }; -#define LOAD_SYMBOL(result, name, arguments) \ - name = reinterpret_cast(symbol(#name)); \ - if (!name) { unavailable = "GTK 4 provider is unavailable: missing or mismatched macOS symbol " #name; return; } - UI_SYMBOLS(LOAD_SYMBOL) - LOAD_SYMBOL(void *, gdk_display_get_default, ()) - LOAD_SYMBOL(unsigned long, gdk_macos_display_get_type, ()) - LOAD_SYMBOL(int, g_type_check_instance_is_a, (void *, unsigned long)) -#undef LOAD_SYMBOL - loaded = gtk_get_major_version() == 4; - if (!loaded) unavailable = "GTK 4 provider is unavailable: the selected dylib does not provide GTK major version 4"; - } catch (...) { /* Optional provider failures must not terminate the host. */ } -#endif } #undef UI_SYMBOLS }; @@ -259,10 +155,6 @@ struct Context::Impl : std::enable_shared_from_this { Result check() { if (owner != std::this_thread::get_id()) return failure("context must be used on its creation thread"); if (!active.load()) return failure("context has been closed"); -#if defined(__APPLE__) - // Refuse first initialization and later pumping alike before touching GTK. - if (!pthread_main_np()) return failure("GTK must be used on the process UI thread (macOS main thread)"); -#endif auto &a = api(); bool initialized; { @@ -287,17 +179,8 @@ struct Context::Impl : std::enable_shared_from_this { return success(); } if (!a.gtk_init_check()) { -#if defined(__APPLE__) - return failure("GTK could not open a display; a working macOS Quartz desktop session is required"); -#else return failure("GTK could not open a display; a working Wayland or X11 session is required"); -#endif } -#if defined(__APPLE__) - void *display = a.gdk_display_get_default(); - if (!display || !a.g_type_check_instance_is_a(display, a.gdk_macos_display_get_type())) - return failure("GTK could not open the required macOS Quartz display"); -#endif a.ui_thread = std::this_thread::get_id(); a.initialized = true; return success(); diff --git a/notebook/2026-11-04-macos-parity-plan.md b/notebook/2026-11-04-macos-parity-plan.md index b14b9837..e1b75b33 100644 --- a/notebook/2026-11-04-macos-parity-plan.md +++ b/notebook/2026-11-04-macos-parity-plan.md @@ -2216,3 +2216,45 @@ Reconciliations under `sdk-run-41976360302`: The new product GTK checkpoint is `11c7684`. Both native architectures are running provider/runtime/directed-child acceptance in run `41981658320`. + + +## 2026-11-09: AppKit becomes the macOS provider and GTK-on-macOS is retired + +The AppKit provider passes its published contract against a real window server +session on both hosted architectures, 93 checks each, on its first CI run: +`42552736762` on arm64 and `42552857408` on `macos-15-intel`, both reporting a +live `CGMainDisplayID`. The provider is +`nilcompiler/src/ui_runtime_appkit.mm`, its fixture is +`tests/ui_runtime_appkit_tests.mm`, and +`.github/workflows/macos-appkit-provider.yml` builds only that target with LLVM +off so a cycle costs minutes rather than a full source campaign. + +**Why it passed first time.** There is no Mac here, so the first compile is a +CI run and a careless file costs cycles. Reading it again before spending one +found three defects that each would have cost a round trip: `Context::Impl` is +private to `Context`, so an Objective-C class outside that scope cannot name it +-- the delegate carries a block built inside `Impl` instead, which closes over +a weak reference and takes the access with it; `sizeThatFits:` is UIKit, not +AppKit, so natural sizes come from `NSView fittingSize`; and Objective-C +pointer downcasts are not C++ class casts. The Windows experience also +transferred directly: because the provider calls Cocoa and CoreGraphics rather +than loading them, both were declared on the runtime targets, in nillinker's +POSIX arguments and in the compiler's Darwin link command before the first run, +instead of being rediscovered through failures in tests whose names mention +nothing about linking. + +**GTK on macOS is retired.** The justification is the directed-input evidence +at `8aa60d2`: every accessibility query against a GTK process returned +`kAXErrorCannotComplete`, including the application element's own role and +attribute names, because GTK pumps GLib and never runs `-[NSApplication run]` +while AppKit services those requests from the main run loop. That is +structural, not a probe fault, and it means such a process is invisible to +assistive technology. Removed: the macOS half of the GTK provider, the private +provider build, runtime and directed-probe scripts with their control tests, +the provider lock file and `macos-gtk-provider.yml`. `ui_runtime.cpp` is now +the Linux provider only and carries no platform conditionals, since CMake +selects Win32 on Windows and AppKit on macOS. + +`docs/standard-library/ui.md` no longer tells macOS users to supply +`NIL_UI_GTK_DIRECTORY` and a GTK runtime. Linux is unchanged at 572 registered, +0 failed and 3 environment skips. diff --git a/scripts/ci/macos-gtk-directed-probes.mm b/scripts/ci/macos-gtk-directed-probes.mm deleted file mode 100644 index 7f814465..00000000 --- a/scripts/ci/macos-gtk-directed-probes.mm +++ /dev/null @@ -1,478 +0,0 @@ -// Private GTK directed prerequisite: only one verified child receives input. -// No global posting, permission requests, application enumeration or product UI. -#import -#import -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static constexpr char expectedText[] = "Matrix\t \t "; -static constexpr CGKeyCode keyCodes[] = {46, 0, 17, 15, 34, 7, 48, 49, 48, 49}; -static constexpr guint keyValues[] = {GDK_KEY_M, GDK_KEY_a, GDK_KEY_t, GDK_KEY_r, GDK_KEY_i, GDK_KEY_x, GDK_KEY_Tab, GDK_KEY_space, GDK_KEY_Tab, GDK_KEY_space}; -// XNU11417 proc_info_private.h API layout, also used by process_contract_support.py. -// Public SDKs need not ship the private header. A size mismatch fails compilation. -struct UniqueInfo { uint8_t uuid[16]; uint64_t unique, parent; int32_t version, parentVersion; - uint64_t reserved2, reserved3; }; -struct ProcessInfo { proc_bsdinfo bsd; UniqueInfo unique; }; -static_assert(sizeof(proc_bsdinfo) == 136 && sizeof(UniqueInfo) == 56 && sizeof(ProcessInfo) == 192, - "unsupported macOS process identity layout"); - -static void emit(NSDictionary *value) { - NSError *error = nil; - NSData *data = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingSortedKeys error:&error]; - if (!data || error || data.length > 8192) std::abort(); - std::fwrite(data.bytes, 1, data.length, stdout); std::fputc('\n', stdout); std::fflush(stdout); -} -static bool number(const char *text, uint64_t &result) { - if (!text || !*text || std::strlen(text) > 20) return false; - for (const char *p = text; *p; ++p) if (*p < '0' || *p > '9') return false; - errno = 0; char *end = nullptr; result = std::strtoull(text, &end, 10); - return !errno && end && !*end; -} -static bool nonceValid(const char *s) { - if (!s || std::strlen(s) != 32) return false; - for (size_t i = 0; i < 32; ++i) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return false; - return true; -} -static bool infoFor(pid_t pid, ProcessInfo &info) { - return pid > 0 && proc_pidinfo(pid, 18, 1, &info, sizeof(info)) == sizeof(info) && - info.bsd.pbi_pid == static_cast(pid) && info.unique.unique && - info.bsd.pbi_status >= 1 && info.bsd.pbi_status <= 4; // reject zombie/unknown -} -static bool canonical(const char *path, std::string &value) { - char resolved[PATH_MAX]; if (!realpath(path, resolved)) return false; value = resolved; return true; -} -static NSString *loadedOrigin(const void *symbol) { - Dl_info info{}; std::string path; - if (!dladdr(symbol, &info) || !info.dli_fname || !canonical(info.dli_fname, path) || path.size() > 4096) - @throw [NSException exceptionWithName:@"Origin" reason:@"file-backed provider origin required" userInfo:nil]; - return [NSString stringWithUTF8String:path.c_str()]; -} -struct Target { - pid_t pid = 0, parent = 0; uint64_t unique = 0, version = 0, device = 0, inode = 0, baseSeconds = 0; - std::string executable, nonce; - bool verify() const { - ProcessInfo info{}; char path[PROC_PIDPATHINFO_MAXSIZE]{}; struct stat state{}; - std::string actual; - return parent == getppid() && infoFor(pid, info) && info.bsd.pbi_ppid == static_cast(parent) && - info.unique.unique == unique && static_cast(info.unique.version) == version && - proc_pidpath(pid, path, sizeof(path)) > 0 && canonical(path, actual) && actual == executable && - stat(executable.c_str(), &state) == 0 && S_ISREG(state.st_mode) && - static_cast(state.st_dev) == device && static_cast(state.st_ino) == inode; - } -}; -static bool parseTarget(int argc, const char **argv, Target &target) { - if (argc != 11 || !nonceValid(argv[9])) return false; - uint64_t values[7]{}; - for (int i = 0; i < 6; ++i) if (!number(argv[i + 2], values[i])) return false; - if (!number(argv[10], values[6]) || !values[0] || values[0] > INT32_MAX || !values[3] || values[3] > INT32_MAX || - values[2] > UINT32_MAX || !values[1] || !values[6] || values[6] > (uint64_t{1} << 32)) return false; - target.pid = static_cast(values[0]); target.unique = values[1]; target.version = values[2]; - target.parent = static_cast(values[3]); target.device = values[4]; target.inode = values[5]; - target.baseSeconds = values[6]; target.nonce = argv[9]; - // Parent supplies independently sealed target and driver paths. These need - // not be the same program; only its retained direct child may be targeted. - return canonical(argv[8], target.executable) && target.executable == argv[8]; -} -static CFTypeRef attribute(AXUIElementRef element, CFStringRef key, AXError *status = nullptr) { - CFTypeRef value = nullptr; - const AXError error = AXUIElementCopyAttributeValue(element, key, &value); - if (status) *status = error; - if (error != kAXErrorSuccess) return nullptr; - return value; -} -static bool owner(AXUIElementRef element, pid_t pid) { - pid_t actual = 0; return AXUIElementGetPid(element, &actual) == kAXErrorSuccess && actual == pid; -} -static bool stringAttribute(AXUIElementRef element, CFStringRef key, CFStringRef expected) { - CFTypeRef value = attribute(element, key); - bool ok = value && CFGetTypeID(value) == CFStringGetTypeID() && CFEqual(value, expected); - if (value) CFRelease(value); - return ok; -} -static NSString *expectedTitle(const Target &target) { - return [@"Ny GTK directed " stringByAppendingString:[NSString stringWithUTF8String:target.nonce.c_str()]]; -} -static NSNumber *bounded(CFIndex count) { return @(count < 0 ? 0 : count > 64 ? 64 : count); } -// Bounded selection diagnostics. No inner-widget accessibility is claimed, but -// an application's own window list is AppKit's own contract, so a failure to -// select has to say which half is absent: the process has no AX hierarchy at -// all, the attribute is unsupported, the list is empty, or a candidate differs -// in owner, role or title. Every field is a count, an AXError or a bounded -// category; no observed title or widget text is retained. -static void windowDiagnostics(AXUIElementRef app, const Target &target, NSMutableDictionary *observed) { - AXError error = kAXErrorSuccess; - CFTypeRef role = attribute(app, kAXRoleAttribute, &error); - observed[@"app_role_error"] = @(error); - observed[@"app_role_application"] = @(role && CFGetTypeID(role) == CFStringGetTypeID() && - CFEqual(role, kAXApplicationRole)); - if (role) CFRelease(role); - CFArrayRef names = nullptr; - observed[@"attribute_names_error"] = @(AXUIElementCopyAttributeNames(app, &names)); - const CFIndex total = names ? CFArrayGetCount(names) : 0; - observed[@"attribute_names_count"] = bounded(total); - bool present = false; - for (CFIndex i = 0; i < total; ++i) { - CFTypeRef item = CFArrayGetValueAtIndex(names, i); - if (item && CFGetTypeID(item) == CFStringGetTypeID() && CFEqual(item, kAXWindowsAttribute)) present = true; - } - observed[@"windows_attribute_present"] = @(present); - if (names) CFRelease(names); - // The application's focused window is a separate public attribute; it can be - // available when the window list is not, which would be a real alternative. - CFTypeRef focused = attribute(app, kAXFocusedWindowAttribute, &error); - const bool element = focused && CFGetTypeID(focused) == AXUIElementGetTypeID(); - auto window = element ? static_cast(const_cast(focused)) : nullptr; - const bool samePid = window && owner(window, target.pid); - observed[@"focused_window_error"] = @(error); - observed[@"focused_window_element"] = @(element); - observed[@"focused_window_pid_matches"] = @(samePid); - observed[@"focused_window_title_matches"] = @(samePid && - stringAttribute(window, kAXTitleAttribute, (__bridge CFStringRef)expectedTitle(target))); - if (focused) CFRelease(focused); -} -static AXUIElementRef ownWindow(AXUIElementRef app, const Target &target, NSMutableDictionary *observed) { - windowDiagnostics(app, target, observed); - AXError error = kAXErrorSuccess; - CFTypeRef value = attribute(app, kAXWindowsAttribute, &error); - const bool array = value && CFGetTypeID(value) == CFArrayGetTypeID(); - const CFIndex count = array ? CFArrayGetCount(static_cast(value)) : 0; - observed[@"windows_error"] = @(error); - observed[@"windows_array"] = @(array); - observed[@"windows_count"] = bounded(count); - observed[@"first_role_category"] = @"unavailable"; - unsigned owned = 0, windowRoles = 0, titled = 0; - AXUIElementRef result = nullptr; - if (array && count <= 8) { - NSString *title = expectedTitle(target); - for (CFIndex i = 0; i < count; ++i) { - CFTypeRef item = CFArrayGetValueAtIndex(static_cast(value), i); - if (!item || CFGetTypeID(item) != AXUIElementGetTypeID()) continue; - auto window = static_cast(const_cast(item)); - if (!owner(window, target.pid)) continue; - ++owned; - CFTypeRef role = attribute(window, kAXRoleAttribute); - const bool string = role && CFGetTypeID(role) == CFStringGetTypeID(); - const bool windowRole = string && CFEqual(role, kAXWindowRole); - if (owned == 1) - observed[@"first_role_category"] = !string ? @"unavailable" : windowRole ? @"window" : - CFEqual(role, kAXSheetRole) ? @"sheet" : @"other"; - if (role) CFRelease(role); - if (!windowRole) continue; - ++windowRoles; - if (!stringAttribute(window, kAXTitleAttribute, (__bridge CFStringRef)title)) continue; - ++titled; - if (!result) { CFRetain(window); result = window; } - } - } - observed[@"owned_candidates"] = @(owned); - observed[@"window_role_candidates"] = @(windowRoles); - observed[@"title_candidates"] = @(titled); - // Exactly one verified child window may ever be selected. - if (titled != 1 && result) { CFRelease(result); result = nullptr; } - if (value) CFRelease(value); - return result; -} -static bool focusedField(AXUIElementRef app, AXUIElementRef window, const Target &target, - NSMutableDictionary *observed) { - AXError error = kAXErrorSuccess; - // Retain the previous observation, but keyboard-element focus is not the - // public contract for an application's focused window. - CFTypeRef legacy = attribute(window, kAXFocusedAttribute, &error); - observed[@"legacy_window_error"] = @(error); - observed[@"legacy_window_boolean"] = @(legacy && CFGetTypeID(legacy) == CFBooleanGetTypeID()); - observed[@"legacy_window_value"] = @(legacy && CFEqual(legacy, kCFBooleanTrue)); - if (legacy) CFRelease(legacy); - CFTypeRef focusedWindow = attribute(app, kAXFocusedWindowAttribute, &error); - observed[@"app_window_error"] = @(error); - const bool appElement = focusedWindow && CFGetTypeID(focusedWindow) == AXUIElementGetTypeID(); - const bool appOwner = appElement && owner(static_cast(const_cast(focusedWindow)), target.pid); - const bool appMatch = appOwner && CFEqual(focusedWindow, window); - observed[@"app_window_element"] = @(appElement); - observed[@"app_window_pid_matches"] = @(appOwner); - observed[@"app_window_matches"] = @(appMatch); - if (focusedWindow) CFRelease(focusedWindow); - CFTypeRef field = attribute(app, kAXFocusedUIElementAttribute, &error); - observed[@"field_error"] = @(error); - const bool fieldElement = field && CFGetTypeID(field) == AXUIElementGetTypeID(); - auto element = fieldElement ? static_cast(const_cast(field)) : nullptr; - const bool fieldOwner = element && owner(element, target.pid); - observed[@"field_element"] = @(fieldElement); - observed[@"field_pid_matches"] = @(fieldOwner); - bool roleMatch = false, windowMatch = false; - observed[@"field_role_error"] = @(-1); observed[@"field_window_error"] = @(-1); - observed[@"field_role_category"] = @"unavailable"; - observed[@"field_text_role"] = @NO; observed[@"field_window_element"] = @NO; - observed[@"field_window_pid_matches"] = @NO; observed[@"field_window_matches"] = @NO; - if (fieldOwner && AXUIElementSetMessagingTimeout(element, 1.0f) == kAXErrorSuccess) { - CFTypeRef role = attribute(element, kAXRoleAttribute, &error); - roleMatch = role && CFGetTypeID(role) == CFStringGetTypeID() && CFEqual(role, kAXTextFieldRole); - observed[@"field_role_error"] = @(error); observed[@"field_text_role"] = @(roleMatch); - if (role && CFGetTypeID(role) == CFStringGetTypeID()) - observed[@"field_role_category"] = roleMatch ? @"text_field" : CFEqual(role, kAXTextAreaRole) ? @"text_area" : @"other"; - if (role) CFRelease(role); - CFTypeRef fieldWindow = attribute(element, kAXWindowAttribute, &error); - const bool isElement = fieldWindow && CFGetTypeID(fieldWindow) == AXUIElementGetTypeID(); - const bool samePid = isElement && owner(static_cast(const_cast(fieldWindow)), target.pid); - windowMatch = samePid && CFEqual(fieldWindow, window); - observed[@"field_window_error"] = @(error); observed[@"field_window_element"] = @(isElement); - observed[@"field_window_pid_matches"] = @(samePid); observed[@"field_window_matches"] = @(windowMatch); - if (fieldWindow) CFRelease(fieldWindow); - } - if (field) CFRelease(field); - // AccessKit is disabled in this provider profile. Widget AX exposure is - // diagnostic only; the child proves actual GTK entry focus before readiness. - (void)windowMatch; - return appMatch; -} -static int driver(const char *mode, const Target &target) { - bool identity = target.verify(); - const bool post = CGPreflightPostEventAccess(), ax = AXIsProcessTrusted(); - bool selected = false, focused = false, exactTimestamps = false, pressed = false; - unsigned posted = 0; - NSMutableDictionary *focusObservation = [NSMutableDictionary dictionary]; - NSMutableDictionary *windowObservation = [NSMutableDictionary dictionary]; - AXUIElementRef app = nullptr, window = nullptr; CFTypeRef button = nullptr; - if (identity && post && ax) { - app = AXUIElementCreateApplication(target.pid); - if (app && AXUIElementSetMessagingTimeout(app, 1.0f) == kAXErrorSuccess) - window = ownWindow(app, target, windowObservation); - selected = window != nullptr; - if (selected) { - focused = AXUIElementSetMessagingTimeout(window, 1.0f) == kAXErrorSuccess && - focusedField(app, window, target, focusObservation); - if (!std::strcmp(mode, "keys") && focused) { - exactTimestamps = focused; - for (unsigned i = 0; focused && i < 10; ++i) { - for (unsigned down = 0; down < 2; ++down) { - if (!target.verify()) { identity = false; break; } - CGEventRef event = CGEventCreateKeyboardEvent(nullptr, keyCodes[i], down == 0); - if (!event) { exactTimestamps = false; break; } - UniChar text = static_cast(expectedText[i]); - CGEventKeyboardSetUnicodeString(event, 1, &text); - CGEventSetFlags(event, i == 0 ? kCGEventFlagMaskShift : 0); - const CGEventTimestamp timestamp = (target.baseSeconds + i * 2 + down) * uint64_t{1000000000}; - CGEventSetTimestamp(event, timestamp); - const bool exact = CGEventGetTimestamp(event) == timestamp; - exactTimestamps = exactTimestamps && exact; - if (exact) { CGEventPostToPid(target.pid, event); ++posted; } - CFRelease(event); - if (!exact) break; - } - if (!identity || !exactTimestamps) break; - } - } else if (!std::strcmp(mode, "close") && focused) { - button = attribute(window, kAXCloseButtonAttribute); - if (button && CFGetTypeID(button) == AXUIElementGetTypeID()) { - auto element = static_cast(const_cast(button)); - if (owner(element, target.pid) && stringAttribute(element, kAXRoleAttribute, kAXButtonRole) && target.verify()) - pressed = AXUIElementPerformAction(element, kAXPressAction) == kAXErrorSuccess; - } - } - } - } - if (button) CFRelease(button); - if (window) CFRelease(window); - if (app) CFRelease(app); - const bool success = identity && post && ax && selected && focused && - (!std::strcmp(mode, "keys") ? exactTimestamps && posted == 20 : pressed); - emit(@{@"schema": @1, @"phase": [NSString stringWithUTF8String:mode], @"qualification": @NO, - @"identity_verified": @(identity), @"post_event_access": @(post), @"ax_trusted": @(ax), - @"own_window_selected": @(selected), @"focus_verified": @(focused), @"timestamp_readback": @(exactTimestamps), - @"focus_observation": focusObservation, @"window_observation": windowObservation, - @"base_seconds": @(target.baseSeconds), @"events_posted": @(posted), @"close_action": @(pressed), @"success": @(success)}); - return success ? 0 : 2; -} - - -using Clock = std::chrono::steady_clock; -struct GtkState { - GtkWindow *window = nullptr; - GtkWidget *entry = nullptr, *checkbox = nullptr, *button = nullptr; - GdkSurface *surface = nullptr; - uint64_t baseSeconds = 0; - unsigned eventCount = 0, changed = 0, toggled = 0, clicked = 0, closed = 0; - unsigned changedAt[6]{}, toggledAt = 0, clickedAt = 0; - bool invalid = false; - struct Event { guint keyval, keycode, modifiers; guint32 timestamp; int type; bool release, ownSurface, matches; } events[20]{}; -}; -static void keyObservation(GtkEventControllerKey *controller, guint keyval, guint keycode, - GdkModifierType modifiers, bool release, gpointer data) { - auto &state = *static_cast(data); - GdkEvent *event = gtk_event_controller_get_current_event(GTK_EVENT_CONTROLLER(controller)); - if (!event || state.eventCount >= 20) { state.invalid = true; return; } - const unsigned index = state.eventCount, key = index / 2; - const guint expectedModifiers = key == 0 ? GDK_SHIFT_MASK : 0; - const guint32 expectedTime = static_cast((state.baseSeconds + index) * 1000); - const bool own = gdk_event_get_surface(event) == state.surface; - const bool match = own && keyval == keyValues[key] && keycode == keyCodes[key] && - modifiers == expectedModifiers && gdk_event_get_modifier_state(event) == expectedModifiers && - gdk_event_get_time(event) == expectedTime && release == bool(index % 2) && - gdk_event_get_event_type(event) == (release ? GDK_KEY_RELEASE : GDK_KEY_PRESS); - state.events[state.eventCount++] = {keyval, keycode, static_cast(modifiers), gdk_event_get_time(event), static_cast(gdk_event_get_event_type(event)), release, own, match}; - if (!match) state.invalid = true; -} -static gboolean pressed(GtkEventControllerKey *controller, guint keyval, guint keycode, - GdkModifierType modifiers, gpointer data) { - keyObservation(controller, keyval, keycode, modifiers, false, data); return FALSE; -} -static void released(GtkEventControllerKey *controller, guint keyval, guint keycode, - GdkModifierType modifiers, gpointer data) { - keyObservation(controller, keyval, keycode, modifiers, true, data); -} -static void changed(GtkEditable *entry, gpointer data) { - auto &state = *static_cast(data); ++state.changed; - if (state.changed > 6) { state.invalid = true; return; } - state.changedAt[state.changed - 1] = state.eventCount; - if (state.eventCount != state.changed * 2 - 1 || !state.events[state.eventCount - 1].matches || - std::string(gtk_editable_get_text(entry)) != std::string("Matrix", state.changed)) - state.invalid = true; // Never log unknown input content. -} -static void toggled(GtkCheckButton *button, gpointer data) { - auto &state = *static_cast(data); ++state.toggled; - state.toggledAt = state.eventCount; - if (state.toggled != 1 || (state.eventCount != 15 && state.eventCount != 16) || - !state.events[state.eventCount - 1].matches || !gtk_check_button_get_active(button)) state.invalid = true; -} -static void clicked(GtkButton *, gpointer data) { - auto &state = *static_cast(data); ++state.clicked; state.clickedAt = state.eventCount; - if (state.clicked != 1 || (state.eventCount != 19 && state.eventCount != 20) || - !state.events[state.eventCount - 1].matches) state.invalid = true; -} -static gboolean closeRequest(GtkWindow *, gpointer data) { - ++static_cast(data)->closed; - return FALSE; // Normal GTK close handling must actually destroy the native window. -} -static bool entryFocused(const GtkState &state) { - GtkWidget *focus = gtk_window_get_focus(state.window); - return focus && (focus == state.entry || gtk_widget_is_ancestor(focus, state.entry)); -} -static int gtkTarget(const char *nonce) { - const auto start = Clock::now(), limit = start + std::chrono::seconds(25); - GtkState state; - bool ready = false, typed = false, expired = false, exception = false, initialized = false; - __strong NSWindow *native = nil; - @try { - if (!pthread_main_np() || g_strcmp0(g_getenv("GDK_BACKEND"), "macos") || - g_strcmp0(g_getenv("GSK_RENDERER"), "cairo") || !gtk_init_check()) - @throw [NSException exceptionWithName:@"GTKInitialization" reason:@"private GTK main-thread profile unavailable" userInfo:nil]; - initialized = true; - if (g_list_model_get_n_items(gtk_window_get_toplevels()) != 0) - @throw [NSException exceptionWithName:@"GTKWindow" reason:@"unexpected existing windows" userInfo:nil]; - const double uptime = std::floor(NSProcessInfo.processInfo.systemUptime); - if (!std::isfinite(uptime) || uptime < 33 || uptime > 4294967296.0) - @throw [NSException exceptionWithName:@"Timestamp" reason:@"bounded uptime required" userInfo:nil]; - state.baseSeconds = static_cast(uptime) - 32; - state.window = GTK_WINDOW(gtk_window_new()); g_object_ref(state.window); - const std::string title = std::string("Ny GTK directed ") + nonce; - gtk_window_set_title(state.window, title.c_str()); gtk_window_set_default_size(state.window, 360, 180); - GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); - state.entry = gtk_entry_new(); state.checkbox = gtk_check_button_new_with_label("Enable setting"); - state.button = gtk_button_new_with_label("Finish probe"); - gtk_box_append(GTK_BOX(box), state.entry); gtk_box_append(GTK_BOX(box), state.checkbox); - gtk_box_append(GTK_BOX(box), state.button); gtk_window_set_child(state.window, box); - g_signal_connect(state.entry, "changed", G_CALLBACK(changed), &state); - g_signal_connect(state.checkbox, "toggled", G_CALLBACK(toggled), &state); - g_signal_connect(state.button, "clicked", G_CALLBACK(clicked), &state); - g_signal_connect(state.window, "close-request", G_CALLBACK(closeRequest), &state); - GtkEventController *controller = gtk_event_controller_key_new(); - gtk_event_controller_set_propagation_phase(controller, GTK_PHASE_CAPTURE); - g_signal_connect(controller, "key-pressed", G_CALLBACK(pressed), &state); - g_signal_connect(controller, "key-released", G_CALLBACK(released), &state); - gtk_widget_add_controller(GTK_WIDGET(state.window), controller); - gtk_window_present(state.window); - if (!gtk_widget_grab_focus(state.entry)) - @throw [NSException exceptionWithName:@"GTKFocus" reason:@"entry focus request failed" userInfo:nil]; - while (Clock::now() < limit) { - g_main_context_iteration(nullptr, FALSE); - if (!ready && gtk_widget_get_mapped(GTK_WIDGET(state.window))) { - state.surface = gtk_native_get_surface(GTK_NATIVE(state.window)); - if (!state.surface || !GDK_IS_MACOS_SURFACE(state.surface)) - @throw [NSException exceptionWithName:@"GTKSurface" reason:@"Macos surface required" userInfo:nil]; - native = (__bridge NSWindow *)gdk_macos_surface_get_native_window(GDK_MACOS_SURFACE(state.surface)); - if (native && native.windowNumber > 0 && [NSApp.windows containsObject:native] && native.visible && - native.keyWindow && NSApp.active && entryFocused(state)) { - ready = true; - emit(@{@"schema": @1, @"phase": @"ready", @"qualification": @NO, @"pid": @(getpid()), - @"window_number": @(native.windowNumber), @"main_thread": @YES, @"gtk_entry_focused": @YES, - @"active": @YES, @"key_window": @YES, @"base_seconds": @(state.baseSeconds), - // Read-only: GTK drives its own GLib loop rather than -[NSApplication run], - // and AppKit services accessibility requests from the main run loop. - // BOOL is signed char on x86_64 and bool on arm64; box a C++ bool so the - // frame carries JSON true/false on both hosts rather than 1/0 on one. - @"app_running": @(static_cast(NSApp.running)), - @"activation_policy": @(static_cast(NSApp.activationPolicy)), - @"gtk_header": [NSString stringWithFormat:@"%u.%u.%u", GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION], - @"gtk_runtime": [NSString stringWithFormat:@"%u.%u.%u", gtk_get_major_version(), gtk_get_minor_version(), gtk_get_micro_version()], - @"origins": @{@"gtk": loadedOrigin(reinterpret_cast(>k_init_check)), - @"gobject": loadedOrigin(reinterpret_cast(&g_object_ref)), - @"glib": loadedOrigin(reinterpret_cast(&g_main_context_iteration)), - @"gio": loadedOrigin(reinterpret_cast(&g_list_model_get_n_items))}}); - } - } - if (!typed && ready && state.eventCount == 20 && state.changed == 6 && state.clicked == 1 && state.toggled == 1 && - !state.invalid && !std::strcmp(gtk_editable_get_text(GTK_EDITABLE(state.entry)), "Matrix") && - gtk_check_button_get_active(GTK_CHECK_BUTTON(state.checkbox))) { - typed = true; - emit(@{@"schema": @1, @"phase": @"typed", @"qualification": @NO, @"text": @"Matrix", - @"changed": @6, @"toggled": @1, @"clicked": @1, @"events": @20, @"checked": @YES}); - } - if (state.invalid || state.closed) break; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - expired = Clock::now() >= limit; - } @catch (NSException *) { exception = true; } - const bool genuineClose = initialized && typed && state.closed == 1 && - g_list_model_get_n_items(gtk_window_get_toplevels()) == 0 && native && !native.visible; - bool cleaned = false; - @try { - if (state.window) gtk_window_destroy(state.window); - while (initialized && Clock::now() < start + std::chrono::seconds(29) && - (g_list_model_get_n_items(gtk_window_get_toplevels()) != 0 || (native && native.visible))) { - g_main_context_iteration(nullptr, FALSE); - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - cleaned = !initialized || (g_list_model_get_n_items(gtk_window_get_toplevels()) == 0 && (!native || !native.visible)); - if (state.window) { g_object_unref(state.window); state.window = nullptr; } - } @catch (NSException *) { cleaned = false; } - NSMutableArray *events = [NSMutableArray array]; - for (unsigned i = 0; i < state.eventCount; ++i) { - const auto &value = state.events[i]; - [events addObject:@{@"index": @(i), @"keyval": @(value.keyval), @"keycode": @(value.keycode), - @"modifiers": @(value.modifiers), @"time_ms": @(value.timestamp), @"event_type": @(value.type), @"release": @(value.release), - @"own_surface": @(value.ownSurface), @"matches": @(value.matches)}]; - } - NSMutableArray *changedAt = [NSMutableArray array]; - for (unsigned value : state.changedAt) [changedAt addObject:@(value)]; - const bool success = ready && typed && genuineClose && cleaned && !expired && !exception && !state.invalid; - emit(@{@"schema": @1, @"phase": @"final", @"qualification": @NO, @"ready": @(ready), @"typed": @(typed), - @"gdk_events": events, @"changed": @(state.changed), @"clicked": @(state.clicked), @"toggled": @(state.toggled), - @"changed_at": changedAt, @"toggled_at": @(state.toggledAt), @"clicked_at": @(state.clickedAt), - @"close_requests": @(state.closed), @"native_close": @(genuineClose), @"cleanup_verified": @(cleaned), - @"expired": @(expired), @"exception": @(exception), @"invalid": @(state.invalid), @"success": @(success)}); - return success ? 0 : 2; -} -int main(int argc, const char **argv) { - @autoreleasepool { - if (argc == 3 && !std::strcmp(argv[1], "target") && nonceValid(argv[2])) return gtkTarget(argv[2]); - if (argc > 1 && (!std::strcmp(argv[1], "keys") || !std::strcmp(argv[1], "close"))) { - Target value; if (parseTarget(argc, argv, value)) return driver(argv[1], value); - } - std::fputs("invalid private GTK directed-probe arguments\n", stderr); return 2; - } -} diff --git a/scripts/ci/macos-gtk-directed-probes.py b/scripts/ci/macos-gtk-directed-probes.py deleted file mode 100644 index 6cb55977..00000000 --- a/scripts/ci/macos-gtk-directed-probes.py +++ /dev/null @@ -1,423 +0,0 @@ -#!/usr/bin/env python3 -"""Bounded real GTK input/close to one retained child; no language or SDK qualification.""" -from __future__ import annotations -import argparse -import hashlib -import importlib.util -import json -import os -from pathlib import Path -import platform -import re -import secrets -import shlex -import stat -import subprocess -import sys -import time - -ROOT = Path(__file__).resolve().parents[2] -TOTAL_SECONDS = 180 -RESERVE_SECONDS = 20 -MAX_OUTPUT = 256 * 1024 - - -def require(value, message): - if not value: - raise ValueError(message) - - -def load(path, name): - spec = importlib.util.spec_from_file_location(name, path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def paths(output, work, root=ROOT): - require(not output.is_symlink() and not work.is_symlink(), 'Output/work may not be symlinks') - output, work, root = output.resolve(), work.resolve(), root.resolve() - require(not output.exists() and not work.exists(), 'Output/work must be fresh') - require(output != work and output not in work.parents and work not in output.parents, 'Output/work overlap') - require(work != root and root not in work.parents and work not in root.parents, 'Work must be outside checkout') - require(output != root and output not in root.parents and - (root not in output.parents or root/'build' in output.parents), 'Checkout evidence must be under build') - return output, work - - -def record(path, deadline): - original = Path(path); path = original.resolve(strict=True) - descriptor = os.open(path, os.O_RDONLY | os.O_NONBLOCK | getattr(os, 'O_NOFOLLOW', 0)) - digest = hashlib.sha256(); total = 0 - with os.fdopen(descriptor, 'rb') as stream: - before = os.fstat(stream.fileno()) - require(stat.S_ISREG(before.st_mode) and before.st_size <= 512 * 1024**2, 'Unbounded/nonregular input') - while block := stream.read(1024**2): - require(time.monotonic() < deadline, 'Seal deadline expired') - total += len(block); require(total <= 512 * 1024**2, 'Input grew beyond bound'); digest.update(block) - after = os.fstat(stream.fileno()) - identity = lambda s: (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_mode) - require(identity(before) == identity(after) == identity(path.stat()) and total == after.st_size and - original.resolve(strict=True) == path, 'Input changed while sealing') - return dict(path=str(original), canonical_path=str(path), bytes=total, sha256=digest.hexdigest(), - device=after.st_dev, inode=after.st_ino, mode=stat.S_IMODE(after.st_mode)) - - -def decode(raw, phase): - require(len(raw) <= 8192, 'Native frame exceeds bound') - def pairs(items): - result = {} - for key, value in items: - require(key not in result, 'Duplicate JSON key'); result[key] = value - return result - value = json.loads(raw, object_pairs_hook=pairs) - require(type(value) is dict and type(value.get('schema')) is int and value['schema'] == 1 and - value.get('qualification') is False and value.get('phase') == phase, 'Native frame scope/phase mismatch') - return value - - -KEYCODES = (46, 0, 17, 15, 34, 7, 48, 49, 48, 49) -KEYVALS = (ord('M'), ord('a'), ord('t'), ord('r'), ord('i'), ord('x'), 0xff09, 32, 0xff09, 32) -ALIASES = {'gtk': 'libgtk-4.1.dylib', 'gobject': 'libgobject-2.0.0.dylib', - 'glib': 'libglib-2.0.0.dylib', 'gio': 'libgio-2.0.0.dylib'} - - -def ready_frame(value, pid, aliases): - require(type(value.get('pid')) is int and value['pid'] == pid and type(value.get('window_number')) is int and - 0 < value['window_number'] < 2**31 and all(value.get(key) is True for key in - ('active', 'key_window', 'gtk_entry_focused', 'main_thread')), 'Target readiness missing') - require(type(value.get('base_seconds')) is int and 0 < value['base_seconds'] <= 2**32, - 'Bounded exact timestamp origin required') - require(value.get('gtk_header') == value.get('gtk_runtime') == '4.18.6', 'GTK version differs') - # Observations, not requirements: GTK runs its own loop, and whether AppKit - # is running one is exactly what a selection failure has to be read against. - require(type(value.get('app_running')) is bool and type(value.get('activation_policy')) is int and - 0 <= value['activation_policy'] <= 2, 'Bounded target application loop observation required') - require(value.get('origins') == {key: str(aliases[name]) for key, name in ALIASES.items()}, - 'Actual GTK/GLib/GObject/GIO origins differ from validated provider') - - -def typed_frame(value): - require(value.get('text') == 'Matrix' and value.get('checked') is True and - all(type(value.get(k)) is int and value[k] == n for k, n in - (('changed', 6), ('toggled', 1), ('clicked', 1), ('events', 20))), - 'Actual GTK text/toggle/button callbacks or final key release missing') - - -def expected_events(base): - require(type(base) is int and 0 < base <= 2**32, 'Bounded timestamp origin required') - return [dict(index=i, keyval=KEYVALS[i//2], keycode=KEYCODES[i//2], modifiers=1 if i < 2 else 0, - time_ms=((base+i)*1000) & 0xffffffff, release=bool(i % 2), - event_type=5 if i % 2 else 4, own_surface=True, matches=True) for i in range(20)] - - -def final_frame(value, base): - require(all(value.get(key) is True for key in ('ready', 'typed', 'native_close', 'cleanup_verified', 'success')) and - all(value.get(key) is False for key in ('invalid', 'expired', 'exception')) and - all(type(value.get(key)) is int and value[key] == count for key, count in - (('changed', 6), ('toggled', 1), ('clicked', 1), ('close_requests', 1))), - 'Actual GTK callbacks/native close proof incomplete') - events = value.get('gdk_events') - require(type(events) is list and len(events) == 20, 'Complete ordered GDK event sequence required') - for actual, expected in zip(events, expected_events(base)): - require(type(actual) is dict and set(actual) == set(expected) and - all(type(actual[k]) is type(v) and actual[k] == v for k, v in expected.items()), - 'Observed GDK event differs in identity, order, key, surface, modifier or timestamp') - require(value.get('changed_at') == [1, 3, 5, 7, 9, 11] and - all(type(i) is int for i in value['changed_at']) and - type(value.get('toggled_at')) is int and value['toggled_at'] in (15, 16) and - type(value.get('clicked_at')) is int and value['clicked_at'] in (19, 20), - 'Widget callbacks not causally bound to their actual key events') - - -def focus_proof(value): - require(type(value) is dict, 'Missing bounded focus observations') - if not value: return False - errors = ('legacy_window_error', 'app_window_error', 'field_error', 'field_role_error', 'field_window_error') - flags = ('legacy_window_boolean', 'legacy_window_value', 'app_window_element', 'app_window_pid_matches', - 'app_window_matches', 'field_element', 'field_pid_matches', 'field_text_role', - 'field_window_element', 'field_window_pid_matches', 'field_window_matches') - require(set(value) == set(errors + flags + ('field_role_category',)) and - all(type(value[k]) is int and -26000 <= value[k] <= 0 for k in errors) and - all(type(value[k]) is bool for k in flags), 'Malformed focus observation') - require(value['field_role_category'] in ('unavailable', 'text_field', 'text_area', 'other') and - value['field_text_role'] == (value['field_role_category'] == 'text_field'), 'Inconsistent bounded field role') - require(not value['legacy_window_value'] or (value['legacy_window_boolean'] and value['legacy_window_error'] == 0), - 'Inconsistent legacy window observation') - # AccessKit is disabled. AX widget roles are observations, not accessibility - # acceptance; the child must independently prove real GTK entry focus. - return value['app_window_error'] == 0 and all(value[k] for k in - ('app_window_element', 'app_window_pid_matches', 'app_window_matches')) - - -def window_proof(value): - require(type(value) is dict, 'Missing bounded window observations') - if not value: return False - errors = ('app_role_error', 'attribute_names_error', 'windows_error', 'focused_window_error') - flags = ('app_role_application', 'windows_attribute_present', 'windows_array', - 'focused_window_element', 'focused_window_pid_matches', 'focused_window_title_matches') - counts = ('attribute_names_count', 'windows_count', 'owned_candidates', - 'window_role_candidates', 'title_candidates') - require(set(value) == set(errors + flags + counts + ('first_role_category',)) and - all(type(value[k]) is int and -26000 <= value[k] <= 0 for k in errors) and - all(type(value[k]) is bool for k in flags) and - all(type(value[k]) is int and 0 <= value[k] <= 64 for k in counts), 'Malformed window observation') - require(value['first_role_category'] in ('unavailable', 'window', 'sheet', 'other') and - value['windows_count'] >= value['owned_candidates'] >= value['window_role_candidates'] >= - value['title_candidates'], 'Inconsistent bounded window candidates') - require((not value['windows_array'] or value['windows_error'] == 0) and - (value['windows_count'] == 0 or value['windows_array']), 'Inconsistent window list observation') - require(value['owned_candidates'] or value['first_role_category'] == 'unavailable', - 'Role category without an owned candidate') - # Exactly one owned, correctly titled window of the verified child. - return value['title_candidates'] == 1 - - -def driver_frame(value, phase, code, base): - require(code in (0, 2), 'Unexpected driver exit') - common = ('identity_verified', 'post_event_access', 'ax_trusted', 'own_window_selected', 'focus_verified') - for key in (*common, 'timestamp_readback', 'close_action', 'success'): - require(type(value.get(key)) is bool, 'Driver observation missing: ' + key) - require(type(value.get('events_posted')) is int and 0 <= value['events_posted'] <= 20, 'Unbounded event count') - require(type(value.get('base_seconds')) is int and value['base_seconds'] == base, 'Driver timestamp origin differs') - require(value['focus_verified'] == focus_proof(value.get('focus_observation')), 'Focus proof/summary mismatch') - require(value['own_window_selected'] == window_proof(value.get('window_observation')), - 'Window proof/summary mismatch') - success = all(value[key] for key in common) and ( - value['timestamp_readback'] and value['events_posted'] == 20 and not value['close_action'] if phase == 'keys' - else value['close_action'] and value['events_posted'] == 0 and not value['timestamp_readback']) - require(value['success'] == success and (code == 0) == success, 'Driver outcome/exit mismatch') - return success - - -def driver_arguments(driver, target, phase, identity, parent, driver_seal, target_seal, nonce, base): - require(phase in ('keys', 'close') and set(identity) == {'pid', 'created'} and - all(type(identity[k]) is int for k in identity) and 0 < identity['pid'] <= 2**31-1 and - 0 < identity['created'] < 2**96 and identity['created'] >> 32 > 0, 'Invalid process identity') - require(type(parent) is int and 0 < parent <= 2**31-1 and re.fullmatch('[0-9a-f]{32}', nonce) and - type(base) is int and 0 < base <= 2**32, 'Invalid private driver identity') - for path, seal in ((driver, driver_seal), (target, target_seal)): - require(str(path) == seal['canonical_path'] and Path(path).is_absolute() and - all(type(seal.get(k)) is int and seal[k] >= 0 for k in ('device', 'inode')), 'Invalid executable seal') - return list(map(str, [driver, phase, identity['pid'], identity['created'] >> 32, identity['created'] & 0xffffffff, - parent, target_seal['device'], target_seal['inode'], target, nonce, base])) - - -class Frames: - def __init__(self, reader, stream): - self.reader, self.stream, self.buffer = reader, stream, b'' - self.eof = False - - def next(self, phase, deadline): - while b'\n' not in self.buffer: - require(time.monotonic() < deadline, 'Target protocol deadline') - chunk = self.reader.read(max(.001, deadline - time.monotonic())) - self.eof = not chunk - require(chunk, 'Target exited before ' + phase) - self.stream.write(chunk); self.stream.flush(); self.buffer += chunk - require(len(self.buffer) <= 16384, 'Target protocol buffer exceeded bound') - raw, self.buffer = self.buffer.split(b'\n', 1) - return decode(raw, phase) - - def drain(self, deadline, reject_new=False): - if self.eof: - return - saw_extra = False - while True: - require(time.monotonic() < deadline, 'Target drain deadline') - chunk = self.reader.read(max(.001, deadline - time.monotonic())) - if not chunk: - self.eof = True - require(not (reject_new and saw_extra), 'Unexpected trailing target stdout') - return - self.stream.write(chunk); self.stream.flush() - saw_extra = True - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--provider-report', type=Path, required=True) - parser.add_argument('--output', type=Path, required=True) - parser.add_argument('--work-dir', type=Path, required=True) - parser.add_argument('--revision', required=True) - parser.add_argument('--architecture', choices=('arm64', 'x86_64'), required=True) - args = parser.parse_args() - require(sys.platform == 'darwin' and platform.machine() == args.architecture, 'Matching native macOS host required') - require(re.fullmatch('[0-9a-f]{40}', args.revision), 'Exact revision required') - output, work = paths(args.output, args.work_dir) - output.mkdir(parents=True, mode=0o700); work.mkdir(parents=True, mode=0o700) - logs = output/'logs'; logs.mkdir(); (work/'tmp').mkdir() - started = time.monotonic(); deadline = started + TOTAL_SECONDS - variables = {key: os.environ[key] for key in ('HOME', 'USER', 'LOGNAME', 'DEVELOPER_DIR') if key in os.environ} - variables.update(PATH='/usr/bin:/bin:/usr/sbin:/sbin', LC_ALL='C', TMPDIR=str(work/'tmp'), - PYTHONDONTWRITEBYTECODE='1', GIT_OPTIONAL_LOCKS='0') - sources = [Path(__file__).resolve(), Path(__file__).with_suffix('.mm'), - ROOT/'tests/tools/ordinary_io_parity_contract.py', - ROOT/'validation/ny-3d/scripts/debugger_process.py', ROOT/'tests/tools/process_contract_support.py', - ROOT/'scripts/ci/macos-gtk-runtime.py', ROOT/'scripts/ci/macos-gtk-provider.py', - ROOT/'scripts/ci/macos-ui-probes.py', Path(__file__).with_name('test_macos_gtk_directed_probes.py')] - report = dict(schema='nil.macos.gtk-directed.v1', status='INCOMPLETE', qualification=False, language_acceptance=False, - accessibility_acceptance=False, sdk_replaced=False, accesskit_enabled=False, - scope='GTK prerequisite: actual directed keys, widget callbacks and native AX close to one retained child only', - revision=args.revision, architecture=args.architecture, platform=platform.platform(), - total_seconds_limit=180, target_seconds_limit=30, driver_seconds_limit=10, - output_limit_bytes=4 * 1024**2, phases=[], problems=[], - image={key: os.environ.get(key) for key in ('ImageOS', 'ImageVersion', 'GITHUB_RUN_ID', 'GITHUB_SHA')}) - seals = {}; raw_bytes = 0; target = None; readers = []; streams = []; frames = None - target_cleaned = False; target_started = None; target_deadline = None - provider = None; baseline = None; provider_anchor = None; support = ownership = None; finalizing = False - def seal(path): - key = str(Path(path).absolute()) - if key not in seals: seals[key] = record(Path(key), deadline - RESERVE_SECONDS) - return seals[key] - def run(name, argv, seconds=10, env=None): - nonlocal raw_bytes - remaining = deadline - (5 if finalizing else RESERVE_SECONDS) - time.monotonic() - if target_deadline is not None: remaining = min(remaining, target_deadline - time.monotonic()) - require(remaining > 0, 'Whole/target deadline exhausted') - row = support.run_process(ownership, list(map(str, argv)), work, variables if env is None else env, logs, name, min(seconds, remaining)) - report['phases'].append(row) - raw = (logs/row['stdout']).read_bytes(); errors = (logs/row['stderr']).read_bytes() - raw_bytes += len(raw) + len(errors) - require(raw_bytes <= report['output_limit_bytes'], 'Raw output bound exceeded') - require(row.get('cleanup_verified') is True and not row.get('error') and not row.get('timed_out'), - name + ': process/cleanup failure; raw logs retained') - return row['exit_code'], raw - def checked(name, argv, seconds=10, env=None): - code, raw = run(name, argv, seconds, env); require(code == 0, name + ': nonzero exit; raw logs retained') - return raw.decode('utf-8').strip() - try: - for path in sources: seal(path) - support = load(sources[2], 'directed_io_support'); support.MAX_OUTPUT = MAX_OUTPUT - ownership = support.load_ownership(ROOT) - identity_support = load(sources[4], 'directed_identity_support') - require(checked('source-revision', ['/usr/bin/git', '-C', ROOT, 'rev-parse', 'HEAD']) == args.revision, - 'Checkout revision mismatch') - require(not checked('source-before', ['/usr/bin/git', '-C', ROOT, 'status', '--porcelain', '--untracked-files=no']), - 'Clean source required') - provider = load(sources[5], 'directed_provider_validation') - provider_anchor = seal(args.provider_report) - baseline = provider.validate_provider(args.provider_report, args.revision, args.architecture, - deadline - RESERVE_SECONDS) - report['provider_report'] = provider_anchor; report['provider_validated_before'] = True - aliases = provider.provider_aliases(baseline); report['provider_aliases'] = {k: str(v) for k, v in aliases.items()} - compiler = Path(baseline['toolchain']['compiler']); sdk = Path(baseline['toolchain']['sdk']) - build_env = baseline['build_environment']; wrapper = Path(build_env['PKG_CONFIG']) - for path in (compiler, sdk/'SDKSettings.json', wrapper): - row = seal(path); expected = baseline['inputs_before'].get(str(path)) - # Provider record has a different schema; bind exact bytes/canonical path. - require(expected is not None and all(row[k] == expected[k] for k in ('sha256', 'bytes', 'canonical_path')), - 'Provider toolchain input differs') - seal(Path(sys.executable)) - report['toolchain'] = dict(sdk=str(sdk), compiler=str(compiler), provider_pkg_config=str(wrapper)) - flags = shlex.split(checked('gtk-flags', [wrapper, '--cflags', '--libs', 'gtk4-macos'], env=build_env)) - require(0 < len(flags) <= 256 and all(len(x) <= 4096 and '\x00' not in x for x in flags), 'Compiler flags unbounded') - binary = work/'gtk-directed-probe' - checked('compile', [compiler, '-std=c++17', '-fobjc-arc', '-Wall', '-Wextra', '-Werror', '-isysroot', sdk, - '-mmacosx-version-min=15.0', sources[1], *flags, '-framework', 'AppKit', '-framework', 'ApplicationServices', - '-o', binary], 30, build_env) - target_seal = seal(binary); binary = Path(target_seal['canonical_path']) - driver = binary; driver_seal = dict(target_seal) - report['target_binary'] = target_seal; report['driver_binary'] = driver_seal - variables = provider.runtime_environment(work, baseline) - nonce = secrets.token_hex(16) - command = [str(binary), 'target', nonce] - target_started = time.monotonic(); target_deadline = min(target_started + 30, deadline - RESERVE_SECONDS) - target = ownership.OwnedProcess(command, cwd=work, env=variables, stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - report['target'] = dict(argv=command, pid=target.process.pid, cleanup_verified=False, - stdout='target.stdout', stderr='target.stderr') - budget = ownership.CaptureBudget(target.terminate, maximum=64 * 1024) - stdout = (logs/'target.stdout').open('wb'); stderr = (logs/'target.stderr').open('wb'); streams = [stdout, stderr] - reader = ownership.PipeReader(target.process.stdout, budget); readers.append(reader) - readers.append(ownership.PipeReader(target.process.stderr, budget, sink=stderr)) - frames = Frames(reader, stdout) - identity = identity_support.process_identity(target.process.pid) - report['target']['identity'] = identity - observed = frames.next('ready', min(target_deadline, time.monotonic() + 7)) - report['ready'] = observed; ready_frame(observed, identity['pid'], aliases) - base = observed['base_seconds'] - for phase in ('keys', 'close'): - require(identity_support.process_alive(identity), 'Target is dead or its lifetime changed') - require(record(binary, deadline - RESERVE_SECONDS) == target_seal and - record(driver, deadline - RESERVE_SECONDS) == driver_seal, 'Private executable changed before driver') - argv = driver_arguments(driver, binary, phase, identity, os.getpid(), driver_seal, target_seal, nonce, base) - # Never poll/reap the target while a PID-directed driver is active. - # Even an unexpectedly dead target remains our unreaped child, pinning its PID. - code, raw = run('driver-' + phase, argv, 10) - value = decode(raw, phase); report[phase] = value - require(driver_frame(value, phase, code, base), phase + ': directed capability/delivery prerequisite unavailable') - if phase == 'keys': - observed = frames.next('typed', min(target_deadline, time.monotonic() + 5)) - report['typed'] = observed; typed_frame(observed) - observed = frames.next('final', target_deadline); report['final'] = observed; final_frame(observed, base) - code = target.wait(max(.01, target_deadline - time.monotonic())); target.finish() - report['target']['exit_code'] = code; require(code == 0, 'Target native close failed') - frames.drain(deadline - 10, reject_new=True); require(not frames.buffer, 'Unexpected trailing target frames') - budget.check(); report['observations_completed'] = True - except Exception as error: - report['problems'].append(type(error).__name__ + ': ' + str(error)) - finally: - if target is not None: - try: - # Drivers have finished (including their own cleanup) before any target wait/reap. - if target.process.returncode is None: target.kill() - target.finish() - if frames is not None and not report.get('observations_completed'): - frames.drain(deadline - 10) - for reader in readers: reader.close() - target_cleaned = True - except Exception as error: - report['problems'].append('Target cleanup: ' + type(error).__name__ + ': ' + str(error)) - for stream in streams: stream.close() - report['target'].update(cleanup_verified=target_cleaned, exit_code=target.process.returncode, - elapsed_seconds=time.monotonic() - target_started) - try: - for name in ('target.stdout', 'target.stderr'): - path = logs/name - if path.exists(): - row = record(path, deadline); raw_bytes += row['bytes']; report['target'][name + '_record'] = row - except Exception as error: - report['problems'].append('Target log seal: ' + type(error).__name__ + ': ' + str(error)) - finalizing = True - if baseline is not None: - try: - after = provider.validate_provider(args.provider_report, args.revision, args.architecture, deadline - 5) - require(after == baseline, 'Provider report changed') - report['provider_validated_after'] = True - except Exception as error: - report['provider_validated_after'] = False - report['problems'].append('Provider final seals: ' + type(error).__name__ + ': ' + str(error)) - if support is not None and time.monotonic() < deadline - 5: - try: - # The target is fully cleaned before these final source checks. - target_deadline = None - require(not checked('source-after', ['/usr/bin/git', '-C', ROOT, 'status', '--porcelain', '--untracked-files=no']), - 'Source changed') - require(checked('revision-after', ['/usr/bin/git', '-C', ROOT, 'rev-parse', 'HEAD']) == args.revision, - 'Revision changed') - report['source_unchanged'] = True - except Exception as error: - report['source_unchanged'] = False - report['problems'].append('Final source: ' + type(error).__name__ + ': ' + str(error)) - report['inputs_before'] = seals - try: - report['inputs_after'] = {key: record(Path(key), deadline) for key in seals} - report['inputs_unchanged'] = report['inputs_after'] == seals - except Exception as error: - report['inputs_unchanged'] = False - report['problems'].append('Final seals: ' + type(error).__name__ + ': ' + str(error)) - report['cleanup_verified'] = all(row.get('cleanup_verified') is True for row in report['phases']) and ( - target is None or target_cleaned) - report['elapsed_seconds'] = time.monotonic() - started; report['raw_output_bytes'] = raw_bytes - report['directed_child_feasible'] = bool(report.get('observations_completed') and report['inputs_unchanged'] and - report.get('provider_validated_after') is True and report.get('source_unchanged') is True and - report['cleanup_verified'] and not report['problems'] and report['elapsed_seconds'] < TOTAL_SECONDS and - raw_bytes <= report['output_limit_bytes']) - report['status'] = 'PASS' if report['directed_child_feasible'] else 'FAIL' - (output/'report.json').write_text(json.dumps(report, indent=2, sort_keys=True) + '\n') - return 0 if report['status'] == 'PASS' else 1 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/scripts/ci/macos-gtk-provider-lock.json b/scripts/ci/macos-gtk-provider-lock.json deleted file mode 100644 index 6e3c1a01..00000000 --- a/scripts/ci/macos-gtk-provider-lock.json +++ /dev/null @@ -1,405 +0,0 @@ -{ - "baseline": { - "arm64": { - "glib_tools": { - "glib-compile-resources": { - "path": "/opt/homebrew/bin/glib-compile-resources", - "version": "2.90.1" - }, - "glib-compile-schemas": { - "path": "/opt/homebrew/bin/glib-compile-schemas", - "version": "2.90.1" - } - }, - "loaded_files": { - "/opt/homebrew/Cellar/cairo/1.18.6/lib/libcairo.2.dylib": { - "bytes": 1165296, - "canonical_path": "/opt/homebrew/Cellar/cairo/1.18.6/lib/libcairo.2.dylib", - "mode": 292, - "path": "/opt/homebrew/Cellar/cairo/1.18.6/lib/libcairo.2.dylib", - "sha256": "374ae84ba3b155a3e855c504b045298203518488830093e4f1ccc9458443db08" - }, - "/opt/homebrew/Cellar/glib/2.90.1/lib/libgio-2.0.0.dylib": { - "bytes": 2040160, - "canonical_path": "/opt/homebrew/Cellar/glib/2.90.1/lib/libgio-2.0.0.dylib", - "mode": 292, - "path": "/opt/homebrew/Cellar/glib/2.90.1/lib/libgio-2.0.0.dylib", - "sha256": "3a0a7c33093a1f372d56932a79f4e64c536096b57cf89abb0107027a11079c8e" - }, - "/opt/homebrew/Cellar/glib/2.90.1/lib/libglib-2.0.0.dylib": { - "bytes": 1366832, - "canonical_path": "/opt/homebrew/Cellar/glib/2.90.1/lib/libglib-2.0.0.dylib", - "mode": 292, - "path": "/opt/homebrew/Cellar/glib/2.90.1/lib/libglib-2.0.0.dylib", - "sha256": "9b7fa6436bfb8b906eba284563f80bc7dfae7629ed4f8e03996d1040aa1e8317" - }, - "/opt/homebrew/Cellar/glib/2.90.1/lib/libgobject-2.0.0.dylib": { - "bytes": 411264, - "canonical_path": "/opt/homebrew/Cellar/glib/2.90.1/lib/libgobject-2.0.0.dylib", - "mode": 292, - "path": "/opt/homebrew/Cellar/glib/2.90.1/lib/libgobject-2.0.0.dylib", - "sha256": "977d3440275e705240a4d3b9fbfe4b8555bf0b64e1a5ad465123400ebd43a7d5" - }, - "/opt/homebrew/Cellar/harfbuzz/15.0.0_1/lib/libharfbuzz-subset.0.dylib": { - "bytes": 1959552, - "canonical_path": "/opt/homebrew/Cellar/harfbuzz/15.0.0_1/lib/libharfbuzz-subset.0.dylib", - "mode": 292, - "path": "/opt/homebrew/Cellar/harfbuzz/15.0.0_1/lib/libharfbuzz-subset.0.dylib", - "sha256": "c101e3e6f016173a2008bb2e97bf456b479de0068da1eeb3ac6dd8c0792f4d3b" - }, - "/opt/homebrew/Cellar/harfbuzz/15.0.0_1/lib/libharfbuzz.0.dylib": { - "bytes": 1445872, - "canonical_path": "/opt/homebrew/Cellar/harfbuzz/15.0.0_1/lib/libharfbuzz.0.dylib", - "mode": 292, - "path": "/opt/homebrew/Cellar/harfbuzz/15.0.0_1/lib/libharfbuzz.0.dylib", - "sha256": "d4310e2ec6bbb7244aa6a3391880f4baaf38e46478859660a920f59dca454e3d" - } - }, - "pkg_config_compatibility": "/opt/homebrew/Library/Homebrew/os/mac/pkgconfig/15", - "versions": { - "cairo": "1.18.6", - "glib": "2.90.1", - "harfbuzz": "15.0.0" - } - }, - "x86_64": { - "glib_tools": { - "glib-compile-resources": { - "path": "/usr/local/bin/glib-compile-resources", - "version": "2.88.3" - }, - "glib-compile-schemas": { - "path": "/usr/local/bin/glib-compile-schemas", - "version": "2.88.3" - } - }, - "loaded_files": { - "/usr/local/Cellar/cairo/1.18.4/lib/libcairo.2.dylib": { - "bytes": 1163200, - "canonical_path": "/usr/local/Cellar/cairo/1.18.4/lib/libcairo.2.dylib", - "mode": 292, - "path": "/usr/local/Cellar/cairo/1.18.4/lib/libcairo.2.dylib", - "sha256": "01d9746cc06472faee5a9468aae9b9e89ad747f49e3b47a43b93b6d72abaa119" - }, - "/usr/local/Cellar/glib/2.88.3/lib/libgio-2.0.0.dylib": { - "bytes": 1733920, - "canonical_path": "/usr/local/Cellar/glib/2.88.3/lib/libgio-2.0.0.dylib", - "mode": 292, - "path": "/usr/local/Cellar/glib/2.88.3/lib/libgio-2.0.0.dylib", - "sha256": "be8888f94edc641aed09267c53e1c5d2c06402fe14ca81e3a2336f0876047cce" - }, - "/usr/local/Cellar/glib/2.88.3/lib/libglib-2.0.0.dylib": { - "bytes": 1199040, - "canonical_path": "/usr/local/Cellar/glib/2.88.3/lib/libglib-2.0.0.dylib", - "mode": 292, - "path": "/usr/local/Cellar/glib/2.88.3/lib/libglib-2.0.0.dylib", - "sha256": "382b2608cc18f8568891080f40222fac2550d2600fd7b24952dbf49d9c620d28" - }, - "/usr/local/Cellar/glib/2.88.3/lib/libgobject-2.0.0.dylib": { - "bytes": 348224, - "canonical_path": "/usr/local/Cellar/glib/2.88.3/lib/libgobject-2.0.0.dylib", - "mode": 292, - "path": "/usr/local/Cellar/glib/2.88.3/lib/libgobject-2.0.0.dylib", - "sha256": "71f131f9446bf8e2d32dcb61e92acfa9b24f547528ca926560152bc4ce7c68df" - }, - "/usr/local/Cellar/harfbuzz/14.3.1/lib/libharfbuzz-subset.0.dylib": { - "bytes": 1291736, - "canonical_path": "/usr/local/Cellar/harfbuzz/14.3.1/lib/libharfbuzz-subset.0.dylib", - "mode": 292, - "path": "/usr/local/Cellar/harfbuzz/14.3.1/lib/libharfbuzz-subset.0.dylib", - "sha256": "bd05d57cd203cf36af3b0a704ec64b92d935da5635d072d60e02eab7f3b693e3" - }, - "/usr/local/Cellar/harfbuzz/14.3.1/lib/libharfbuzz.0.dylib": { - "bytes": 1146424, - "canonical_path": "/usr/local/Cellar/harfbuzz/14.3.1/lib/libharfbuzz.0.dylib", - "mode": 292, - "path": "/usr/local/Cellar/harfbuzz/14.3.1/lib/libharfbuzz.0.dylib", - "sha256": "bf57b9bd5d962e770e23e444b259775e17787fc721d8127982755c5f874cffc4" - } - }, - "pkg_config_compatibility": "/usr/local/Homebrew/Library/Homebrew/os/mac/pkgconfig/15", - "versions": { - "cairo": "1.18.4", - "glib": "2.88.3", - "harfbuzz": "14.3.1" - } - } - }, - "meson": { - "bytes": 1108668, - "filename": "meson-1.12.1-py3-none-any.whl", - "members": { - "entries": 256, - "expanded_bytes": 4309832, - "manifest_sha256": "87b350d26a8f7c5f5e191fcbeaea0d02f2f582fcfd1e0cdf81b196fa59974919" - }, - "requires_python": ">=3.10", - "sha256": "930bc7542cbd9f57009e182fd014eba48cf1a0180a7b9006d2d32d8f168d8b02", - "url": "https://files.pythonhosted.org/packages/57/99/36cd25f9598eef70db97577440a70a360af505f6f01c2338a18d1556079c/meson-1.12.1-py3-none-any.whl", - "version": "1.12.1" - }, - "prerequisite_evidence": "c508eb67985651447f251249fb2294eac04e7c6fd1b3cdf1dcf0ffbd6e14bc90", - "profile": "Private macOS15 shared Release GTK4.18.6, Cairo renderer; no SDK or runtime admission", - "schema": "nil.macos.gtk-provider-lock.v1", - "sources": [ - { - "bytes": 1098260, - "checksum_source": "https://api.github.com/repos/fribidi/fribidi/releases/tags/v1.0.16", - "members": { - "entries": 196, - "expanded_bytes": 19935464, - "manifest_sha256": "34dfed393ab989fb18020e47d7e188182361e8b7ce6a9b77e1fb3f3de75d0e9d", - "maximum_file_bytes": 7959974 - }, - "name": "fribidi-1.0.16.tar.xz", - "options": [ - "-Ddocs=false", - "-Dbin=false", - "-Dtests=false" - ], - "required_files": { - "fribidi-1.0.16/meson.build": { - "bytes": 2597, - "sha256": "484ec5aa67a62a7917dcecd229cdf823d9ddc477f2c4e3de399494e19a97b511" - }, - "fribidi-1.0.16/meson_options.txt": { - "bytes": 458, - "sha256": "4f43276ba0e983d3a2d9ffc0afd49eaa3097f1bfc64a36a6cf621f1e5a4bf356" - } - }, - "root": "fribidi-1.0.16", - "sha256": "1b1cde5b235d40479e91be2f0e88a309e3214c8ab470ec8a2744d82a5a9ea05c", - "url": "https://github.com/fribidi/fribidi/releases/download/v1.0.16/fribidi-1.0.16.tar.xz" - }, - { - "bytes": 1883988, - "checksum_source": "https://download.gnome.org/sources/pango/1.56/pango-1.56.4.sha256sum", - "members": { - "entries": 595, - "expanded_bytes": 10119810, - "manifest_sha256": "05346b48b86def3eb5a78357ff3c26724c31ee73434029fa8402bb09fc32973e", - "maximum_file_bytes": 3037870 - }, - "name": "pango-1.56.4.tar.xz", - "options": [ - "-Dcairo=enabled", - "-Dfontconfig=disabled", - "-Dfreetype=disabled", - "-Dxft=disabled", - "-Dlibthai=disabled", - "-Dintrospection=disabled", - "-Ddocumentation=false", - "-Dman-pages=false", - "-Dbuild-testsuite=false", - "-Dbuild-examples=false", - "-Dsysprof=disabled" - ], - "required_files": { - "pango-1.56.4/meson.build": { - "bytes": 19163, - "sha256": "c804cc0e0f364d1e9f67cdc3ee44f93d3f0bc67be073525c60087a017455199e" - }, - "pango-1.56.4/meson.options": { - "bytes": 1698, - "sha256": "aed5219c1f773f22bcddc87edc3f86180f1bff6d58ddfb62f3b48261852ba6c8" - } - }, - "root": "pango-1.56.4", - "sha256": "17065e2fcc5f5a5bdbffc884c956bfc7c451a96e8c4fb2f8ad837c6413cb5a01", - "url": "https://download.gnome.org/sources/pango/1.56/pango-1.56.4.tar.xz" - }, - { - "bytes": 6525072, - "checksum_source": "https://download.gnome.org/sources/gdk-pixbuf/2.42/gdk-pixbuf-2.42.12.sha256sum", - "members": { - "entries": 730, - "expanded_bytes": 24941912, - "manifest_sha256": "350422e844715483b9f077c2d6082aacc7f652f823a685e6c47add83c696fe12", - "maximum_file_bytes": 8791300 - }, - "name": "gdk-pixbuf-2.42.12.tar.xz", - "options": [ - "-Dpng=enabled", - "-Dbuiltin_loaders=png", - "-Djpeg=disabled", - "-Dtiff=disabled", - "-Dgif=disabled", - "-Dothers=disabled", - "-Dintrospection=disabled", - "-Dgtk_doc=false", - "-Ddocs=false", - "-Dman=false", - "-Dtests=false", - "-Dinstalled_tests=false" - ], - "required_files": { - "gdk-pixbuf-2.42.12/meson.build": { - "bytes": 13557, - "sha256": "aeb1ba092b0ceb8f1c61d6fa94923bc7c0000996876dbe07f05e79b775d6946c" - }, - "gdk-pixbuf-2.42.12/meson_options.txt": { - "bytes": 2588, - "sha256": "f139def01d67b1cf8aab33e62ed7332fd1ceb2d9a2f69abaa79836f428734a94" - } - }, - "root": "gdk-pixbuf-2.42.12", - "sha256": "b9505b3445b9a7e48ced34760c3bcb73e966df3ac94c95a148cb669ab748e3c7", - "url": "https://download.gnome.org/sources/gdk-pixbuf/2.42/gdk-pixbuf-2.42.12.tar.xz" - }, - { - "bytes": 333924, - "checksum_source": "https://download.gnome.org/sources/graphene/1.10/graphene-1.10.8.sha256sum", - "members": { - "entries": 164, - "expanded_bytes": 2039894, - "manifest_sha256": "f93a55d4467e92b7fdd081f4209e2d1e5b1f62ca758eb4da21bff69c0bc66848", - "maximum_file_bytes": 394144 - }, - "name": "graphene-1.10.8.tar.xz", - "options": [ - "-Dgobject_types=true", - "-Dintrospection=disabled", - "-Dgtk_doc=false", - "-Dtests=false", - "-Dinstalled_tests=false" - ], - "required_files": { - "graphene-1.10.8/meson.build": { - "bytes": 13270, - "sha256": "a2c324bde5db95af98fbb09e58863fb8bec9eb007a9d70f98f17f21860925ae7" - }, - "graphene-1.10.8/meson_options.txt": { - "bytes": 1003, - "sha256": "7c06f49f9728b87717811adc40a634991781ed1203b8617bb480cf1e0b6d6d8e" - } - }, - "root": "graphene-1.10.8", - "sha256": "a37bb0e78a419dcbeaa9c7027bcff52f5ec2367c25ec859da31dfde2928f279a", - "url": "https://download.gnome.org/sources/graphene/1.10/graphene-1.10.8.tar.xz" - }, - { - "bytes": 223528, - "checksum_source": "https://download.gnome.org/sources/libepoxy/1.5/libepoxy-1.5.10.sha256sum", - "members": { - "entries": 77, - "expanded_bytes": 3427406, - "manifest_sha256": "50790d5e16b57578d1a236cb78165db030682a09664cb778578cf9d4e26c590d", - "maximum_file_bytes": 2799209 - }, - "name": "libepoxy-1.5.10.tar.xz", - "options": [ - "-Dglx=no", - "-Degl=no", - "-Dx11=false", - "-Ddocs=false", - "-Dtests=false" - ], - "required_files": { - "libepoxy-1.5.10/meson.build": { - "bytes": 7569, - "sha256": "fd65cb3ac94480956191020a5f624ee4d1144b09b4adc2e422ad1c210f33fbb3" - }, - "libepoxy-1.5.10/meson_options.txt": { - "bytes": 642, - "sha256": "f0398914a161bd15379a99b694fa488ae730dc8ad8d7645b3eb0b7df6bd77b7d" - } - }, - "root": "libepoxy-1.5.10", - "sha256": "072cda4b59dd098bba8c2363a6247299db1fa89411dc221c8b81b8ee8192e623", - "url": "https://download.gnome.org/sources/libepoxy/1.5/libepoxy-1.5.10.tar.xz" - }, - { - "bytes": 17710412, - "checksum_source": "https://download.gnome.org/sources/gtk/4.18/gtk-4.18.6.sha256sum", - "members": { - "entries": 7549, - "expanded_bytes": 104103323, - "manifest_sha256": "2f0c4c32e05dfcfbfc211728b93d7020cea219a9b71182c4dca9dd2a3c49e2dc", - "maximum_file_bytes": 3100196 - }, - "name": "gtk-4.18.6.tar.xz", - "options": [ - "-Dmacos-backend=true", - "-Dx11-backend=false", - "-Dwayland-backend=false", - "-Dbroadway-backend=false", - "-Dwin32-backend=false", - "-Dandroid-backend=false", - "-Dmedia-gstreamer=disabled", - "-Dprint-cups=disabled", - "-Dprint-cpdb=disabled", - "-Dvulkan=disabled", - "-Dcloudproviders=disabled", - "-Dtracker=disabled", - "-Dcolord=disabled", - "-Dsysprof=disabled", - "-Daccesskit=disabled", - "-Dintrospection=disabled", - "-Ddocumentation=false", - "-Dscreenshots=false", - "-Dman-pages=false", - "-Dbuild-demos=false", - "-Dbuild-testsuite=false", - "-Dbuild-examples=false", - "-Dbuild-tests=false" - ], - "required_files": { - "gtk-4.18.6/gtk/meson.build": { - "bytes": 32573, - "sha256": "19a493bbb63815c573be970994e80d7a8ed1e1a2d509ca22b7b7fe10597681ce" - }, - "gtk-4.18.6/gtk/theme/Default/Default-dark.css": { - "bytes": 146841, - "sha256": "423d185487b900fee7ec40e295448b010605a0150a6963606978ba7b5a264605" - }, - "gtk-4.18.6/gtk/theme/Default/Default-hc-dark.css": { - "bytes": 147447, - "sha256": "8e69d5156e88132dc57225158931f1835dfd255a5c0476f0f204fbcea8fa10fb" - }, - "gtk-4.18.6/gtk/theme/Default/Default-hc.css": { - "bytes": 147618, - "sha256": "e427fe3533b9d3ec640d4253e718384387539e86b08da132d8040b95e221b094" - }, - "gtk-4.18.6/gtk/theme/Default/Default-light.css": { - "bytes": 147433, - "sha256": "0371288fe3d1028fb194d83d09f449ff30cfd22cbbf81d2378f8bbd20be74745" - }, - "gtk-4.18.6/gtk/theme/Default/gtk-dark.css": { - "bytes": 74, - "sha256": "6a7461775fa12dd4016ba979dc46c87955c39b2c0a806ee16df9c29e5a8be929" - }, - "gtk-4.18.6/gtk/theme/Default/gtk-hc-dark.css": { - "bytes": 77, - "sha256": "375ff5b473c5ecd14b381edcb5c3cb608454444a7960c32e94ac509c2a6ee48a" - }, - "gtk-4.18.6/gtk/theme/Default/gtk-hc.css": { - "bytes": 72, - "sha256": "bb600e56bcc2b9051c0ebd9d9de24b0168578706d0804dd275dfd13300a667e3" - }, - "gtk-4.18.6/gtk/theme/Default/gtk-light.css": { - "bytes": 75, - "sha256": "7a45fc3fcc9791842d21b450f139b15fd7f46db33bf2a21641c1572b3570f0ff" - }, - "gtk-4.18.6/gtk/theme/Default/gtk.css": { - "bytes": 75, - "sha256": "7a45fc3fcc9791842d21b450f139b15fd7f46db33bf2a21641c1572b3570f0ff" - }, - "gtk-4.18.6/gtk/theme/Empty/gtk.css": { - "bytes": 28, - "sha256": "509352e5b90871b13fb44cc2528ae614fceb6cacbbefa38840eb2406cb69db8d" - }, - "gtk-4.18.6/meson.build": { - "bytes": 33176, - "sha256": "b3a6acb62f7438d2f040e255456eefed37e2eb8817926c27dc0c3040f16a8a14" - }, - "gtk-4.18.6/meson.options": { - "bytes": 3846, - "sha256": "ea368111a2b193740c5f702c54761f5e99663c785007d8b0d04c5cf8e7fe636e" - } - }, - "root": "gtk-4.18.6", - "sha256": "e1817c650ddc3261f9a8345b3b22a26a5d80af154630dedc03cc7becefffd0fa", - "url": "https://download.gnome.org/sources/gtk/4.18/gtk-4.18.6.tar.xz" - } - ] -} diff --git a/scripts/ci/macos-gtk-provider-smoke.mm b/scripts/ci/macos-gtk-provider-smoke.mm deleted file mode 100644 index e59cac92..00000000 --- a/scripts/ci/macos-gtk-provider-smoke.mm +++ /dev/null @@ -1,341 +0,0 @@ -// Private provider feasibility only. All events target this process's GTK window. -// GTK owns AppKit integration; this probe only iterates the default GLib context. -#import -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using Clock = std::chrono::steady_clock; -static void require(bool value, const char *message) { - if (!value) throw std::runtime_error(message); -} -static NSString *text(const char *value) { - return value ? [NSString stringWithUTF8String:value] : @""; -} -static NSDictionary *origin(const void *symbol, bool fileRequired = true) { - Dl_info info{}; - require(dladdr(symbol, &info) != 0 && info.dli_fname, "loaded symbol origin unavailable"); - char *canonical = realpath(info.dli_fname, nullptr); - require(canonical != nullptr || !fileRequired, "loaded symbol origin is not file-backed"); - NSString *path = canonical ? text(canonical) : nil; - free(canonical); - require((!path || (path.length > 0 && path.length <= 4096)) && std::strlen(info.dli_fname) <= 4096, - "invalid origin path"); - // Apple framework install names can be backed by the dyld shared cache rather - // than a readable individual file. Report that distinction; do not invent a hash. - return @{@"declared":text(info.dli_fname), @"canonical":path ?: (id)[NSNull null], - @"file_backed":@(path != nil)}; -} - -struct State { - struct Key { - unsigned stage, keyval, keycode, modifiers; - guint32 time; - bool release, own_surface, matches; - }; - GtkWindow *window = nullptr; - GtkWidget *entry = nullptr, *button = nullptr, *check = nullptr; - GdkSurface *surface = nullptr; // Borrowed only while the window is realized. - unsigned stage = 0, presses[3]{}, releases[3]{}; - guint32 times[3]{}; - unsigned changed = 0, clicked = 0, toggled = 0, closed = 0; - unsigned unexpected_keys = 0; - Key keys[6]{}; - unsigned key_count = 0; - bool invalid = false; -}; -static void observeKey(GtkEventControllerKey *controller, guint keyval, guint keycode, - GdkModifierType modifiers, bool release, State *state) { - GdkEvent *event = gtk_event_controller_get_current_event(GTK_EVENT_CONTROLLER(controller)); - if (state->stage >= 3 || !event || gdk_event_get_surface(event) != state->surface) { - state->invalid = true; - return; - } - const unsigned stage = state->stage; - const bool match = keyval == (stage == 0 ? GDK_KEY_n : GDK_KEY_space) && - keycode == (stage == 0 ? 45U : 49U) && modifiers == 0 && - gdk_event_get_modifier_state(event) == 0 && - gdk_event_get_time(event) == state->times[stage] && - gdk_event_get_event_type(event) == (release ? GDK_KEY_RELEASE : GDK_KEY_PRESS); - if (state->key_count < 6) state->keys[state->key_count++] = { - stage,keyval,keycode,static_cast(modifiers),gdk_event_get_time(event),release, - gdk_event_get_surface(event) == state->surface,match}; - else state->invalid = true; - if (!match) { - ++state->unexpected_keys; // No unrelated character/title data is retained. - state->invalid = true; - return; - } - auto &count = release ? state->releases[stage] : state->presses[stage]; - if (++count != 1) state->invalid = true; -} -static gboolean keyPressed(GtkEventControllerKey *controller, guint keyval, guint keycode, - GdkModifierType modifiers, gpointer data) { - observeKey(controller, keyval, keycode, modifiers, false, static_cast(data)); - return FALSE; // Observe; leave normal GTK widget handling intact. -} -static void keyReleased(GtkEventControllerKey *controller, guint keyval, guint keycode, - GdkModifierType modifiers, gpointer data) { - observeKey(controller, keyval, keycode, modifiers, true, static_cast(data)); -} -static void changed(GtkEditable *, gpointer data) { ++static_cast(data)->changed; } -static void clicked(GtkButton *, gpointer data) { ++static_cast(data)->clicked; } -static void toggled(GtkCheckButton *, gpointer data) { ++static_cast(data)->toggled; } -static gboolean closed(GtkWindow *, gpointer data) { - ++static_cast(data)->closed; - return FALSE; -} - -template -static bool pumpUntil(Clock::time_point limit, Predicate done) { - // No blocking iteration or unbounded drain: even a busy source observes time. - while (Clock::now() < limit) { - if (done()) return true; - g_main_context_iteration(nullptr, FALSE); - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - return done(); -} -static bool focused(State &state, GtkWidget *target) { - GtkWidget *focus = gtk_window_get_focus(state.window); - return focus && (focus == target || gtk_widget_is_ancestor(focus, target)); -} -static NSDictionary *queueKeys(State &state, NSWindow *native, double seconds) { - require(std::isfinite(seconds) && seconds >= 1 && seconds <= 4294967296.0 && - std::floor(seconds) == seconds, "timestamp must be a bounded whole second"); - NSString *characters = state.stage == 0 ? @"n" : @" "; - const unsigned short code = state.stage == 0 ? 45 : 49; - state.times[state.stage] = static_cast(static_cast(seconds * 1000.0)); - for (const NSEventType type : {NSEventTypeKeyDown, NSEventTypeKeyUp}) { - NSEvent *event = [NSEvent keyEventWithType:type location:NSZeroPoint modifierFlags:0 - timestamp:seconds windowNumber:native.windowNumber context:nil characters:characters - charactersIgnoringModifiers:characters isARepeat:NO keyCode:code]; - require(event && event.window == native && event.windowNumber == native.windowNumber && - event.timestamp == seconds && event.type == type && event.keyCode == code && - event.modifierFlags == 0 && [event.characters isEqualToString:characters] && - [event.charactersIgnoringModifiers isEqualToString:characters], "queued event metadata mismatch"); - [NSApp postEvent:event atStart:NO]; - } - char encoded[64]; - std::snprintf(encoded, sizeof encoded, "%a", seconds); - return @{@"stage":@(state.stage), @"timestamp_seconds":@(seconds), - @"timestamp_hex":text(encoded), @"gdk_time_ms":@(state.times[state.stage]), - @"keycode":@(code), @"keyval":@(state.stage == 0 ? GDK_KEY_n : GDK_KEY_space), - @"modifiers":@0, @"queued_count":@2, @"window_number":@(native.windowNumber)}; -} - -static NSDictionary *fontProof(GtkWidget *widget) { - PangoContext *context = gtk_widget_get_pango_context(widget); - require(context != nullptr, "GTK Pango context absent"); - PangoFontMap *map = pango_context_get_font_map(context); - require(PANGO_IS_CAIRO_FONT_MAP(map), "Pango font map is not Cairo"); - require(pango_cairo_font_map_get_font_type(PANGO_CAIRO_FONT_MAP(map)) == CAIRO_FONT_TYPE_QUARTZ, - "Pango Cairo font map is not Quartz"); - PangoFontDescription *description = pango_font_description_from_string("Sans 12"); - require(description != nullptr, "font description failed"); - PangoFont *font = pango_context_load_font(context, description); - pango_font_description_free(description); - require(font != nullptr, "CoreText font load failed"); - // Pango's CoreText implementation header is not installed. Observe the font - // through installed PangoCairo/HarfBuzz APIs instead of declaring its internals. - cairo_scaled_font_t *scaled = PANGO_IS_CAIRO_FONT(font) - ? pango_cairo_font_get_scaled_font(PANGO_CAIRO_FONT(font)) : nullptr; - const bool quartz = scaled && cairo_scaled_font_status(scaled) == CAIRO_STATUS_SUCCESS && - cairo_scaled_font_get_type(scaled) == CAIRO_FONT_TYPE_QUARTZ; - hb_font_t *hbfont = pango_font_get_hb_font(font); // Borrowed from this exact Pango font. - CTFontRef native = hbfont && hbfont != hb_font_get_empty() ? hb_coretext_font_get_ct_font(hbfont) : nullptr; - const bool nativeValid = native && CTFontGetSize(native) > 0; - NSString *fontType = text(G_OBJECT_TYPE_NAME(font)); - g_object_unref(font); - require(quartz && nativeValid, "actual Pango font lacks Quartz/CoreText backing"); - PangoLayout *layout = pango_layout_new(context); - require(layout != nullptr, "Pango layout failed"); - pango_layout_set_text(layout, "Ny GTK", -1); - int width = 0, height = 0; - pango_layout_get_pixel_size(layout, &width, &height); - g_object_unref(layout); - require(width > 0 && width < 4096 && height > 0 && height < 4096, "invalid Pango layout size"); - return @{@"font_type":fontType, @"font_map_type":text(G_OBJECT_TYPE_NAME(map)), - @"quartz":@YES, @"coretext":@YES, @"width":@(width), @"height":@(height)}; -} -static NSDictionary *pngProof() { - static const guchar bytes[] = { - 0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0,0,0,0xd,0x49,0x48,0x44,0x52, - 0,0,0,1,0,0,0,1,8,6,0,0,0,0x1f,0x15,0xc4,0x89,0,0,0,0xd,0x49,0x44,0x41, - 0x54,0x78,0x9c,0x63,0x10,0x54,0x32,0xfe,0xf,0,2,0x14,1,0x66,4,0xe0,0xde, - 0x7f,0,0,0,0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82}; - GError *error = nullptr; - GdkPixbufLoader *loader = gdk_pixbuf_loader_new_with_type("png", &error); - if (error) g_error_free(error); - require(loader != nullptr, "PNG loader missing"); - error = nullptr; - bool okay = gdk_pixbuf_loader_write(loader, bytes, sizeof bytes, &error); - if (error) g_error_free(error); - error = nullptr; - const bool complete = gdk_pixbuf_loader_close(loader, &error); - if (error) g_error_free(error); - GdkPixbuf *pixbuf = gdk_pixbuf_loader_get_pixbuf(loader); - okay = okay && complete && pixbuf && gdk_pixbuf_get_width(pixbuf) == 1 && - gdk_pixbuf_get_height(pixbuf) == 1 && gdk_pixbuf_get_n_channels(pixbuf) == 4 && - gdk_pixbuf_get_has_alpha(pixbuf) && gdk_pixbuf_get_bits_per_sample(pixbuf) == 8; - const guchar *pixel = okay ? gdk_pixbuf_read_pixels(pixbuf) : nullptr; - okay = okay && pixel && pixel[0] == 17 && pixel[1] == 34 && pixel[2] == 51 && pixel[3] == 255; - g_object_unref(loader); - require(okay, "PNG pixel oracle failed"); - return @{@"width":@1, @"height":@1, @"channels":@4, @"rgba":@[@17,@34,@51,@255], @"decoded":@YES}; -} - -int main(int argc, char **) { - const auto started = Clock::now(); - const auto workLimit = started + std::chrono::seconds(24); - const auto wholeLimit = started + std::chrono::seconds(29); - @autoreleasepool { - NSMutableDictionary *report = [@{@"schema":@"nil.macos-gtk-provider-smoke.v1", - @"scope":@"private-provider-own-process", @"status":@"FAIL", - @"language_acceptance":@NO, @"main_thread":@(pthread_main_np() != 0)} mutableCopy]; - State state; - __strong NSWindow *native = nil; - bool initialized = false, bodyPassed = false; - @try { - try { - require(argc == 1, "smoke takes no arguments"); - require(pthread_main_np() != 0, "GTK must initialize on process main thread"); - require(g_strcmp0(g_getenv("GDK_BACKEND"), "macos") == 0 && - g_strcmp0(g_getenv("GSK_RENDERER"), "cairo") == 0, "explicit Macos/Cairo profile required"); - require(gtk_init_check(), "gtk_init_check failed"); - initialized = true; - GdkDisplay *display = gdk_display_get_default(); - require(display && GDK_IS_MACOS_DISPLAY(display), "live display is not Macos"); - require(g_list_model_get_n_items(gtk_window_get_toplevels()) == 0, "unexpected initial GTK windows"); - report[@"backend"] = text(G_OBJECT_TYPE_NAME(display)); - report[@"versions"] = @{@"gtk_header":[NSString stringWithFormat:@"%u.%u.%u",GTK_MAJOR_VERSION,GTK_MINOR_VERSION,GTK_MICRO_VERSION], - @"gtk_runtime":[NSString stringWithFormat:@"%u.%u.%u",gtk_get_major_version(),gtk_get_minor_version(),gtk_get_micro_version()], - @"pango_header":text(PANGO_VERSION_STRING), @"pango_runtime":text(pango_version_string()), - @"pixbuf_header":text(GDK_PIXBUF_VERSION), @"pixbuf_runtime":text(gdk_pixbuf_version), - @"png_header":text(PNG_LIBPNG_VER_STRING), @"png_runtime":text(png_get_libpng_ver(nullptr))}; - require(gtk_get_major_version() == GTK_MAJOR_VERSION && gtk_get_minor_version() == GTK_MINOR_VERSION && - gtk_get_micro_version() == GTK_MICRO_VERSION && - std::strcmp(PANGO_VERSION_STRING,pango_version_string()) == 0 && - std::strcmp(GDK_PIXBUF_VERSION,gdk_pixbuf_version) == 0 && - std::strcmp(PNG_LIBPNG_VER_STRING,png_get_libpng_ver(nullptr)) == 0, "header/runtime version mismatch"); - report[@"origins"] = @{@"gtk":origin((const void *)>k_init_check), - @"pango":origin((const void *)&pango_font_get_hb_font), - @"pangocairo":origin((const void *)&pango_cairo_font_map_get_default), - @"harfbuzz":origin((const void *)&hb_coretext_font_get_ct_font), - @"pixbuf":origin((const void *)&gdk_pixbuf_loader_new_with_type), - @"glib":origin((const void *)&g_main_context_iteration), - @"gobject":origin((const void *)&g_object_ref), @"cairo":origin((const void *)&cairo_version_string), - @"png":origin((const void *)&png_get_libpng_ver), - @"coretext":origin((const void *)&CTFontGetSize, false), @"appkit":origin((const void *)&NSRectFill, false)}; - report[@"png"] = pngProof(); - state.window = GTK_WINDOW(gtk_window_new()); - g_object_ref(state.window); // Keep one own reference through default close handling. - gtk_window_set_title(state.window, "Ny private GTK provider smoke"); - gtk_window_set_default_size(state.window, 360, 180); - GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); - state.entry = gtk_entry_new(); - state.button = gtk_button_new_with_label("Probe button"); - state.check = gtk_check_button_new_with_label("Probe checkbox"); - gtk_box_append(GTK_BOX(box), state.entry); - gtk_box_append(GTK_BOX(box), state.button); - gtk_box_append(GTK_BOX(box), state.check); - gtk_window_set_child(state.window, box); - g_signal_connect(state.entry, "changed", G_CALLBACK(changed), &state); - g_signal_connect(state.button, "clicked", G_CALLBACK(clicked), &state); - g_signal_connect(state.check, "toggled", G_CALLBACK(toggled), &state); - g_signal_connect(state.window, "close-request", G_CALLBACK(closed), &state); - GtkEventController *controller = gtk_event_controller_key_new(); - gtk_event_controller_set_propagation_phase(controller, GTK_PHASE_CAPTURE); - g_signal_connect(controller, "key-pressed", G_CALLBACK(keyPressed), &state); - g_signal_connect(controller, "key-released", G_CALLBACK(keyReleased), &state); - gtk_widget_add_controller(GTK_WIDGET(state.window), controller); - gtk_window_present(state.window); - require(pumpUntil(workLimit, [&] {return gtk_widget_get_mapped(GTK_WIDGET(state.window));}), "GTK map timeout"); - state.surface = gtk_native_get_surface(GTK_NATIVE(state.window)); - require(state.surface && GDK_IS_MACOS_SURFACE(state.surface), "window surface is not Macos"); - native = (__bridge NSWindow *)gdk_macos_surface_get_native_window(GDK_MACOS_SURFACE(state.surface)); - require(native && native.windowNumber > 0 && [NSApp.windows containsObject:native], - "public native window unavailable/not in own application"); - GskRenderer *renderer = gtk_native_get_renderer(GTK_NATIVE(state.window)); - require(renderer && GSK_IS_CAIRO_RENDERER(renderer), "actual renderer is not Cairo"); - report[@"renderer"] = text(G_OBJECT_TYPE_NAME(renderer)); - require(pumpUntil(workLimit, [&] {return native.visible && native.keyWindow && NSApp.active;}), "owned window not active/key/visible"); - report[@"font"] = fontProof(state.entry); - require(state.changed == 0 && state.clicked == 0 && state.toggled == 0, "widget callbacks before input"); - NSMutableArray *events = [NSMutableArray array]; - report[@"events"] = events; - const double baseTime = std::floor(NSProcessInfo.processInfo.systemUptime) - 3; - GtkWidget *targets[] = {state.entry, state.button, state.check}; - for (state.stage = 0; state.stage < 3; ++state.stage) { - require(gtk_widget_grab_focus(targets[state.stage]), "widget focus request failed"); - require(pumpUntil(workLimit, [&] {return focused(state,targets[state.stage]);}), "widget focus timeout"); - [events addObject:queueKeys(state,native,baseTime + state.stage)]; - require(pumpUntil(workLimit, [&] { - const bool outcome = state.stage == 0 ? state.changed == 1 : state.stage == 1 ? state.clicked == 1 : state.toggled == 1; - return state.invalid || (outcome && state.presses[state.stage] == 1 && state.releases[state.stage] == 1); - }), "queued GTK input/outcome timeout"); - require(!state.invalid, "unexpected/duplicate GTK key observation"); - } - require(std::strcmp(gtk_editable_get_text(GTK_EDITABLE(state.entry)), "n") == 0 && - state.changed == 1 && state.clicked == 1 && state.toggled == 1 && - gtk_check_button_get_active(GTK_CHECK_BUTTON(state.check)), "widget outcome mismatch"); - report[@"widgets"] = @{@"entry_text":@"n", @"entry_changed":@(state.changed), - @"button_clicked":@(state.clicked), @"checkbox_toggled":@(state.toggled), @"checkbox_active":@YES}; - [native performClose:nil]; // Only this owned window; normal GTK close-request path. - require(pumpUntil(workLimit, [&] {return state.closed == 1 && g_list_model_get_n_items(gtk_window_get_toplevels()) == 0 && !native.visible;}), "normal close timeout"); - bodyPassed = true; - } catch (const std::exception &error) { report[@"error"] = text(error.what()); } - } @catch (NSException *error) { - report[@"error"] = @"Objective-C exception"; - report[@"exception_name"] = error.name ?: @"unknown"; - } - // Failure cleanup is independent of acceptance; never change FAIL into PASS. - bool cleanup = false, ownWindowHidden = false; - @try { - if (state.window) gtk_window_destroy(state.window); - cleanup = !initialized || pumpUntil(wholeLimit, [&] { - return g_list_model_get_n_items(gtk_window_get_toplevels()) == 0 && (!native || !native.visible); - }); - ownWindowHidden = !native || !native.visible; - if (state.window) { g_object_unref(state.window); state.window = nullptr; } - native = nil; - } @catch (NSException *) { cleanup = false; } - report[@"observed_keys"] = @[@{@"pressed":@(state.presses[0]), @"released":@(state.releases[0])}, - @{@"pressed":@(state.presses[1]), @"released":@(state.releases[1])}, - @{@"pressed":@(state.presses[2]), @"released":@(state.releases[2])}]; - report[@"unexpected_keys"] = @(state.unexpected_keys); - NSMutableArray *dispatched = [NSMutableArray array]; - for (unsigned index = 0; index < state.key_count; ++index) { - const auto &key = state.keys[index]; - [dispatched addObject:@{@"stage":@(key.stage), @"keyval":@(key.keyval), @"keycode":@(key.keycode), - @"modifiers":@(key.modifiers), @"gdk_time_ms":@(key.time), @"release":@(key.release), - @"own_surface":@(key.own_surface), @"matches":@(key.matches)}]; - } - report[@"dispatched_keys"] = dispatched; - report[@"close_requests"] = @(state.closed); - report[@"cleanup"] = @{@"verified":@(cleanup), @"own_window_hidden":@(ownWindowHidden), - @"gtk_toplevel_count":@(initialized ? g_list_model_get_n_items(gtk_window_get_toplevels()) : 0)}; - const double elapsed = std::chrono::duration(Clock::now()-started).count(); - report[@"elapsed_seconds"] = @(elapsed); - const bool passed = bodyPassed && cleanup && ownWindowHidden && !state.invalid && state.key_count == 6 && elapsed <= 29; - report[@"status"] = passed ? @"PASS" : @"FAIL"; - NSError *error = nil; - NSData *json = [NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingSortedKeys error:&error]; - if (!json || json.length > 32768 || std::fwrite(json.bytes, 1, json.length, stdout) != json.length || std::putchar('\n') == EOF) - return 2; - return passed ? 0 : 1; - } -} diff --git a/scripts/ci/macos-gtk-provider.py b/scripts/ci/macos-gtk-provider.py deleted file mode 100644 index 56884a77..00000000 --- a/scripts/ci/macos-gtk-provider.py +++ /dev/null @@ -1,668 +0,0 @@ -#!/usr/bin/env python3 -"""Build a pinned, private GTK provider and observe its public macOS API only.""" -from __future__ import annotations -import argparse -import hashlib -import importlib.util -import json -import math -import os -from pathlib import Path, PurePosixPath -import platform -import re -import shlex -import stat -import struct -import sys -import tarfile -import time -import zipfile - -ROOT = Path(__file__).resolve().parents[2] -LOCK = ROOT / 'scripts/ci/macos-gtk-provider-lock.json' -TOTAL_SECONDS, RESERVE_SECONDS = 1800, 30 -MiB = 1024**2 -MAX_OUTPUT, MAX_TOTAL_OUTPUT = 8 * MiB, 128 * MiB -MAX_ENTRIES, MAX_EXPANDED, MAX_FILE = 20000, 256 * MiB, 16 * MiB -INPUTS = ('scripts/ci/macos-gtk-provider.py', 'scripts/ci/macos-gtk-provider-lock.json', - 'scripts/ci/macos-gtk-provider-smoke.mm', 'scripts/ci/macos-ui-probes.py', - 'tests/tools/ordinary_io_parity_contract.py', 'validation/ny-3d/scripts/debugger_process.py') -BUILD_ORDER = ('fribidi-1.0.16', 'pango-1.56.4', 'gdk-pixbuf-2.42.12', - 'graphene-1.10.8', 'libepoxy-1.5.10', 'gtk-4.18.6') -IMAGE_SOURCE = r''' -#include -#include -#include -#include -#include -#include -static bool origin(const char *name, const void *symbol) { - Dl_info d{}; if (!dladdr(symbol, &d) || !d.dli_fname) return false; - std::printf("%s_path=%s\n", name, d.dli_fname); return true; -} -int main() { - // Encode then decode actual RGBA pixels through the selected PNG runtime. - const unsigned char pixels[4] = {17, 29, 43, 255}; - unsigned char encoded[1024]{}, decoded[4]{}; - png_alloc_size_t bytes = sizeof(encoded); - png_image image{}; image.version = PNG_IMAGE_VERSION; image.width = image.height = 1; - image.format = PNG_FORMAT_RGBA; - bool ok = png_image_write_to_memory(&image, encoded, &bytes, 0, pixels, 0, nullptr) != 0; - png_image read{}; read.version = PNG_IMAGE_VERSION; - ok = ok && png_image_begin_read_from_memory(&read, encoded, bytes); - read.format = PNG_FORMAT_RGBA; - ok = ok && read.width == 1 && read.height == 1 && - png_image_finish_read(&read, nullptr, decoded, 0, nullptr) && !std::memcmp(pixels, decoded, 4); - png_image_free(&read); png_image_free(&image); - jpeg_decompress_struct jpeg{}; jpeg_error_mgr errors{}; - jpeg.err = jpeg_std_error(&errors); jpeg_create_decompress(&jpeg); jpeg_destroy_decompress(&jpeg); - std::printf("png_header=%lu\npng_runtime=%lu\npng_roundtrip=%s\njpeg_header=%d\njpeg_abi=passed\ntiff_header=%d\ntiff_runtime=%d\n", - static_cast(PNG_LIBPNG_VER), static_cast(png_access_version_number()), - ok ? "passed" : "failed", JPEG_LIB_VERSION, TIFFLIB_VERSION, - std::strncmp(TIFFGetVersion(), TIFFLIB_VERSION_STR, std::strlen(TIFFLIB_VERSION_STR)) == 0); - bool paths = origin("png", reinterpret_cast(&png_access_version_number)) && - origin("tiff", reinterpret_cast(&TIFFGetVersion)) && - origin("jpeg", reinterpret_cast(&jpeg_std_error)); - return ok && paths && PNG_LIBPNG_VER == png_access_version_number() && - std::strncmp(TIFFGetVersion(), TIFFLIB_VERSION_STR, std::strlen(TIFFLIB_VERSION_STR)) == 0 ? 0 : 2; -} -''' - - -def require(value, message): - if not value: - raise ValueError(message) - - -def load(name, relative): - spec = importlib.util.spec_from_file_location(name, ROOT / relative) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def save(path, value): - with path.open('x', encoding='utf-8') as stream: - json.dump(value, stream, indent=2, sort_keys=True) - stream.write('\n') - - -def digest_json(value): - return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest() - - -def remaining(deadline, limit): - left = deadline - time.monotonic() - require(left > 0, 'Whole provider deadline exceeded') - return min(left, limit) - - -def safe_name(raw): - path = PurePosixPath(raw) - require(raw and not path.is_absolute() and '..' not in path.parts and '\\' not in raw and - not any(ord(c) < 32 for c in raw) and path.as_posix() == raw.rstrip('/'), 'Unsafe archive member name') - return path - - -def member_manifest(members, root): - require(0 < len(members) <= MAX_ENTRIES, 'Archive entry bound exceeded') - rows, names, total = [], {}, 0 - for member in members: - path = safe_name(member.name) - require(path.parts[0] == root and path.as_posix() not in names, 'Archive root/duplicate differs') - require(member.isdir() or member.isfile() or member.issym(), 'Archive contains unsupported type') - require(not member.mode & 0o7000 and type(member.mtime) in (int, float) and - math.isfinite(member.mtime) and 0 <= member.mtime <= 4102444800, 'Invalid archive mode/time') - require(0 <= member.size <= MAX_FILE and (member.isfile() or member.size == 0), 'Archive member size exceeds bound') - total += member.size - require(total <= MAX_EXPANDED, 'Archive expanded size exceeds bound') - names[path.as_posix()] = member - rows.append({'name': member.name, 'kind': 'directory' if member.isdir() else 'file' if member.isfile() else 'symlink', - 'size': member.size, 'mode': member.mode, 'mtime': member.mtime, 'link': member.linkname}) - for name, member in names.items(): - path = PurePosixPath(name) - for parent in path.parents: - require(str(parent) not in names or names[str(parent)].isdir(), 'Archive parent is not a directory') - if member.issym(): - # The locked GdkPixbuf aliases are single-basename references to - # existing regular test images, never traversed during extraction. - link = safe_name(member.linkname) - target = (path.parent / link).as_posix() - require(len(link.parts) == 1 and target in names and names[target].isfile(), 'Archive alias target is not a sibling regular file') - require(root in names and names[root].isdir(), 'Archive root directory missing') - return rows, {'entries': len(rows), 'expanded_bytes': total, - 'maximum_file_bytes': max(m.size for m in members), 'manifest_sha256': digest_json(rows)} - - -def extract_source(archive, destination, item, deadline, record): - require(record(archive, deadline)['sha256'] == item['sha256'] and archive.stat().st_size == item['bytes'], 'Release archive digest/size differs') - require(destination.is_dir() and not any(destination.iterdir()), 'Fresh extraction directory required') - with tarfile.open(archive, 'r:xz') as source: - members = [] - for member in source: - remaining(deadline, 1); members.append(member) - require(len(members) <= MAX_ENTRIES, 'Archive entry bound exceeded') - rows, inventory = member_manifest(members, item['root']) - require(inventory == item['members'], 'Locked release member inventory differs') - for member in members: - remaining(deadline, 1) - target = destination.joinpath(*PurePosixPath(member.name).parts) - if member.isdir(): - target.mkdir(parents=True, exist_ok=True) - elif member.isfile(): - target.parent.mkdir(parents=True, exist_ok=True) - with source.extractfile(member) as incoming, target.open('xb') as outgoing: - copied = 0 - while block := incoming.read(MiB): - remaining(deadline, 1); copied += len(block) - require(copied <= member.size, 'Archive member grew') - outgoing.write(block) - require(copied == member.size, 'Archive member truncated') - target.chmod(0o755 if member.mode & 0o111 else 0o644) - os.utime(target, (member.mtime, member.mtime), follow_symlinks=False) - # All links were checked against regular, non-link archive members. - for member in members: - if member.issym(): - destination.joinpath(*PurePosixPath(member.name).parts).symlink_to(member.linkname) - for member in reversed(members): - if member.isdir(): - os.utime(destination / member.name, (member.mtime, member.mtime), follow_symlinks=False) - for name, expected in item['required_files'].items(): - actual = record(destination / name, deadline) - require({k: actual[k] for k in ('bytes', 'sha256')} == expected, 'Required generated/build input differs: ' + name) - return inventory - - -def extract_meson(archive, destination, item, deadline, record): - actual = record(archive, deadline) - require({k: actual[k] for k in ('bytes', 'sha256')} == {k: item[k] for k in ('bytes', 'sha256')}, 'Meson wheel digest/size differs') - with zipfile.ZipFile(archive) as source: - members = source.infolist() - require(0 < len(members) <= 2000, 'Meson wheel entry bound exceeded') - rows, names, total = [], set(), 0 - for entry in members: - remaining(deadline, 1) - path = safe_name(entry.filename) - mode = entry.external_attr >> 16 - require(path.as_posix() not in names and (stat.S_ISREG(mode) or mode == 0) and not entry.is_dir() and - 0 <= entry.file_size <= MAX_FILE and not mode & 0o7000, 'Invalid Meson wheel member') - names.add(path.as_posix()); total += entry.file_size - require(total <= 32 * MiB, 'Meson expanded bound exceeded') - rows.append({'name': entry.filename, 'bytes': entry.file_size, 'mode': mode, 'compressed_bytes': entry.compress_size}) - require({'entries': len(rows), 'expanded_bytes': total, 'manifest_sha256': digest_json(rows)} == item['members'], 'Locked wheel inventory differs') - for entry in members: - target = destination / entry.filename - target.parent.mkdir(parents=True, exist_ok=True) - with source.open(entry) as incoming, target.open('xb') as outgoing: - copied = 0 - while block := incoming.read(MiB): - remaining(deadline, 1); copied += len(block) - require(copied <= entry.file_size, 'Meson member grew'); outgoing.write(block) - require(copied == entry.file_size, 'Meson member truncated') - target.chmod(0o644) - require((destination / 'mesonbuild/mesonmain.py').is_file(), 'Meson entry point absent') - - -def tree_seal(root, deadline, record): - result, total = {}, 0 - # os.walk never follows directory aliases; internal file symlinks remain - # explicit records, including dangling and external aliases as errors. - for parent, dirs, files in os.walk(root, followlinks=False, onerror=lambda e: (_ for _ in ()).throw(e)): - for name in sorted(dirs + files): - remaining(deadline, 1) - path = Path(parent) / name; mode = path.lstat().st_mode - require(len(result) < 40000, 'Tree entry bound exceeded') - key = path.relative_to(root).as_posix() - if stat.S_ISDIR(mode): - result[key] = {'directory': True, 'mode': stat.S_IMODE(mode)} - elif stat.S_ISLNK(mode): - target = path.resolve(strict=True) - require(root in target.parents and target.is_file(), 'Tree alias leaves prefix or names a directory') - result[key] = {'link': os.readlink(path), 'target': target.relative_to(root).as_posix()} - else: - require(stat.S_ISREG(mode), 'Tree contains special file') - row = record(path, deadline) - result[key] = {k: row[k] for k in ('bytes', 'sha256', 'mode')} - total += row['bytes']; require(total <= 2 * 1024**3, 'Tree byte bound exceeded') - require(result, 'Empty tree seal') - return result - - -def environment(work, inherited=None): - inherited = os.environ if inherited is None else inherited - env = {k: inherited[k] for k in ('HOME', 'USER', 'LOGNAME', '__CF_USER_TEXT_ENCODING') if k in inherited} - env.update(PATH=str(work / 'tool-bin') + ':/usr/bin:/bin:/usr/sbin:/sbin', - LC_ALL='C', LANG='C', TZ='UTC', TMPDIR=str(work / 'tmp'), PYTHONDONTWRITEBYTECODE='1', - ZERO_AR_DATE='1', GIT_OPTIONAL_LOCKS='0') - return env - - -def setup_arguments(meson, source, build, prefix, native_file, item): - return [*meson, 'setup', str(build), str(source), '--prefix=' + str(prefix), '--libdir=lib', - '--buildtype=release', '--default-library=shared', '--wrap-mode=nofallback', - '--native-file=' + str(native_file), *item['options']] - - -def image_result(raw): - result = {} - for line in raw.decode().splitlines(): - key, sep, value = line.partition('=') - require(sep and key not in result and value, 'Invalid image prerequisite record'); result[key] = value - require(set(result) == {'png_header', 'png_runtime', 'png_roundtrip', 'jpeg_header', 'jpeg_abi', - 'tiff_header', 'tiff_runtime', 'png_path', 'tiff_path', 'jpeg_path'}, 'Image prerequisite fields differ') - require(result['png_header'].isdigit() and result['png_header'] == result['png_runtime'] and - result['png_roundtrip'] == result['jpeg_abi'] == 'passed' and result['tiff_runtime'] == '1' and - result['jpeg_header'].isdigit() and result['tiff_header'].isdigit(), 'Image header/runtime operation differs') - return result - - -def smoke_result(row): - require(isinstance(row, dict) and row.get('schema') == 'nil.macos-gtk-provider-smoke.v1' and - row.get('scope') == 'private-provider-own-process' and row.get('status') == 'PASS' and - row.get('language_acceptance') is False and row.get('main_thread') is True and - 'error' not in row, 'GTK smoke identity/status differs') - require(row.get('backend') == 'GdkMacosDisplay' and row.get('renderer') == 'GskCairoRenderer', - 'GTK backend/renderer differs') - versions = row['versions'] - for name, version in (('gtk','4.18.6'),('pango','1.56.4'),('pixbuf','2.42.12')): - require(versions[name+'_header'] == versions[name+'_runtime'] == version, 'GTK provider version differs') - require(isinstance(versions['png_header'], str) and re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', versions['png_header']) and - versions['png_header'] == versions['png_runtime'], 'PNG header/runtime differs') - integer = lambda value, expected: type(value) is int and value == expected - cleanup = row['cleanup'] - require(cleanup.get('verified') is True and cleanup.get('own_window_hidden') is True and integer(cleanup.get('gtk_toplevel_count'), 0), 'GTK cleanup not proven') - require(integer(row.get('unexpected_keys'), 0) and integer(row.get('close_requests'), 1), 'Unexpected key/close count') - elapsed = row.get('elapsed_seconds') - require(type(elapsed) in (int, float) and math.isfinite(elapsed) and 0 <= elapsed <= 29, 'GTK elapsed bound differs') - widgets = row['widgets'] - require(widgets.get('entry_text') == 'n' and widgets.get('checkbox_active') is True and - all(integer(widgets.get(key), 1) for key in ('entry_changed','button_clicked','checkbox_toggled')), - 'GTK widget outcome differs') - png = row['png'] - require(png.get('decoded') is True and integer(png.get('width'), 1) and integer(png.get('height'), 1) and - integer(png.get('channels'), 4) and png.get('rgba') == [17,34,51,255] and - all(type(x) is int for x in png['rgba']), 'GTK PNG pixel oracle differs') - font = row['font'] - require(font.get('quartz') is True and font.get('coretext') is True and - all(type(font.get(key)) is int and 0 < font[key] < 4096 for key in ('width','height')), - 'Pango CoreText/layout proof missing') - require(len(row['events']) == len(row['observed_keys']) == 3, 'GTK event inventory differs') - windows, seconds_seen = set(), [] - for index, event in enumerate(row['events']): - require(all(integer(event.get(key), value) for key, value in ( - ('stage',index), ('keycode',45 if index == 0 else 49), ('keyval',110 if index == 0 else 32), - ('modifiers',0), ('queued_count',2))), 'GTK queued event differs') - seconds = event['timestamp_seconds'] - require(type(seconds) in (int,float) and math.isfinite(seconds) and 1 <= seconds <= 4294967296 and - math.floor(seconds) == seconds and float.fromhex(event['timestamp_hex']) == seconds and - integer(event.get('gdk_time_ms'), int(seconds*1000) % 2**32), 'GTK event timestamp differs') - require(type(event.get('window_number')) is int and event['window_number'] > 0, 'GTK event window differs') - windows.add(event['window_number']); seconds_seen.append(seconds) - require(all(integer(row['observed_keys'][index].get(key), 1) for key in ('pressed','released')), - 'GTK translated key dispatch missing or duplicated') - require(len(windows) == 1 and seconds_seen == [seconds_seen[0]+i for i in range(3)], 'GTK event identity sequence differs') - require(len(row['dispatched_keys']) == 6, 'GTK actual dispatch inventory differs') - for index, key in enumerate(row['dispatched_keys']): - event = row['events'][index//2] - require(all(integer(key.get(name), event[name]) for name in ('stage','keyval','keycode','modifiers','gdk_time_ms')) and - key.get('release') is bool(index%2) and key.get('own_surface') is True and key.get('matches') is True, - 'GTK dispatched event metadata differs from own queued event') - origins = row['origins'] - require(set(origins) == {'gtk','pango','pangocairo','pixbuf','glib','gobject','cairo','png','harfbuzz','coretext','appkit'}, - 'GTK runtime origin inventory differs') - for key, value in origins.items(): - require(isinstance(value, dict) and isinstance(value.get('declared'), str) and - value['declared'].startswith('/') and len(value['declared']) <= 4096, 'GTK declared origin invalid') - if key in ('coretext','appkit'): - require(system_library(value['declared']) and type(value.get('file_backed')) is bool and - (value['canonical'] is None) == (not value['file_backed']), 'Apple framework origin differs') - else: - require(value.get('file_backed') is True and isinstance(value.get('canonical'), str) and - value['canonical'].startswith('/'), 'GTK file-backed origin absent') - return row - - -def macho_header(raw, architecture): - require(len(raw) == 32, 'Truncated Mach-O header') - magic, cpu, subtype, kind, commands, size, flags, reserved = struct.unpack('<8I', raw) - require(magic == 0xfeedfacf and cpu == {'arm64':0x100000c,'x86_64':0x1000007}[architecture] and - kind in (2,6,8) and 0 < commands <= 4096 and 0 < size <= 16*MiB, - 'Loader file is not the declared native64 executable/dylib/bundle') - return {'architecture':architecture,'cpu':cpu,'subtype':subtype,'file_type':kind, - 'load_commands':commands,'command_bytes':size,'flags':flags,'reserved':reserved} - - -def loader_commands(raw): - commands, current = [], None - for line in raw.decode().splitlines(): - value = line.strip() - if value.startswith('cmd '): - current = {'command': value[4:]} - if current['command'] in ('LC_ID_DYLIB', 'LC_LOAD_DYLIB', 'LC_LOAD_WEAK_DYLIB', 'LC_REEXPORT_DYLIB', - 'LC_LOAD_UPWARD_DYLIB', 'LC_LAZY_LOAD_DYLIB', 'LC_RPATH'): - commands.append(current) - elif current in commands and (value.startswith('name ') or value.startswith('path ')): - current['path'] = value.split(' ', 1)[1].rsplit(' (offset ', 1)[0] - require(len(commands) <= 256 and all(x.get('path') for x in commands), 'Malformed loader command inventory') - return commands - - -def system_library(name): - return name.startswith('/usr/lib/') or name.startswith('/System/Library/') - - -def resolve_load(name, owner, rpaths, executable): - def expand(value): - if value == '@loader_path': - return owner.parent - if value == '@executable_path': - return executable.parent - if value.startswith('@loader_path/'): - return owner.parent / value[len('@loader_path/'):] - if value.startswith('@executable_path/'): - return executable.parent / value[len('@executable_path/'):] - require(value.startswith('/'), 'Unresolved loader placeholder: ' + value) - return Path(value) - if name.startswith('@rpath/'): - candidates = [expand(value) / name[len('@rpath/'):] for value in rpaths] - existing = [path for path in candidates if path.is_file()] - require(existing, 'Unresolved @rpath dependency: ' + name) - return existing[0].resolve(strict=True) - return expand(name).resolve(strict=True) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--output', required=True, type=Path) - parser.add_argument('--work-dir', required=True, type=Path) - parser.add_argument('--revision', required=True) - parser.add_argument('--architecture', required=True, choices=('arm64', 'x86_64')) - args = parser.parse_args() - require(sys.platform == 'darwin' and platform.machine() == args.architecture and platform.mac_ver()[0].split('.')[0] == '15', 'Native macOS15 matching architecture required') - require(re.fullmatch('[0-9a-f]{40}', args.revision), 'Exact source revision required') - ui = load('gtk_provider_ui_support', 'scripts/ci/macos-ui-probes.py') - output, work = ui.paths(args.output, args.work_dir) - output.mkdir(parents=True, mode=0o700); work.mkdir(mode=0o700) - logs, prefix = output / 'logs', work / 'prefix' - for path in (logs, prefix, work / 'tmp', work / 'tool-bin', work / 'sources', work / 'builds', work / 'meson'): - path.mkdir(mode=0o700) - started = time.monotonic(); final = started + TOTAL_SECONDS; deadline = final - RESERVE_SECONDS - report = {'schema': 'nil.macos.gtk-provider.v1', 'status': 'FAIL', 'qualification': False, - 'sdk_replaced': False, 'product_runtime_admitted': False, - 'scope': 'Private prefix build and public GTK API observation only; host-dependent, not redistributed', - 'revision': args.revision, 'architecture': args.architecture, 'prefix': str(prefix), - 'work_dir': str(work), 'work_retained': True, 'phases': [], 'problems': [], 'phase': 'initialize', - 'limits': {'whole_seconds': TOTAL_SECONDS, 'reserve_seconds': RESERVE_SECONDS, 'parallel_jobs': 2, - 'phase_output_bytes': MAX_OUTPUT, 'aggregate_output_bytes': MAX_TOTAL_OUTPUT}} - inputs, releases, sources, source_seals, external = {}, {}, {}, {}, {} - support = ownership = None; prefix_before = None; total_output = 0 - variables = environment(work) - homebrew = Path('/opt/homebrew' if args.architecture == 'arm64' else '/usr/local') - def seal(path): - row = ui.record(Path(path), deadline) - require(str(path) not in inputs or inputs[str(path)] == row, 'Previously sealed input changed: ' + str(path)) - inputs[str(path)] = row - return row - def run(name, argv, seconds=30, *, cwd=work, env=None, final_check=False, check_exit=True): - nonlocal total_output - if not final_check: - report['phase'] = name - row = support.run_process(ownership, [str(x) for x in argv], cwd, env or variables, logs, - name, remaining(final - 5 if final_check else deadline, seconds)) - report['phases'].append(row); save(logs / (name + '.json'), row) - for key in ('stdout_record', 'stderr_record'): - total_output += row.get(key, {}).get('bytes', 0) - require(total_output <= MAX_TOTAL_OUTPUT, 'Aggregate output bound exceeded') - require(row.get('cleanup_verified') is True and not row.get('error') and (not check_exit or row.get('exit_code') == 0), - name + ': owned phase failed; raw evidence retained') - return (logs / row['stdout']).read_bytes() - def text(name, argv, seconds=10): return run(name, argv, seconds).decode().strip() - def flags(name, argv): - result = shlex.split(text(name, argv)) - require(len(result) <= 256 and not any('\0' in x or '\n' in x for x in result), 'Compiler flag inventory invalid') - return result - def header_seal(name, compiler, source, cflags): - target = output / (name + '-headers.d') - run(name + '-headers', [compiler, '-isysroot', sdk, '-M', '-MF', target, source, *cflags], 30) - raw = target.read_text().replace('\\\n', '') - require(len(raw) <= MiB and ':' in raw, 'Invalid header dependency output') - headers = shlex.split(raw.split(':', 1)[1]); require(0 < len(headers) <= 5000, 'Header inventory bound exceeded') - for header in headers: - path = Path(header).resolve(strict=True) - # SDK/system headers are covered by declared selected SDK metadata; - # every non-SDK header participating in the probe is byte-sealed. - if sdk not in path.parents and not str(path).startswith('/Library/Developer/CommandLineTools/SDKs/'): - seal(path) - return headers - try: - for name in INPUTS: seal(ROOT / name) - lock = json.loads(LOCK.read_bytes()) - require(lock['schema'] == 'nil.macos.gtk-provider-lock.v1' and tuple(x['root'] for x in lock['sources']) == BUILD_ORDER, 'Provider lock/profile differs') - support = load('gtk_provider_capture', 'tests/tools/ordinary_io_parity_contract.py') - support.MAX_OUTPUT = MAX_OUTPUT; ownership = support.load_ownership(ROOT) - require(text('revision-before', ['/usr/bin/git', '-C', ROOT, 'rev-parse', 'HEAD']) == args.revision, 'Source revision differs') - require(not text('source-before', ['/usr/bin/git', '-C', ROOT, 'status', '--porcelain', '--untracked-files=no']), 'Clean source required') - baseline = lock['baseline'][args.architecture] - sdk = Path(text('apple-sdk', ['/usr/bin/xcrun', '--sdk', 'macosx', '--show-sdk-path'])).resolve(strict=True) - compiler = Path(text('compiler', ['/usr/bin/xcrun', '--find', 'clang++'])) - ccompiler = Path(text('c-compiler', ['/usr/bin/xcrun', '--find', 'clang'])) - for path in (Path(sys.executable), compiler, ccompiler, sdk / 'SDKSettings.json', Path('/usr/bin/xcrun')): seal(path) - report['toolchain'] = {'sdk': str(sdk), 'compiler': str(compiler), 'c_compiler': str(ccompiler), - 'version': text('compiler-version', [compiler, '--version'])} - # Only explicit build tools are visible in addition to Apple's system - # commands. No incidental Meson/Sass/other package-manager tools enter PATH. - tools = {'python3': Path(sys.executable), 'pkg-config': homebrew/'bin/pkg-config', - 'ninja': homebrew/'bin/ninja', **{name: homebrew/'bin'/name for name in ( - 'glib-compile-resources', 'glib-compile-schemas', 'glib-genmarshal', 'glib-mkenums', - 'gdbus-codegen', 'gio-querymodules', 'msgfmt', 'msgmerge', 'xgettext')}} - for name, path in list(tools.items()): - if name in ('msgfmt', 'msgmerge', 'xgettext') and not path.exists(): - path = homebrew/'opt/gettext/bin'/name - tools[name] = path - seal(path); require(os.access(path, os.X_OK), 'Declared tool not executable: ' + name) - (work / 'tool-bin' / name).symlink_to(path) - pkg = tools['pkg-config']; selected_pkg = ui.pkg_command(pkg, sdk) - compatibility = ui.compatibility_directory(text('pkg-search', [pkg, '--variable=pc_path', 'pkg-config']), homebrew, '15') - require(str(compatibility) == baseline['pkg_config_compatibility'], 'Observed compatibility directory changed') - variables['PKG_CONFIG_LIBDIR'] = ':'.join(str(x) for x in ( - prefix/'lib/pkgconfig', prefix/'share/pkgconfig', homebrew/'lib/pkgconfig', homebrew/'share/pkgconfig', compatibility)) - # Meson invokes this wrapper, so its own dependency resolution uses the - # same selected SDK substitution as the explicit preflight commands. - wrapper = work/'pkg-config' - wrapper.write_text('#!/bin/sh\nexec ' + shlex.join([str(x) for x in selected_pkg]) + ' "$@"\n'); wrapper.chmod(0o700); seal(wrapper) - variables['PKG_CONFIG'] = str(wrapper) - variables['CC'], variables['CXX'] = str(ccompiler), str(compiler) - variables['OBJC'], variables['OBJCXX'] = str(ccompiler), str(compiler) - variables['SDKROOT'] = str(sdk) - variables['MACOSX_DEPLOYMENT_TARGET'] = '15.0' - variables['CFLAGS'] = variables['CXXFLAGS'] = variables['OBJCFLAGS'] = variables['OBJCXXFLAGS'] = '-isysroot ' + shlex.quote(str(sdk)) - report['build_environment'] = dict(variables) - report['build_tools'] = {name: inputs[str(path)] for name, path in tools.items()} - report['required_codec_policy'] = {'source': 'gtk-4.18.6/meson.build', - 'required': ['libpng', 'libtiff-4', 'libjpeg'], 'gdk_pixbuf_builtin_loaders': ['png'], - 'source_sha256': lock['sources'][-1]['required_files']['gtk-4.18.6/meson.build']['sha256']} - packages = {} - for module in (*ui.REQUIRED, 'libpng', 'libtiff-4', 'libjpeg'): - version = text('version-' + module, [*selected_pkg, '--modversion', module]) - packages[module] = {'version': version} - pcdir = Path(text('pcdir-' + module, [*selected_pkg, '--variable=pcfiledir', module])) - require(homebrew.resolve() in pcdir.resolve(strict=True).parents, 'Prerequisite metadata outside selected Homebrew prefix') - seal(pcdir / (module + '.pc')) - for module in ('libffi', 'zlib', 'bzip2', 'expat'): - pcdir = Path(text('system-pcdir-' + module, [*selected_pkg, '--variable=pcfiledir', module])) - require(pcdir.resolve(strict=True) == compatibility.resolve(), 'System pkg metadata origin differs'); seal(pcdir/(module+'.pc')) - for name, expected in baseline['glib_tools'].items(): - require(text(name + '-version', [tools[name], '--version']) == expected['version'], 'GLib tool version differs') - for name, module in (('glib', 'glib-2.0'), ('cairo', 'cairo'), ('harfbuzz', 'harfbuzz')): - require(packages[module]['version'] == baseline['versions'][name], 'Pinned prerequisite version differs') - dependencies = work/'dependencies.cpp'; dependencies.write_text(ui.DEPENDENCY_SOURCE); seal(dependencies) - deps_flags = flags('dependency-flags', [*selected_pkg, '--cflags', '--libs', *ui.REQUIRED]) - header_seal('dependencies', compiler, dependencies, deps_flags) - binary = work/'dependencies' - run('compile-dependencies', [compiler, '-std=c++17', '-Wall', '-Wextra', '-Werror', '-isysroot', sdk, - dependencies, *deps_flags, '-framework', 'CoreText', '-framework', 'CoreGraphics', '-o', binary], 45) - seal(binary); observed, matched = ui.dependency_result(run('load-dependencies', [binary], 10), packages) - require(matched and observed['operations'] == 'passed', 'Prerequisite headers/runtime/operations differ') - loaded = {} - for name, value in observed.items(): - if name.endswith('_path'): - row = seal(Path(value)); loaded[row['canonical_path']] = row - require(set(loaded) == set(baseline['loaded_files']), 'Pinned prerequisite loaded origins differ') - for name, expected in baseline['loaded_files'].items(): - require(all(loaded[name][key] == expected[key] for key in ('bytes', 'sha256', 'mode')), 'Pinned prerequisite bytes differ') - report['prerequisites'] = {'packages': packages, 'operations': observed, 'loaded': loaded} - images = work/'images.cpp'; images.write_text(IMAGE_SOURCE); seal(images) - image_flags = flags('image-flags', [*selected_pkg, '--cflags', '--libs', 'libpng', 'libtiff-4', 'libjpeg']) - header_seal('images', compiler, images, image_flags) - image_binary = work/'images' - run('compile-images', [compiler, '-std=c++17', '-Wall', '-Wextra', '-Werror', '-isysroot', sdk, - images, *image_flags, '-o', image_binary], 45) - seal(image_binary); report['images'] = image_result(run('image-preflight', [image_binary], 10)) - png_version = packages['libpng']['version'].split('.') - require(len(png_version) == 3 and all(x.isdigit() for x in png_version) and - int(report['images']['png_header']) == int(png_version[0])*10000+int(png_version[1])*100+int(png_version[2]), - 'PNG metadata/header/runtime version differs') - for name in ('png', 'tiff', 'jpeg'): - path = Path(report['images'][name+'_path']); require(homebrew.resolve() in path.resolve(strict=True).parents, 'Image runtime leaves declared Homebrew prefix'); seal(path) - # All archives and the wheel are verified/extracted before any of their - # executable build code is run. No fetch fallback or package installation. - items = [*lock['sources'], {**lock['meson'], 'name': lock['meson']['filename']}] - for index, item in enumerate(items): - archive = work/item['name'] - run('download-' + str(index), ['/usr/bin/curl', '--disable', '--fail', '--location', '--silent', '--show-error', - '--proto', '=https', '--proto-redir', '=https', '--connect-timeout', '15', '--max-time', '55', - '--max-filesize', str(item['bytes']), '--output', archive, item['url']], 60) - releases[item['name']] = seal(archive) - if 'root' in item: - dest = work/'sources'/item['root']; dest.mkdir() - extract_source(archive, dest, item, deadline, ui.record) - source = dest/item['root']; sources[item['root']] = source - source_seals[item['root']] = tree_seal(source, deadline, ui.record) - else: - extract_meson(archive, work/'meson', item, deadline, ui.record) - sources['meson-wheel'] = work/'meson' - source_seals['meson-wheel'] = tree_seal(work/'meson', deadline, ui.record) - save(output/'release-inputs.json', {'archives': releases, 'sources': source_seals, 'lock': inputs[str(LOCK)]}) - launcher = work/'meson-launch.py' - launcher.write_text('import runpy,sys\nsys.path.insert(0,' + repr(str(work/'meson')) + ')\nrunpy.run_module("mesonbuild.mesonmain",run_name="__main__")\n'); seal(launcher) - meson = [sys.executable, '-I', '-B', launcher] - require(text('meson-version', [*meson, '--version']) == lock['meson']['version'], 'Pinned Meson version differs') - native = work/'native.ini' - native.write_text('[binaries]\nc = '+repr(str(ccompiler))+'\ncpp = '+repr(str(compiler))+'\nobjc = '+repr(str(ccompiler))+'\nobjcpp = '+repr(str(compiler))+'\npkg-config = '+repr(str(wrapper))+'\n') - seal(native) - for item in lock['sources']: - name = item['root']; build = work/'builds'/name - run(name+'-configure', setup_arguments(meson, sources[name], build, prefix, native, item), 90) - run(name+'-build', [*meson, 'compile', '-C', build, '--jobs=2'], 600) - run(name+'-install', [*meson, 'install', '-C', build, '--no-rebuild'], 60) - report['provider_packages'] = {} - for module, version in (('fribidi','1.0.16'),('pango','1.56.4'),('pangocairo','1.56.4'),('gdk-pixbuf-2.0','2.42.12'),('graphene-gobject-1.0','1.10.8'),('epoxy','1.5.10'),('gtk4','4.18.6')): - actual = text('installed-version-'+module, [*selected_pkg, '--modversion', module]) - pcdir = Path(text('installed-pcdir-'+module, [*selected_pkg,'--variable=pcfiledir',module])).resolve(strict=True) - require(actual == version and prefix in pcdir.parents, 'Installed provider metadata differs') - report['provider_packages'][module] = {'version': actual, 'metadata': seal(pcdir/(module+'.pc'))} - require((prefix/'share/glib-2.0/schemas/gschemas.compiled').is_file(), 'Compiled GTK schemas missing') - prefix_before = tree_seal(prefix, deadline, ui.record); save(output/'prefix-before.json', prefix_before) - smoke_source = ROOT/'scripts/ci/macos-gtk-provider-smoke.mm' - smoke_flags = flags('smoke-flags', [*selected_pkg, '--cflags', '--libs', 'gtk4-macos', 'pangocairo', 'gdk-pixbuf-2.0', 'libpng', 'harfbuzz']) - smoke = work/'gtk-smoke' - header_seal('smoke', compiler, smoke_source, smoke_flags) - run('compile-smoke', [compiler, '-std=c++17', '-fobjc-arc', '-Wall', '-Wextra', '-Werror', - '-isysroot', sdk, '-mmacosx-version-min=15.0', smoke_source, *smoke_flags, - '-framework', 'AppKit', '-framework', 'CoreText', '-o', smoke], 60) - seal(smoke) - # Walk every private Mach-O and its complete non-system dependency graph. - # Apple cache/framework loads are explicit boundaries, not hashed closure. - pending = [smoke] - for key, item in prefix_before.items(): - if 'sha256' in item: - path = prefix/key - with path.open('rb') as stream: magic = stream.read(4) - if magic in (b'\xcf\xfa\xed\xfe', b'\xce\xfa\xed\xfe', b'\xca\xfe\xba\xbe'): - pending.append(path) - closure = {}; executable_rpaths = [] - while pending: - path = pending.pop(0).resolve(strict=True) - if str(path) in closure: continue - require(len(closure) < 256, 'Loader closure bound exceeded') - with path.open('rb') as stream: - header = macho_header(stream.read(32), args.architecture) - commands = loader_commands(run('loader-'+str(len(closure)), ['/usr/bin/otool', '-l', path], 10)) - rpaths = [x['path'] for x in commands if x['command'] == 'LC_RPATH'] - if path == smoke: executable_rpaths = rpaths - row = {'file': seal(path), 'header': header, 'commands': commands, 'loads': []}; closure[str(path)] = row - for command in commands: - if command['command'] in ('LC_ID_DYLIB','LC_RPATH'): continue - name = command['path'] - if system_library(name): - row['loads'].append({'name': name, 'system_cache_or_framework_boundary': True}); continue - target = resolve_load(name, path, rpaths+executable_rpaths, smoke) - require(prefix in target.parents or homebrew.resolve() in target.parents, 'Loader dependency leaves declared roots') - row['loads'].append({'name': name, 'target': str(target)}) - external[str(target)] = seal(target); pending.append(target) - save(output/'loader-closure.json', closure) - smoke_env = dict(variables, GSK_RENDERER='cairo', GDK_BACKEND='macos', - GSETTINGS_SCHEMA_DIR=str(prefix/'share/glib-2.0/schemas'), GSETTINGS_BACKEND='memory', - XDG_DATA_DIRS=str(prefix/'share'), XDG_CACHE_HOME=str(work/'cache'), - XDG_CONFIG_HOME=str(work/'config'), XDG_DATA_HOME=str(work/'data')) - report['smoke_environment'] = {k: smoke_env[k] for k in ('GSK_RENDERER','GDK_BACKEND','GSETTINGS_SCHEMA_DIR','GSETTINGS_BACKEND','XDG_DATA_DIRS','XDG_CACHE_HOME','XDG_CONFIG_HOME','XDG_DATA_HOME')} - raw = run('gtk-smoke', [smoke], 30, env=smoke_env, check_exit=False) - observed = json.loads(raw) - report['smoke'] = observed # retain a failed own-window oracle too - smoke_result(observed) - require(report['phases'][-1]['exit_code'] == 0, 'GTK smoke nonzero exit') - for key, value in observed['origins'].items(): - if key in ('coretext','appkit'): - continue # explicit system-cache/framework boundary - path = Path(value['declared']); row = seal(path) - require(row['canonical_path'] == value['canonical'], 'Observed runtime alias changed') - require(str(path.resolve(strict=True)) in closure, 'Loaded runtime absent from sealed loader closure') - if key in ('gtk','pango','pangocairo','pixbuf'): - require(prefix in path.resolve(strict=True).parents, 'GTK runtime escaped private prefix') - else: - expected = (observed['origins'][key]['canonical']) - original = report['images']['png_path'] if key == 'png' else report['prerequisites']['operations'][key+'_path'] - require(Path(original).resolve(strict=True) == Path(expected), 'GTK loaded prerequisite changed') - report['status'] = 'PASS'; report['phase'] = 'complete' - except Exception as error: - report['problems'].append(type(error).__name__ + ': ' + str(error)) - finally: - # Keep partial configuration and introspection records on every failure; - # work/build trees are retained and never automatically removed. - try: - for build in sorted((work/'builds').iterdir()): - for rel in ('meson-logs/meson-log.txt', 'meson-info/intro-buildoptions.json', - 'meson-info/intro-dependencies.json', 'meson-info/intro-installed.json'): - src = build/rel - if src.exists() or src.is_symlink(): - row = ui.record(src, final-5); require(row['bytes'] <= MAX_OUTPUT, 'Meson diagnostic exceeds bound') - data = src.read_bytes(); require(hashlib.sha256(data).hexdigest() == row['sha256'], 'Meson diagnostic changed') - (output/(build.name+'-'+Path(rel).name)).write_bytes(data) - except Exception as error: report['problems'].append('Partial build evidence: '+str(error)) - for label, action in ( - ('inputs', lambda: {name: ui.record(Path(name), final-5) for name in inputs}), - ('release_sources', lambda: {name: tree_seal(path, final-5, ui.record) for name,path in sources.items()}), - ('prefix', lambda: tree_seal(prefix, final-5, ui.record) if any(prefix.iterdir()) else {})): - try: - value = action(); save(output/(label+'-after.json'), value) - expected = inputs if label == 'inputs' else source_seals if label == 'release_sources' else prefix_before - report[label+'_unchanged'] = value == expected - except Exception as error: - report[label+'_unchanged'] = False; report['problems'].append(label+' final seal: '+str(error)) - report['inputs_before'] = inputs - try: - report['source_unchanged'] = (run('revision-after', ['/usr/bin/git','-C',ROOT,'rev-parse','HEAD'], 5, final_check=True).decode().strip() == args.revision and - not run('source-after', ['/usr/bin/git','-C',ROOT,'status','--porcelain','--untracked-files=no'], 5, final_check=True).strip()) - except Exception as error: - report['source_unchanged'] = False; report['problems'].append('Source final seal: '+str(error)) - report['cleanup_verified'] = bool(report['phases']) and all(x.get('cleanup_verified') is True for x in report['phases']) - report['raw_output_bytes'] = total_output; report['elapsed_seconds'] = time.monotonic()-started - if (report['problems'] or report['elapsed_seconds'] > TOTAL_SECONDS or not report['cleanup_verified'] or - not all(report.get(k) is True for k in ('source_unchanged','inputs_unchanged','release_sources_unchanged','prefix_unchanged'))): - report['status'] = 'FAIL' - save(output/'report.json', report) - print(json.dumps({k:report[k] for k in ('status','phase','prefix','problems','cleanup_verified','elapsed_seconds')})) - return 0 if report['status'] == 'PASS' else 1 - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/scripts/ci/macos-gtk-runtime.py b/scripts/ci/macos-gtk-runtime.py deleted file mode 100644 index 091616a1..00000000 --- a/scripts/ci/macos-gtk-runtime.py +++ /dev/null @@ -1,341 +0,0 @@ -#!/usr/bin/env python3 -"""Bounded standalone Ny UI runtime checks against one unchanged private GTK provider.""" -from __future__ import annotations -import argparse -import hashlib -import importlib.util -import json -import math -import os -from pathlib import Path -import platform -import re -import stat -import sys -import time - -ROOT = Path(__file__).resolve().parents[2] -TOTAL_SECONDS, RESERVE_SECONDS = 180, 20 -MiB = 1024**2 -INPUTS = ('scripts/ci/macos-gtk-runtime.py', 'scripts/ci/macos-gtk-provider.py', - 'scripts/ci/macos-ui-probes.py', 'tests/tools/ordinary_io_parity_contract.py', - 'validation/ny-3d/scripts/debugger_process.py', 'nilcompiler/src/ui_runtime.cpp', - 'nilcompiler/src/ui_runtime.hpp', 'tests/ui_runtime_tests.cpp', 'tests/ui_registry_observer.hpp', - 'tests/ui_lifecycle_tests.cpp', 'nilcompiler/src/codegen.hpp', 'nilcompiler/src/native_runtime.hpp', - 'nilcompiler/src/nil_loader.hpp', 'nilcompiler/src/vm.hpp', 'nilcompiler/src/ast.hpp', - 'nilcompiler/src/lexer.hpp', 'nilcompiler/src/annotation_arguments.hpp', - 'nilcompiler/src/source_debug.hpp', 'nilcompiler/src/database_runtime.hpp', 'nilcompiler/src/memory_profile.hpp') -ALIASES = {'gtk':'libgtk-4.1.dylib','gobject':'libgobject-2.0.0.dylib', - 'glib':'libglib-2.0.0.dylib','gio':'libgio-2.0.0.dylib'} -MODE_CHECKS = {'--provider-present':19, '--provider-absent':20, '--no-display':20, - '--darwin-worker-first':27, '--darwin-mixed-provider':31} - - -def require(value, message): - if not value: - raise ValueError(message) - - -def load(name, relative): - spec = importlib.util.spec_from_file_location(name, ROOT/relative) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def provider_modules(): - return (load('runtime_gtk_provider', 'scripts/ci/macos-gtk-provider.py'), - load('runtime_gtk_file_identity', 'scripts/ci/macos-ui-probes.py')) - - -def save(path, value): - with path.open('x', encoding='utf-8') as stream: - json.dump(value, stream, indent=2, sort_keys=True); stream.write('\n') - - -def read_json(path, deadline, ui): - row = ui.record(path, deadline) - require(row['bytes'] <= 16*MiB, 'JSON evidence bound exceeded') - data = path.read_bytes() - require(len(data) == row['bytes'] and hashlib.sha256(data).hexdigest() == row['sha256'], 'JSON evidence changed') - return json.loads(data), row - - -def admit_provider(report, revision, architecture): - require(report.get('schema') == 'nil.macos.gtk-provider.v1' and report.get('status') == 'PASS' and - report.get('phase') == 'complete' and report.get('revision') == revision and - report.get('architecture') == architecture and architecture in ('arm64','x86_64'), - 'Successful exact-source native provider required') - require(report.get('qualification') is False and report.get('sdk_replaced') is False and - report.get('product_runtime_admitted') is False and report.get('problems') == [], - 'Provider scope/problems differ') - for key in ('source_unchanged','inputs_unchanged','release_sources_unchanged','prefix_unchanged','cleanup_verified'): - require(report.get(key) is True, 'Provider lacks '+key) - elapsed = report.get('elapsed_seconds') - require(type(elapsed) in (int,float) and math.isfinite(elapsed) and 0 <= elapsed <= 1800, - 'Provider whole bound differs') - phases = report.get('phases') - require(isinstance(phases,list) and 0 < len(phases) <= 450 and - len({p['name'] for p in phases}) == len(phases), 'Provider phase inventory differs') - require(all(p.get('status') == 'PASS' and type(p.get('exit_code')) is int and p.get('exit_code') == 0 and - p.get('cleanup_verified') is True and not p.get('error') and not p.get('timed_out') for p in phases), - 'Provider contains incomplete/failed owned phase') - return report - - -def provider_aliases(report): - origins = report['smoke']['origins'] - result = {ALIASES[key]:Path(origins[key]['canonical']) for key in ('gtk','gobject','glib')} - declared = report['prerequisites']['operations']['gio_path'] - result[ALIASES['gio']] = Path(report['inputs_before'][declared]['canonical_path']) - require(all(path.is_absolute() and '..' not in path.parts for path in result.values()) and - len(set(result.values())) == 4, 'Provider canonical alias inventory differs') - return result - - -def validate_provider(path, revision, architecture, deadline): - """Read-only same-job provider validation; reusable by directed-input probes. - - Rehash the provider's declared files and installed prefix. This intentionally - admits only the original runner/source/profile; it is not SDK qualification. - """ - provider, ui = provider_modules() - path = Path(path) - require(path.is_absolute() and not path.is_symlink() and path.resolve(strict=True) == path, - 'Canonical regular provider report path required') - report, anchor = read_json(path, deadline, ui) - admit_provider(report, revision, architecture) - work, prefix = Path(report['work_dir']), Path(report['prefix']) - require(work.is_absolute() and work.resolve(strict=True) == work and prefix == work/'prefix' and - prefix.resolve(strict=True) == prefix and ROOT not in work.parents and work not in ROOT.parents and work != ROOT, - 'Provider work/prefix identity differs') - info = work.stat() - require(stat.S_IMODE(info.st_mode) == 0o700 and info.st_uid == os.getuid(), 'Private provider work ownership differs') - inputs = report['inputs_before'] - require(isinstance(inputs,dict) and 0 < len(inputs) <= 5000, 'Provider input inventory bound differs') - after, _ = read_json(path.parent/'inputs-after.json', deadline, ui) - require(inputs == after, 'Provider original input seal differs') - for name in provider.INPUTS: - expected = inputs.get(str(ROOT/name)) - require(expected is not None and ui.record(ROOT/name, deadline) == expected, - 'Provider source helper differs from current checkout: '+name) - for name, expected in inputs.items(): - require(ui.record(Path(name), deadline) == expected, 'Declared provider input changed: '+name) - before, _ = read_json(path.parent/'prefix-before.json', deadline, ui) - after, _ = read_json(path.parent/'prefix-after.json', deadline, ui) - require(before == after and provider.tree_seal(prefix, deadline, ui.record) == before, - 'Installed private provider changed') - phases = {p['name']:p for p in report['phases']} - for name, args, expected in ( - ('revision-before',['rev-parse','HEAD'],revision+'\n'), ('revision-after',['rev-parse','HEAD'],revision+'\n'), - ('source-before',['status','--porcelain','--untracked-files=no'],''), - ('source-after',['status','--porcelain','--untracked-files=no'],'')): - require(phases[name]['argv'] == ['/usr/bin/git','-C',str(ROOT),*args], 'Provider checkout command differs') - require((path.parent/'logs'/(name+'.stdout')).read_text() == expected, 'Provider checkout observation differs') - raw = path.parent/'logs/gtk-smoke.stdout' - require(ui.record(raw,deadline)['sha256'] == phases['gtk-smoke']['stdout_record']['sha256'], 'Provider raw smoke changed') - observed = json.loads(raw.read_bytes()) - require(observed == report['smoke'], 'Provider smoke report differs from actual output') - provider.smoke_result(observed) - closure, _ = read_json(path.parent/'loader-closure.json', deadline, ui) - require(isinstance(closure,dict) and 0 < len(closure) <= 256, 'Provider loader closure bound differs') - for name, row in closure.items(): - require(row['file'] == inputs[name] and ui.record(Path(name),deadline) == row['file'], - 'Provider loader closure input changed') - with Path(name).open('rb') as stream: - header=provider.macho_header(stream.read(32),architecture) - require(header==row['header'],'Current provider Mach-O architecture/header differs') - for item in row['loads']: - require(provider.system_library(item['name']) if item.get('system_cache_or_framework_boundary') else - item['target'] in closure, 'Provider loader closure is incomplete') - aliases = provider_aliases(report) - for name, target in aliases.items(): - require(str(target) in closure and ui.record(target,deadline)['sha256'] == closure[str(target)]['file']['sha256'], - 'Curated runtime absent from sealed provider closure: '+name) - require(prefix in aliases[ALIASES['gtk']].parents, 'GTK runtime escaped private prefix') - require(ui.record(path,deadline) == anchor, 'Provider report changed during validation') - return report - - -def curate(directory, aliases): - require(not directory.exists() and not directory.is_symlink(), 'Fresh curated directory required') - require(set(aliases) == set(ALIASES.values()), 'Curated provider role inventory differs') - directory.mkdir(mode=0o700) - for name, target in aliases.items(): - require(target.is_absolute() and target.resolve(strict=True) == target and target.is_file(), - 'Curated provider target must be canonical regular file') - (directory/name).symlink_to(target) - - -def curated_seal(directory, deadline, ui): - require(directory.is_dir() and not directory.is_symlink(), 'Curated provider directory changed') - info=directory.stat() - require(stat.S_IMODE(info.st_mode)==0o700 and info.st_uid==os.getuid(), 'Curated directory ownership/mode changed') - result = {} - for path in sorted(directory.iterdir()): - require(path.name in ALIASES.values(), 'Unexpected curated provider file') - mode = path.lstat().st_mode - require(stat.S_ISLNK(mode) or stat.S_ISREG(mode), 'Curated provider contains special file') - result[path.name] = {'link':os.readlink(path) if stat.S_ISLNK(mode) else None, - 'file':ui.record(path,deadline)} - return result - - -def runtime_environment(work, provider_report, inherited=None): - provider, _ = provider_modules() - env = provider.environment(work,inherited) - prefix = Path(provider_report['prefix']) - env.update(GSK_RENDERER='cairo',GDK_BACKEND='macos',GSETTINGS_BACKEND='memory', - GSETTINGS_SCHEMA_DIR=str(prefix/'share/glib-2.0/schemas'),XDG_DATA_DIRS=str(prefix/'share'), - XDG_CACHE_HOME=str(work/'cache'),XDG_CONFIG_HOME=str(work/'config'),XDG_DATA_HOME=str(work/'data')) - return env - - -def runtime_output(raw, mode): - require(len(raw) <= 4096, 'Runtime summary exceeds bound') - match = re.fullmatch(rb'UI runtime: ([0-9]+) checks passed \((--[a-z-]+)\)\n',raw) - require(match is not None and match[2].decode() == mode, 'Runtime summary/mode differs') - count = int(match[1]) - require(4000 <= count <= 20000 if mode == '--display' else - mode in MODE_CHECKS and count == MODE_CHECKS[mode], - 'Runtime assertion inventory is incomplete/unbounded') - return {'mode':mode,'checks':count} - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--provider-report',required=True,type=Path) - parser.add_argument('--output',required=True,type=Path) - parser.add_argument('--work-dir',required=True,type=Path) - parser.add_argument('--revision',required=True) - parser.add_argument('--architecture',required=True,choices=('arm64','x86_64')) - args = parser.parse_args() - require(sys.platform == 'darwin' and platform.machine() == args.architecture and - re.fullmatch('[0-9a-f]{40}',args.revision), 'Exact-source matching native macOS required') - provider,ui = provider_modules() - output,work = ui.paths(args.output,args.work_dir) - output.mkdir(parents=True,mode=0o700);work.mkdir(mode=0o700) - logs=output/'logs';logs.mkdir() - for name in ('tmp','tool-bin'): (work/name).mkdir() - start=time.monotonic();final=start+TOTAL_SECONDS;deadline=final-RESERVE_SECONDS - report={'schema':'nil.macos.gtk-runtime.v1','status':'FAIL','revision':args.revision,'architecture':args.architecture, - 'scope':'Standalone ui_runtime.cpp execution plus ui_lifecycle_tests.cpp syntax only; excludes VM lifecycle execution, language, external-input, debugger and installed SDK acceptance', - 'qualification':False,'sdk_replaced':False,'language_acceptance':False,'work_dir':str(work), - 'work_retained':True,'phase':'initialize','phases':[],'cases':[],'problems':[], - 'limits':{'whole_seconds':TOTAL_SECONDS,'reserve_seconds':RESERVE_SECONDS,'phase_output_bytes':MiB}} - support=ownership=None;inputs={};provider_anchor=None;curated_before={};baseline=None - env=provider.environment(work) - def run(name,argv,limit=10,*,variables=None,strict=True,final_check=False): - if not final_check:report['phase']=name - row=support.run_process(ownership,[str(x) for x in argv],work,variables or env,logs,name, - provider.remaining(final-5 if final_check else deadline,limit)) - report['phases'].append(row);save(logs/(name+'.json'),row) - require(row.get('cleanup_verified') is True and not row.get('error') and not row.get('timed_out'), - name+': owned process/cleanup failure') - if strict:require(row.get('exit_code')==0,name+': nonzero exit; raw logs retained') - return row,(logs/row['stdout']).read_bytes() - try: - for name in INPUTS:inputs[str(ROOT/name)]=ui.record(ROOT/name,deadline) - support=load('runtime_gtk_owner','tests/tools/ordinary_io_parity_contract.py');ownership=support.load_ownership(ROOT) - require(support.MAX_OUTPUT==MiB,'Capture bound changed') - _,raw=run('revision-before',['/usr/bin/git','-C',ROOT,'rev-parse','HEAD']) - require(raw.decode().strip()==args.revision,'Runtime checkout revision differs') - _,raw=run('source-before',['/usr/bin/git','-C',ROOT,'status','--porcelain','--untracked-files=no']) - require(not raw,'Clean source required') - baseline=validate_provider(args.provider_report,args.revision,args.architecture,deadline) - provider_anchor=ui.record(args.provider_report,deadline);report['provider_report']=provider_anchor - report['prefix']=baseline['prefix'];report['provider_validated_before']=True - aliases=provider_aliases(baseline);report['aliases']={name:str(path) for name,path in aliases.items()} - curated=work/'provider space λ';curate(curated,aliases) - incomplete=work/'incomplete';curate(incomplete,aliases);(incomplete/ALIASES['gtk']).unlink() - mixed=work/'mixed';curate(mixed,aliases);(mixed/ALIASES['glib']).unlink() - original=aliases[ALIASES['glib']];expected=ui.record(original,deadline) - copied=0;digest=hashlib.sha256() - with original.open('rb') as source,(mixed/ALIASES['glib']).open('xb') as target: - while block:=source.read(MiB): - provider.remaining(deadline,1);copied+=len(block) - require(copied<=expected['bytes'],'GLib grew while copying private negative fixture') - digest.update(block);target.write(block) - require(copied==expected['bytes'] and digest.hexdigest()==expected['sha256'] and ui.record(original,deadline)==expected, - 'GLib changed before mixed-copy fixture') - (mixed/ALIASES['glib']).chmod(0o600) - for path in (curated,incomplete,mixed):curated_before[str(path)]=curated_seal(path,deadline,ui) - empty=work/'empty';empty.mkdir(mode=0o700);curated_before[str(empty)]=curated_seal(empty,deadline,ui) - selected=work/'selected-file';selected.write_text('not a provider directory\n');inputs[str(selected)]=ui.record(selected,deadline) - env=runtime_environment(work,baseline) - compiler=Path(baseline['toolchain']['compiler']);sdk=Path(baseline['toolchain']['sdk']) - for path in (compiler,sdk/'SDKSettings.json'): - require(ui.record(path,deadline)==baseline['inputs_before'][str(path)],'Selected compiler/SDK differs from provider') - executable=work/'runtime space λ' - run('compile-runtime',[compiler,'-std=c++17','-O2','-Wall','-Wextra','-Werror','-pthread','-isysroot',sdk, - '-mmacosx-version-min=15.0','-iquote',ROOT/'nilcompiler/src','-iquote',ROOT/'tests', - ROOT/'nilcompiler/src/ui_runtime.cpp',ROOT/'tests/ui_runtime_tests.cpp','-o',executable],60) - inputs[str(executable)]=ui.record(executable,deadline);report['binary']=inputs[str(executable)] - # Match this CMake target's C++17 warning profile; this checks the real - # newly enabled platform body without linking or executing the VM. - run('lifecycle-syntax',[compiler,'-std=c++17','-pthread','-isysroot',sdk, - '-mmacosx-version-min=15.0','-iquote',ROOT/'nilcompiler/src','-iquote',ROOT/'tests', - '-fsyntax-only',ROOT/'tests/ui_lifecycle_tests.cpp'],30) - report['lifecycle_syntax']={'status':'PASS','executed':False,'linked':False, - 'source':inputs[str(ROOT/'tests/ui_lifecycle_tests.cpp')]} - cases=[('provider-present','--provider-present',str(curated),10), - ('provider-unset','--provider-absent',None,10),('provider-empty-setting','--provider-absent','',10), - ('provider-relative','--provider-absent','provider space λ',10), - ('provider-missing','--provider-absent',str(work/'does-not-exist'),10), - ('provider-file','--provider-absent',str(selected),10), - ('provider-empty-directory','--provider-absent',str(empty),10), - ('provider-incomplete','--provider-absent',str(incomplete),10), - ('provider-mixed','--darwin-mixed-provider',str(mixed),15), - ('invalid-backend','--no-display',str(curated),15), - ('worker-first','--darwin-worker-first',str(curated),20), - ('display','--display',str(curated),45)] - for name,mode,selection,limit in cases: - variables=dict(env) - if selection is not None:variables['NIL_UI_GTK_DIRECTORY']=selection - if mode=='--darwin-mixed-provider':variables['NIL_UI_GTK_TEST_PRELOAD_GTK']=str(aliases[ALIASES['gtk']]) - case={'name':name,'mode':mode,'provider_selection':selection,'status':'FAIL'};report['cases'].append(case) - try: - row,raw=run(name,[executable,mode],limit,variables=variables,strict=False) - require(row['exit_code']==0,name+': runtime rejection/acceptance contract failed') - case.update(runtime_output(raw,mode),status='PASS') - except Exception as error: - case['error']=str(error);report['problems'].append(name+': '+str(error)) - if time.monotonic()>=deadline or report['phases'][-1].get('cleanup_verified') is not True:break - require(len(report['cases'])==len(cases) and all(x['status']=='PASS' for x in report['cases']), - 'Standalone runtime case inventory incomplete/failed') - report['status']='PASS';report['phase']='complete' - except Exception as error:report['problems'].append(type(error).__name__+': '+str(error)) - finally: - checks={};report['after_checks']=checks - def final_check(name,action): - try:action();checks[name]={'status':'PASS'} - except Exception as error: - checks[name]={'status':'FAIL','error':str(error)};report['problems'].append(name+': '+str(error)) - def provider_after(): - require(provider_anchor is not None,'Initial provider validation did not complete') - require(ui.record(args.provider_report,final-5)==provider_anchor,'Provider report changed') - require(validate_provider(args.provider_report,args.revision,args.architecture,final-5)==baseline,'Provider evidence changed') - def inputs_after(): - observed={name:ui.record(Path(name),final-5) for name in inputs} - save(output/'inputs-after.json',observed);require(observed==inputs,'Runtime source/binary inputs changed') - def aliases_after(): - observed={name:curated_seal(Path(name),final-5,ui) for name in curated_before} - save(output/'curated-after.json',observed);require(observed==curated_before,'Curated namespace changed') - require(not (work/'does-not-exist').exists() and not (work/'does-not-exist').is_symlink(),'Missing provider fixture changed') - def source_after(): - _,raw=run('revision-after',['/usr/bin/git','-C',ROOT,'rev-parse','HEAD'],5,final_check=True) - require(raw.decode().strip()==args.revision,'Source revision changed') - _,raw=run('source-after',['/usr/bin/git','-C',ROOT,'status','--porcelain','--untracked-files=no'],5,final_check=True) - require(not raw,'Tracked source changed') - for name,action in (('provider',provider_after),('inputs',inputs_after),('curated',aliases_after),('source',source_after)): - final_check(name,action) - report['inputs_before']=inputs;save(output/'curated-before.json',curated_before) - report['cleanup_verified']=bool(report['phases']) and all(x.get('cleanup_verified') is True for x in report['phases']) - report['elapsed_seconds']=time.monotonic()-start - if report['problems'] or not report['cleanup_verified'] or report['elapsed_seconds']>TOTAL_SECONDS:report['status']='FAIL' - save(output/'report.json',report) - print(json.dumps({k:report[k] for k in ('status','phase','problems','cleanup_verified','elapsed_seconds')})) - return 0 if report['status']=='PASS' else 1 - -if __name__=='__main__': - raise SystemExit(main()) diff --git a/scripts/ci/test_macos_gtk_directed_probes.py b/scripts/ci/test_macos_gtk_directed_probes.py deleted file mode 100644 index 6f6c0ff6..00000000 --- a/scripts/ci/test_macos_gtk_directed_probes.py +++ /dev/null @@ -1,301 +0,0 @@ -#!/usr/bin/env python3 -"""Pure identity/oracle controls; these do not claim native GTK event delivery.""" -import copy -import importlib.util -import io -import json -import os -from pathlib import Path -import tempfile -import time -import unittest - -SPEC = importlib.util.spec_from_file_location('gtk_directed', Path(__file__).with_name('macos-gtk-directed-probes.py')) -gate = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(gate) - - -class Controls(unittest.TestCase): - def setUp(self): - temporary = tempfile.TemporaryDirectory(); self.addCleanup(temporary.cleanup) - self.base = Path(temporary.name).resolve(); self.root = self.base/'repo'; self.root.mkdir() - self.aliases = {name: self.base/name for name in gate.ALIASES.values()} - - def ready(self): - return dict(pid=123, window_number=17, active=True, key_window=True, gtk_entry_focused=True, main_thread=True, - base_seconds=12345, gtk_header='4.18.6', gtk_runtime='4.18.6', - app_running=False, activation_policy=1, - origins={key:str(self.aliases[name]) for key,name in gate.ALIASES.items()}) - - def typed(self): - return dict(text='Matrix', checked=True, changed=6, clicked=1, toggled=1, events=20) - - def final(self): - return dict(ready=True, typed=True, native_close=True, cleanup_verified=True, success=True, - invalid=False, expired=False, exception=False, changed=6, clicked=1, toggled=1, - close_requests=1, gdk_events=gate.expected_events(12345), changed_at=[1,3,5,7,9,11], - toggled_at=15, clicked_at=20) - - def focus(self): - # A provider without AccessKit may not expose a focused AX text element. - return dict(legacy_window_error=0, legacy_window_boolean=True, legacy_window_value=False, - app_window_error=0, app_window_element=True, app_window_pid_matches=True, app_window_matches=True, - field_error=-25212, field_element=False, field_pid_matches=False, field_role_error=-1, - field_text_role=False, field_role_category='unavailable', field_window_error=-1, - field_window_element=False, field_window_pid_matches=False, field_window_matches=False) - - def window(self): - # One owned, correctly titled window; AccessKit is absent either way. - return dict(app_role_error=0, app_role_application=True, attribute_names_error=0, attribute_names_count=12, - windows_attribute_present=True, windows_error=0, windows_array=True, windows_count=1, - owned_candidates=1, window_role_candidates=1, title_candidates=1, first_role_category='window', - focused_window_error=0, focused_window_element=True, focused_window_pid_matches=True, - focused_window_title_matches=True) - - def driver(self, phase): - return dict(identity_verified=True, post_event_access=True, ax_trusted=True, own_window_selected=True, - focus_verified=True, timestamp_readback=phase=='keys', events_posted=20 if phase=='keys' else 0, - close_action=phase=='close', success=True, focus_observation=self.focus(), - window_observation=self.window(), base_seconds=12345) - - def test_private_fresh_disjoint_paths(self): - self.assertEqual(gate.paths(self.root/'build/evidence',self.base/'work',self.root), - (self.root/'build/evidence',self.base/'work')) - for output, work in ((self.root,self.base/'work'),(self.base/'output',self.root/'work'), - (self.root/'evidence',self.base/'work'),(self.base/'out',self.base/'out/work')): - with self.subTest(output=output),self.assertRaises(ValueError):gate.paths(output,work,self.root) - - def test_symlink_output_or_work_rejected(self): - link=self.base/'link';link.symlink_to(self.root,target_is_directory=True) - with self.assertRaises(ValueError):gate.paths(self.base/'out',link,self.root) - with self.assertRaises(ValueError):gate.paths(link,self.base/'work',self.root) - - def test_regular_input_seal_and_deadline(self): - path=self.base/'file';path.write_bytes(b'private') - row=gate.record(path,time.monotonic()+1) - self.assertEqual(row['bytes'],7);self.assertEqual(row['inode'],path.stat().st_ino) - self.assertEqual(row,gate.record(path,time.monotonic()+1)) - with self.assertRaises(ValueError):gate.record(path,time.monotonic()-1) - - @unittest.skipUnless(hasattr(os,'mkfifo'),'POSIX FIFO control') - def test_special_input_cannot_block_sealing(self): - path=self.base/'fifo';os.mkfifo(path) - with self.assertRaises(ValueError):gate.record(path,time.monotonic()+1) - - def test_native_scope_phase_duplicate_and_bounds(self): - raw=b'{"schema":1,"phase":"ready","qualification":false}' - self.assertEqual(gate.decode(raw,'ready')['phase'],'ready') - for value in (raw.replace(b'false',b'true'),raw.replace(b'1',b'true'),raw.replace(b'ready',b'keys'), - b'{"schema":1,"schema":1,"phase":"ready","qualification":false}',b'x'*8193): - with self.subTest(raw=value[:100]),self.assertRaises(ValueError):gate.decode(value,'ready') - - def test_ready_requires_target_main_thread_real_gtk_focus(self): - gate.ready_frame(self.ready(),123,self.aliases) - for key,value in (('pid',124),('pid',True),('window_number',0),('main_thread',False), - ('active',False),('key_window',False),('gtk_entry_focused',False)): - row=self.ready();row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.ready_frame(row,123,self.aliases) - - def test_application_loop_observation_is_bounded_not_required(self): - for value in (True, False): - row=self.ready();row['app_running']=value;gate.ready_frame(row,123,self.aliases) - for key,value in (('app_running',1),('app_running',None),('activation_policy',True), - ('activation_policy',3),('activation_policy',-1)): - row=self.ready();row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.ready_frame(row,123,self.aliases) - - def test_ready_requires_exact_provider_versions_and_origins(self): - for key in ('gtk','gobject','glib','gio'): - row=self.ready();row['origins'][key]+='-different' - with self.subTest(key=key),self.assertRaises(ValueError):gate.ready_frame(row,123,self.aliases) - for key in ('gtk_header','gtk_runtime'): - row=self.ready();row[key]='4.18.5' - with self.subTest(key=key),self.assertRaises(ValueError):gate.ready_frame(row,123,self.aliases) - - def test_timestamp_origin_rejects_bool_zero_negative_and_overflow(self): - for value in (True,0,-1,2**32+1,float('inf')): - row=self.ready();row['base_seconds']=value - with self.subTest(value=value),self.assertRaises(ValueError):gate.ready_frame(row,123,self.aliases) - with self.assertRaises(ValueError):gate.expected_events(value) - - def test_real_widget_callbacks_and_final_release_required(self): - gate.typed_frame(self.typed()) - for key,value in (('text','matrix'),('text','Matrix '),('checked',False),('changed',5),('changed',True), - ('toggled',0),('clicked',0),('events',19)): - row=self.typed();row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.typed_frame(row) - - def test_exact_twenty_event_sequence(self): - gate.final_frame(self.final(),12345) - events=gate.expected_events(12345) - self.assertEqual([e['modifiers'] for e in events],[1,1]+[0]*18) - self.assertEqual([e['keyval'] for e in events[:4]],[77,77,97,97]) - self.assertEqual([e['keycode'] for e in events[12:]],[48,48,49,49,48,48,49,49]) - # GDK publicly narrows milliseconds to guint32; preserve that exact conversion. - self.assertEqual(gate.expected_events(2**32)[19]['time_ms'],19000) - - def test_each_event_identity_field_is_enforced(self): - mutations={'index':7,'keyval':109,'keycode':45,'modifiers':0,'time_ms':12345001, - 'release':True,'event_type':5,'own_surface':False,'matches':False} - for key,value in mutations.items(): - row=self.final();row['gdk_events'][0][key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.final_frame(row,12345) - - def test_event_type_bool_duplicates_extras_reorder_and_truncation_fail(self): - originals=[] - row=self.final();row['gdk_events'][0]['index']=False;originals.append(row) - row=self.final();row['gdk_events'][0]['private_text']='hidden';originals.append(row) - row=self.final();row['gdk_events'][1]=copy.deepcopy(row['gdk_events'][0]);originals.append(row) - row=self.final();row['gdk_events']=list(reversed(row['gdk_events']));originals.append(row) - row=self.final();row['gdk_events'].pop();originals.append(row) - for row in originals: - with self.assertRaises(ValueError):gate.final_frame(row,12345) - - def test_widget_callbacks_bound_to_matching_key_events(self): - for key,value in (('changed_at',[2,4,6,8,10,12]),('changed_at',[True,3,5,7,9,11]), - ('toggled_at',14),('toggled_at',17),('clicked_at',18),('clicked_at',True)): - row=self.final();row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.final_frame(row,12345) - for toggle,click in ((15,19),(16,20)): - row=self.final();row.update(toggled_at=toggle,clicked_at=click);gate.final_frame(row,12345) - - def test_normal_native_close_and_cleanup_are_required_separately(self): - for key in ('ready','typed','native_close','cleanup_verified','success'): - row=self.final();row[key]=False - with self.subTest(key=key),self.assertRaises(ValueError):gate.final_frame(row,12345) - for key in ('invalid','expired','exception'): - row=self.final();row[key]=True - with self.subTest(key=key),self.assertRaises(ValueError):gate.final_frame(row,12345) - for value in (0,2,True): - row=self.final();row['close_requests']=value - with self.assertRaises(ValueError):gate.final_frame(row,12345) - - def test_missing_widget_accessibility_is_observed_not_claimed(self): - self.assertTrue(gate.focus_proof(self.focus())) - value=self.focus();value['field_role_category']='other';self.assertTrue(gate.focus_proof(value)) - value=self.focus();value['legacy_window_error']=-25205;value['legacy_window_boolean']=False - self.assertTrue(gate.focus_proof(value)) - - def test_actual_app_focused_window_identity_cannot_be_bypassed(self): - for key in ('app_window_element','app_window_pid_matches','app_window_matches'): - row=self.focus();row[key]=False - with self.subTest(key=key):self.assertFalse(gate.focus_proof(row)) - row=self.focus();row['app_window_error']=-25205;self.assertFalse(gate.focus_proof(row)) - self.assertFalse(gate.focus_proof({})) - - def test_focus_observations_bounded_without_unrelated_text(self): - for key,value in (('field_role_error',True),('field_error',-99999),('field_text_role',True), - ('external_title','not retained')): - row=self.focus();row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.focus_proof(row) - - def test_directed_driver_requires_permissions_identity_and_real_action(self): - for phase in ('keys','close'): - self.assertTrue(gate.driver_frame(self.driver(phase),phase,0,12345)) - for key in ('identity_verified','post_event_access','ax_trusted','own_window_selected','focus_verified'): - row=self.driver(phase);row[key]=False;row['success']=False - if key=='focus_verified':row['focus_observation']['app_window_matches']=False - if key=='own_window_selected': - row['window_observation']['title_candidates']=0 - row['focus_verified']=False;row['focus_observation']={} - self.assertFalse(gate.driver_frame(row,phase,2,12345)) - with self.assertRaises(ValueError):gate.driver_frame(row,phase,0,12345) - - def test_absent_window_selection_is_diagnosed_not_claimed(self): - self.assertTrue(gate.window_proof(self.window())) - self.assertFalse(gate.window_proof({})) - # Each distinct cause the native diagnostic must now separate. - hierarchy=dict(self.window(),app_role_error=-25204,app_role_application=False, - attribute_names_error=-25204,attribute_names_count=0,windows_attribute_present=False, - windows_error=-25204,windows_array=False,windows_count=0,owned_candidates=0, - window_role_candidates=0,title_candidates=0,first_role_category='unavailable', - focused_window_error=-25204,focused_window_element=False, - focused_window_pid_matches=False,focused_window_title_matches=False) - unsupported=dict(hierarchy,app_role_error=0,app_role_application=True,attribute_names_error=0, - attribute_names_count=9) - empty=dict(unsupported,windows_attribute_present=True,windows_error=0,windows_array=True) - untitled=dict(empty,windows_count=1,owned_candidates=1,window_role_candidates=1) - other_role=dict(empty,windows_count=1,owned_candidates=1,first_role_category='other') - for row in (hierarchy,unsupported,empty,untitled,other_role): - with self.subTest(row=row['first_role_category']):self.assertFalse(gate.window_proof(row)) - # A focused window alone is observed, never selection. - self.assertFalse(gate.window_proof(dict(empty,focused_window_error=0,focused_window_element=True, - focused_window_pid_matches=True,focused_window_title_matches=True))) - - def test_ambiguous_or_unowned_windows_are_never_selected(self): - for row in (dict(self.window(),windows_count=2,owned_candidates=2,window_role_candidates=2,title_candidates=2), - dict(self.window(),owned_candidates=0,window_role_candidates=0,title_candidates=0, - first_role_category='unavailable')): - self.assertFalse(gate.window_proof(row)) - - def test_window_observations_bounded_and_internally_consistent(self): - for key,value in (('windows_count',True),('windows_error',-99999),('attribute_names_count',65), - ('first_role_category','toplevel'),('observed_title','Ny GTK directed'), - ('owned_candidates',-1)): - row=self.window();row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.window_proof(row) - for row in (dict(self.window(),title_candidates=2), - dict(self.window(),windows_count=0,owned_candidates=0,window_role_candidates=0, - title_candidates=0,first_role_category='window'), - dict(self.window(),windows_error=-25205), - dict(self.window(),windows_array=False,windows_error=0,windows_count=1, - owned_candidates=0,window_role_candidates=0,title_candidates=0, - first_role_category='unavailable')): - with self.assertRaises(ValueError):gate.window_proof(row) - - def test_driver_summary_cannot_override_actual_window_selection(self): - row=self.driver('keys');row['window_observation']['title_candidates']=0 - with self.assertRaises(ValueError):gate.driver_frame(row,'keys',0,12345) - row=self.driver('keys');del row['window_observation'] - with self.assertRaises(ValueError):gate.driver_frame(row,'keys',0,12345) - - def test_timestamp_readback_and_final_driver_counts(self): - for phase,key in (('keys','timestamp_readback'),('close','close_action')): - row=self.driver(phase);row[key]=False;row['success']=False - self.assertFalse(gate.driver_frame(row,phase,2,12345)) - for key,value in (('events_posted',True),('events_posted',21),('base_seconds',12346)): - row=self.driver('keys');row[key]=value - with self.subTest(key=key),self.assertRaises(ValueError):gate.driver_frame(row,'keys',0,12345) - - def test_driver_summary_cannot_override_actual_focus(self): - row=self.driver('keys');row['focus_observation']['app_window_matches']=False - with self.assertRaises(ValueError):gate.driver_frame(row,'keys',0,12345) - - def test_distinct_driver_and_target_identity_are_explicit(self): - driver=self.base/'driver';target=self.base/'target';driver.write_bytes(b'driver');target.write_bytes(b'target') - ds=gate.record(driver,time.monotonic()+1);ts=gate.record(target,time.monotonic()+1) - identity=dict(pid=123,created=(2**63+3)<<32|0xffffffff) - argv=gate.driver_arguments(driver,target,'keys',identity,456,ds,ts,'a'*32,12345) - self.assertEqual(argv,list(map(str,[driver,'keys',123,2**63+3,0xffffffff,456,ts['device'],ts['inode'],target,'a'*32,12345]))) - with self.assertRaises(ValueError):gate.driver_arguments(driver,target,'keys',identity,456,ts,ds,'a'*32,12345) - - def test_invalid_pid_lifetime_or_timestamp_rejected_before_launch(self): - binary=self.base/'probe';binary.write_bytes(b'binary');seal=gate.record(binary,time.monotonic()+1) - for identity in (dict(pid=True,created=1<<32),dict(pid=0,created=1<<32),dict(pid=123,created=1), - dict(pid=123,created=1<<96),dict(pid=123,created=-1)): - with self.subTest(identity=identity),self.assertRaises(ValueError): - gate.driver_arguments(binary,binary,'keys',identity,456,seal,seal,'a'*32,12345) - for base in (0,True,2**32+1): - with self.assertRaises(ValueError):gate.driver_arguments(binary,binary,'keys',dict(pid=123,created=1<<32),456,seal,seal,'a'*32,base) - - def test_split_frames_retain_raw_and_reject_trailing_output(self): - raw=b'{"schema":1,"phase":"ready","qualification":false}\n' - class Reader: - def __init__(self,parts):self.parts=iter(parts) - def read(self,_timeout):return next(self.parts) - sink=io.BytesIO();frames=gate.Frames(Reader((raw[:10],raw[10:],b'trailing\n',b'')),sink) - self.assertEqual(gate.decode(raw,'ready'),frames.next('ready',time.monotonic()+1)) - with self.assertRaises(ValueError):frames.drain(time.monotonic()+1,reject_new=True) - self.assertEqual(sink.getvalue(),raw+b'trailing\n');self.assertTrue(frames.eof) - - def test_eof_wrong_phase_and_oversize_fail_without_second_eof_wait(self): - class Reader: - def __init__(self,raw):self.raw=raw - def read(self,_timeout):return self.raw - for raw in (b'',b'x'*16385,b'{"schema":1,"phase":"typed","qualification":false}\n'): - frames=gate.Frames(Reader(raw),io.BytesIO()) - with self.assertRaises(ValueError):frames.next('ready',time.monotonic()+1) - if not raw:frames.drain(time.monotonic()-1) - - -if __name__=='__main__':unittest.main() diff --git a/scripts/ci/test_macos_gtk_provider.py b/scripts/ci/test_macos_gtk_provider.py deleted file mode 100644 index 687bd108..00000000 --- a/scripts/ci/test_macos_gtk_provider.py +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env python3 -"""Pure controls for private GTK inputs, namespace, and evidence admission.""" -import copy -import importlib.util -import io -import json -import os -from pathlib import Path -import stat -import struct -import tarfile -import tempfile -import time -import unittest -import zipfile - -SPEC = importlib.util.spec_from_file_location('gtk_provider', Path(__file__).with_name('macos-gtk-provider.py')) -M = importlib.util.module_from_spec(SPEC); SPEC.loader.exec_module(M) -UI = M.load('gtk_test_ui', 'scripts/ci/macos-ui-probes.py') - - -def member(name, kind=tarfile.REGTYPE, data=b'x', link=''): - result = tarfile.TarInfo(name) - result.type = kind; result.size = len(data) if kind == tarfile.REGTYPE else 0 - result.mode = 0o755 if kind == tarfile.DIRTYPE else 0o644 - result.mtime = 1700000000; result.linkname = link - return result - - -def archive(root, members): - path = root/'fixture.tar.xz' - with tarfile.open(path, 'w:xz') as output: - for item, data in members: - output.addfile(item, io.BytesIO(data) if item.isfile() else None) - rows, inventory = M.member_manifest([item for item, _ in members], 'fixture') - rec = UI.record(path, time.monotonic()+10) - item = {'root':'fixture', 'bytes':rec['bytes'], 'sha256':rec['sha256'], 'members':inventory, 'required_files':{}} - return path, item - - -class ArchiveControls(unittest.TestCase): - def setUp(self): - self.members = [member('fixture', tarfile.DIRTYPE), member('fixture/a'), - member('fixture/alias', tarfile.SYMTYPE, link='a')] - - def test_regular_sibling_alias_is_explicit(self): - rows, observed = M.member_manifest(self.members, 'fixture') - self.assertEqual(rows[-1]['link'], 'a'); self.assertEqual(observed['expanded_bytes'], 1) - - def test_paths_refuse_traversal_and_normalization(self): - for name in ('/fixture', 'fixture/../a', 'fixture//a', './fixture/a', 'fixture\\a', 'fixture/a\n'): - with self.subTest(name=name), self.assertRaises(ValueError): M.safe_name(name) - - def test_duplicate_normalized_directory_rejected(self): - with self.assertRaises(ValueError): - M.member_manifest(self.members+[member('fixture/', tarfile.DIRTYPE)], 'fixture') - - def test_hardlinks_special_files_and_special_modes_rejected(self): - for kind in (tarfile.LNKTYPE, tarfile.FIFOTYPE, tarfile.CHRTYPE): - with self.subTest(kind=kind), self.assertRaises(ValueError): - M.member_manifest(self.members+[member('fixture/bad',kind)], 'fixture') - self.members[1].mode |= 0o4000 - with self.assertRaises(ValueError): M.member_manifest(self.members, 'fixture') - - def test_symlinks_cannot_escape_chain_or_become_parents(self): - for target in ('../a','/a','missing','alias'): - rows=copy.deepcopy(self.members); rows[-1].linkname=target - with self.subTest(target=target), self.assertRaises(ValueError): M.member_manifest(rows,'fixture') - with self.assertRaises(ValueError): - M.member_manifest(self.members+[member('fixture/alias/child')], 'fixture') - - def test_size_and_time_bounds(self): - for field, value in (('size',M.MAX_FILE+1),('mtime',float('nan')),('mtime',-1),('mtime',True)): - rows=copy.deepcopy(self.members); setattr(rows[1],field,value) - with self.subTest(field=field,value=value), self.assertRaises(ValueError): M.member_manifest(rows,'fixture') - - def test_extract_preserves_generated_freshness_and_alias(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve(); generated=member('fixture/generated.c'); generated.mtime=1700000900 - grammar=member('fixture/input.y') - members=[(self.members[0],b''),(generated,b'c'),(grammar,b'y'), - (member('fixture/alias',tarfile.SYMTYPE,link='generated.c'),b'')] - path,item=archive(root,members); dest=root/'out'; dest.mkdir() - M.extract_source(path,dest,item,time.monotonic()+10,UI.record) - self.assertGreater((dest/'fixture/generated.c').stat().st_mtime,(dest/'fixture/input.y').stat().st_mtime) - self.assertTrue((dest/'fixture/alias').is_symlink()) - self.assertEqual((dest/'fixture/alias').read_bytes(),b'c') - - def test_digest_or_member_inventory_mismatch_stops_before_write(self): - for field in ('sha256','members'): - with self.subTest(field=field), tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve(); path,item=archive(root,[(self.members[0],b''),(self.members[1],b'x')]) - if field=='sha256': item[field]='0'*64 - else: item[field]['entries']+=1 - dest=root/'out'; dest.mkdir() - with self.assertRaises(ValueError): M.extract_source(path,dest,item,time.monotonic()+10,UI.record) - self.assertEqual(list(dest.iterdir()),[]) - - def test_required_css_bytes_cannot_be_substituted(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve(); path,item=archive(root,[(self.members[0],b''),(self.members[1],b'x')]) - item['required_files']={'fixture/a':{'bytes':1,'sha256':'0'*64}} - dest=root/'out'; dest.mkdir() - with self.assertRaisesRegex(ValueError,'Required generated'): - M.extract_source(path,dest,item,time.monotonic()+10,UI.record) - - def test_wheel_rejects_symlink_before_extraction(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve(); path=root/'wheel.zip' - with zipfile.ZipFile(path,'w') as output: - item=zipfile.ZipInfo('mesonbuild/mesonmain.py'); item.external_attr=(stat.S_IFLNK|0o777)<<16 - output.writestr(item,'/elsewhere') - rec=UI.record(path,time.monotonic()+10); dest=root/'out';dest.mkdir() - with self.assertRaisesRegex(ValueError,'wheel member'): - M.extract_meson(path,dest,{'bytes':rec['bytes'],'sha256':rec['sha256']},time.monotonic()+10,UI.record) - self.assertEqual(list(dest.iterdir()),[]) - - -class ProfileControls(unittest.TestCase): - def test_locked_build_order_archives_css_and_options(self): - lock=json.loads(M.LOCK.read_text()) - self.assertEqual(tuple(x['root'] for x in lock['sources']),M.BUILD_ORDER) - for item in lock['sources']: - self.assertEqual(len(item['sha256']),64) - self.assertGreater(item['bytes'],0) - self.assertEqual(len(item['options']),len(set(x.split('=')[0] for x in item['options']))) - gtk=lock['sources'][-1] - css=[k for k in gtk['required_files'] if k.endswith('.css')] - self.assertEqual(len(css),10) - self.assertIn('gtk-4.18.6/gtk/theme/Default/Default-light.css',css) - for option in ('-Dmacos-backend=true','-Dwayland-backend=false','-Dbuild-tests=false'): - self.assertIn(option,gtk['options']) - self.assertEqual(lock['meson']['version'],'1.12.1') - - def test_environment_excludes_loader_tool_and_python_overrides(self): - dirty={x:'injected' for x in ('PATH','DYLD_LIBRARY_PATH','DYLD_INSERT_LIBRARIES','DYLD_FRAMEWORK_PATH', - 'PYTHONPATH','PYTHONHOME','CC','CXX','CFLAGS','LDFLAGS','DEVELOPER_DIR','TOOLCHAINS', - 'COMPILER_PATH','GCC_EXEC_PREFIX','CCC_OVERRIDE_OPTIONS','PKG_CONFIG_PATH','PKG_CONFIG_SYSROOT_DIR')} - env=M.environment(Path('/private/work'),dirty) - for key in dirty: - self.assertNotEqual(env.get(key),'injected') - self.assertEqual(env['PATH'],'/private/work/tool-bin:/usr/bin:/bin:/usr/sbin:/sbin') - - def test_setup_is_shared_release_private_no_fallback(self): - args=M.setup_arguments(['python','meson'],Path('/source'),Path('/build'),Path('/prefix'),Path('/native'),{'options':['-Dtests=false']}) - for expected in ('--prefix=/prefix','--libdir=lib','--buildtype=release','--default-library=shared','--wrap-mode=nofallback','--native-file=/native'): - self.assertIn(expected,args) - self.assertEqual(args[-1],'-Dtests=false') - - def test_deadline_cannot_be_extended(self): - with self.assertRaises(ValueError): M.remaining(time.monotonic()-1,600) - self.assertLessEqual(M.remaining(time.monotonic()+.1,600),.1) - - def test_private_roots_reject_checkout_and_alias_overlap(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve(); checkout=root/'checkout';checkout.mkdir(); parent=root/'work';parent.mkdir();alias=root/'alias';alias.symlink_to(parent,target_is_directory=True) - with self.assertRaises(ValueError): UI.paths(root/'output',checkout/'private',checkout) - with self.assertRaises(ValueError): UI.paths(parent/'output',alias/'output'/'nested',checkout) - - def test_prefix_seal_preserves_internal_alias_and_resources(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve(); (root/'real').write_text('bytes');(root/'alias').symlink_to('real') - rows=M.tree_seal(root,time.monotonic()+10,UI.record) - self.assertEqual(rows['alias'],{'link':'real','target':'real'}) - self.assertEqual(rows['real']['bytes'],5) - - def test_prefix_seal_refuses_external_directory_and_special_alias(self): - with tempfile.TemporaryDirectory() as tmp: - parent=Path(tmp).resolve();root=parent/'prefix';root.mkdir();(parent/'other').write_text('x') - (root/'alias').symlink_to('../other') - with self.assertRaises(ValueError): M.tree_seal(root,time.monotonic()+10,UI.record) - (root/'alias').unlink();(root/'dir').mkdir();(root/'alias').symlink_to('dir',target_is_directory=True) - with self.assertRaises(ValueError): M.tree_seal(root,time.monotonic()+10,UI.record) - (root/'alias').unlink();os.mkfifo(root/'pipe') - with self.assertRaises(ValueError): M.tree_seal(root,time.monotonic()+10,UI.record) - - def test_image_oracle_requires_roundtrip_versions_and_all_origins(self): - row={'png_header':'10650','png_runtime':'10650','png_roundtrip':'passed','jpeg_header':'80','jpeg_abi':'passed', - 'tiff_header':'20250521','tiff_runtime':'1','png_path':'/png','tiff_path':'/tiff','jpeg_path':'/jpeg'} - encode=lambda x: ''.join(k+'='+v+'\n' for k,v in x.items()).encode() - self.assertEqual(M.image_result(encode(row)),row) - for field,value in (('png_runtime','10649'),('png_roundtrip','failed'),('tiff_runtime','0')): - changed=dict(row);changed[field]=value - with self.subTest(field=field),self.assertRaises(ValueError): M.image_result(encode(changed)) - del row['jpeg_path'] - with self.assertRaises(ValueError): M.image_result(encode(row)) - - -def smoke_fixture(): - result = {'schema':'nil.macos-gtk-provider-smoke.v1','scope':'private-provider-own-process','status':'PASS', - 'language_acceptance':False,'main_thread':True,'backend':'GdkMacosDisplay','renderer':'GskCairoRenderer', - 'versions':{kind+'_'+side:value for kind,value in (('gtk','4.18.6'),('pango','1.56.4'),('pixbuf','2.42.12'),('png','1.6.50')) for side in ('header','runtime')}, - 'cleanup':{'verified':True,'own_window_hidden':True,'gtk_toplevel_count':0},'unexpected_keys':0,'close_requests':1,'elapsed_seconds':2.0, - 'widgets':{'entry_text':'n','checkbox_active':True,'entry_changed':1,'button_clicked':1,'checkbox_toggled':1}, - 'png':{'decoded':True,'width':1,'height':1,'channels':4,'rgba':[17,34,51,255]}, - 'font':{'quartz':True,'coretext':True,'width':40,'height':12}, - 'events':[],'observed_keys':[{'pressed':1,'released':1} for _ in range(3)],'dispatched_keys':[], - 'origins':{key:{'declared':'/private/'+key,'canonical':'/private/'+key,'file_backed':True} - for key in ('gtk','pango','pangocairo','pixbuf','glib','gobject','cairo','png','harfbuzz')}} - for key in ('coretext','appkit'): - result['origins'][key]={'declared':'/System/Library/Frameworks/'+key,'canonical':None,'file_backed':False} - for index in range(3): - seconds=1000.0+index - event={'stage':index,'keycode':45 if index==0 else 49,'keyval':110 if index==0 else 32,'modifiers':0, - 'queued_count':2,'timestamp_seconds':seconds,'timestamp_hex':seconds.hex(),'gdk_time_ms':int(seconds*1000),'window_number':17} - result['events'].append(event) - for released in (False,True): - result['dispatched_keys'].append({**{key:event[key] for key in ('stage','keycode','keyval','modifiers','gdk_time_ms')}, - 'release':released,'own_surface':True,'matches':True}) - return result - - -class SmokeControls(unittest.TestCase): - def test_complete_native_oracle_and_framework_boundary(self): - row=smoke_fixture();self.assertIs(M.smoke_result(row),row) - - def test_no_success_from_queue_without_dispatch_or_widget_effect(self): - for path,value in ((('observed_keys',0,'released'),0),(('widgets','entry_text'),''), - (('dispatched_keys',0,'own_surface'),False),(('dispatched_keys',1,'release'),False)): - row=smoke_fixture();target=row - for name in path[:-1]:target=target[name] - target[path[-1]]=value - with self.subTest(path=path),self.assertRaises(ValueError):M.smoke_result(row) - - def test_actual_dispatch_timestamp_key_and_order_bound(self): - for field,value in (('gdk_time_ms',3),('keycode',49),('stage',1),('keyval',32),('modifiers',1)): - row=smoke_fixture();row['dispatched_keys'][0][field]=value - with self.subTest(field=field),self.assertRaises(ValueError):M.smoke_result(row) - row=smoke_fixture();row['events'][0]['timestamp_hex']='0x1p0' - with self.assertRaises(ValueError):M.smoke_result(row) - - def test_counts_reject_boolean_alias_and_duplicates(self): - for path in (('events',0,'stage'),('cleanup','gtk_toplevel_count'),('widgets','entry_changed')): - row=smoke_fixture();target=row - for name in path[:-1]:target=target[name] - target[path[-1]]=True if target[path[-1]] else False - with self.subTest(path=path),self.assertRaises(ValueError):M.smoke_result(row) - row=smoke_fixture();row['dispatched_keys'].append(row['dispatched_keys'][-1]) - with self.assertRaises(ValueError):M.smoke_result(row) - - def test_resources_origin_and_real_cleanup_are_mandatory(self): - for path,value in ((('png','rgba'),[0,0,0,255]),(('font','coretext'),False), - (('origins','gtk','file_backed'),False),(('cleanup','own_window_hidden'),False), - (('cleanup','verified'),False),(('versions','pango_runtime'),'1.56.3')): - row=smoke_fixture();target=row - for name in path[:-1]:target=target[name] - target[path[-1]]=value - with self.subTest(path=path),self.assertRaises(ValueError):M.smoke_result(row) - - def test_harfbuzz_font_origin_is_required_and_file_backed(self): - row=smoke_fixture();del row['origins']['harfbuzz'] - with self.assertRaises(ValueError):M.smoke_result(row) - row=smoke_fixture();row['origins']['harfbuzz']['file_backed']=False - with self.assertRaises(ValueError):M.smoke_result(row) - - def test_qualified_or_out_of_bound_reports_cannot_pass(self): - for field,value in (('language_acceptance',True),('elapsed_seconds',30),('elapsed_seconds',float('nan')), - ('elapsed_seconds',True),('status','FAIL'),('renderer','GskGLRenderer')): - row=smoke_fixture();row[field]=value - with self.subTest(field=field,value=value),self.assertRaises(ValueError):M.smoke_result(row) - - -class LoaderControls(unittest.TestCase): - def test_native_loader_header_rejects_wrong_cpu_kind_and_truncation(self): - header=struct.pack('<8I',0xfeedfacf,0x100000c,0,6,12,1000,0,0) - self.assertEqual(M.macho_header(header,'arm64')['file_type'],6) - for raw,arch in ((header,'x86_64'),(header[:31],'arm64'), - (struct.pack('<8I',0xfeedfacf,0x100000c,0,1,12,1000,0,0),'arm64')): - with self.assertRaises(ValueError):M.macho_header(raw,arch) - - def test_all_relevant_load_commands_are_retained(self): - raw=b'Load command 0\n cmd LC_ID_DYLIB\n name @rpath/libgtk.dylib (offset 24)\n cmd LC_RPATH\n path @loader_path (offset 12)\n cmd LC_LOAD_WEAK_DYLIB\n name /usr/lib/libc.dylib (offset 24)\n' - rows=M.loader_commands(raw) - self.assertEqual([x['command'] for x in rows],['LC_ID_DYLIB','LC_RPATH','LC_LOAD_WEAK_DYLIB']) - self.assertEqual(rows[1]['path'],'@loader_path') - - def test_missing_loader_name_is_failure(self): - with self.assertRaises(ValueError): M.loader_commands(b'cmd LC_LOAD_DYLIB\ncmdsize 24\n') - - def test_rpath_preserves_first_existing_choice_and_requires_resolution(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp).resolve();first=root/'first';second=root/'second';first.mkdir();second.mkdir() - (first/'lib.dylib').write_text('first');(second/'lib.dylib').write_text('second') - self.assertEqual(M.resolve_load('@rpath/lib.dylib',first/'owner',['@loader_path'],root/'binary'),first/'lib.dylib') - self.assertEqual(M.resolve_load('@rpath/lib.dylib',root/'binary',[str(first),str(second)],root/'binary'),first/'lib.dylib') - with self.assertRaises(ValueError): M.resolve_load('@rpath/missing',root/'binary',[str(first)],root/'binary') - with self.assertRaises(ValueError): M.resolve_load('@unknown/lib',root/'binary',[],root/'binary') - - def test_system_boundary_is_explicit_not_arbitrary_absolute(self): - self.assertTrue(M.system_library('/usr/lib/libSystem.B.dylib')) - self.assertTrue(M.system_library('/System/Library/Frameworks/AppKit.framework/AppKit')) - self.assertFalse(M.system_library('/tmp/usr/lib/libSystem.B.dylib')) - self.assertFalse(M.system_library('/opt/homebrew/lib/libpng.dylib')) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/ci/test_macos_gtk_runtime.py b/scripts/ci/test_macos_gtk_runtime.py deleted file mode 100644 index 497b4c69..00000000 --- a/scripts/ci/test_macos_gtk_runtime.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python3 -"""Pure admission/namespace/output controls; no toolkit or desktop execution.""" -import copy -import importlib.util -import os -from pathlib import Path -import tempfile -import time -import unittest - -SPEC=importlib.util.spec_from_file_location('gtk_runtime',Path(__file__).with_name('macos-gtk-runtime.py')) -M=importlib.util.module_from_spec(SPEC);SPEC.loader.exec_module(M) -REV='a'*40 - - -def fixture(): - return {'schema':'nil.macos.gtk-provider.v1','status':'PASS','phase':'complete','revision':REV, - 'architecture':'arm64','qualification':False,'sdk_replaced':False,'product_runtime_admitted':False, - 'problems':[],'elapsed_seconds':220.0, - **{key:True for key in ('source_unchanged','inputs_unchanged','release_sources_unchanged','prefix_unchanged','cleanup_verified')}, - 'phases':[{'name':'compile','status':'PASS','exit_code':0,'cleanup_verified':True}], - 'smoke':{'origins':{key:{'canonical':'/private/'+key+'.dylib'} for key in ('gtk','gobject','glib')}}, - 'prerequisites':{'operations':{'gio_path':'/declared/gio.dylib'}}, - 'inputs_before':{'/declared/gio.dylib':{'canonical_path':'/private/gio.dylib'}}} - - -class AdmissionControls(unittest.TestCase): - def test_exact_successful_profile(self): - row=fixture();self.assertIs(M.admit_provider(row,REV,'arm64'),row) - - def test_revision_architecture_or_incomplete_phase_rejected(self): - for field,value in (('revision','b'*40),('architecture','x86_64'),('status','FAIL'),('phase','smoke-headers')): - row=fixture();row[field]=value - with self.subTest(field=field),self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - - def test_unqualified_scope_and_every_after_seal_required(self): - for field in ('qualification','sdk_replaced','product_runtime_admitted','source_unchanged','inputs_unchanged', - 'release_sources_unchanged','prefix_unchanged','cleanup_verified'): - row=fixture();row[field]=not row[field] - with self.subTest(field=field),self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - row=fixture();row['inputs_unchanged']=1 - with self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - - def test_real_failed_timedout_or_unowned_phase_rejected(self): - for field,value in (('exit_code',1),('exit_code',False),('status','FAIL'),('cleanup_verified',False),('error','timeout'),('timed_out',True)): - row=fixture();row['phases'][0][field]=value - with self.subTest(field=field),self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - - def test_duplicate_empty_and_unbounded_inventory_rejected(self): - for phases in ([],fixture()['phases']*2,fixture()['phases']*451): - row=fixture();row['phases']=phases - with self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - - def test_whole_bound_and_errors_remain_failures(self): - for value in (True,float('nan'),float('inf'),-1,1801): - row=fixture();row['elapsed_seconds']=value - with self.subTest(value=value),self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - row=fixture();row['problems']=['source changed'] - with self.assertRaises(ValueError):M.admit_provider(row,REV,'arm64') - - def test_canonical_role_names_and_test_only_gio(self): - result=M.provider_aliases(fixture()) - self.assertEqual(set(result),set(M.ALIASES.values())) - self.assertEqual(result['libgio-2.0.0.dylib'],Path('/private/gio.dylib')) - - def test_alias_inventory_cannot_use_relative_or_same_library_for_roles(self): - for value in ('relative/libgtk.dylib','/private/../gtk.dylib','/private/glib.dylib'): - row=fixture();row['smoke']['origins']['gtk']['canonical']=value - with self.subTest(value=value),self.assertRaises(ValueError):M.provider_aliases(row) - - -class NamespaceControls(unittest.TestCase): - def setUp(self): - self.temporary=tempfile.TemporaryDirectory();self.root=Path(self.temporary.name).resolve() - self.ui=M.provider_modules()[1];self.inputs=self.root/'inputs';self.inputs.mkdir() - self.aliases={name:self.inputs/name for name in M.ALIASES.values()} - for name,path in self.aliases.items():path.write_text(name) - def tearDown(self):self.temporary.cleanup() - - def test_exact_aliases_sealed_without_copy_or_target_write(self): - curated=self.root/'provider space λ';M.curate(curated,self.aliases) - observed=M.curated_seal(curated,time.monotonic()+5,self.ui) - self.assertEqual(set(observed),set(self.aliases)) - for name,path in self.aliases.items(): - self.assertEqual(observed[name]['link'],str(path));self.assertEqual(path.read_text(),name) - - def test_preexisting_or_role_substitution_rejected(self): - curated=self.root/'exists';curated.mkdir() - with self.assertRaises(ValueError):M.curate(curated,self.aliases) - bad=dict(self.aliases);del bad['libgtk-4.1.dylib'] - with self.assertRaises(ValueError):M.curate(self.root/'new',bad) - - def test_file_alias_target_must_already_be_canonical(self): - alias=self.root/'indirect';alias.symlink_to(self.aliases['libgtk-4.1.dylib']) - values=dict(self.aliases);values['libgtk-4.1.dylib']=alias - with self.assertRaises(ValueError):M.curate(self.root/'provider',values) - - def test_missing_special_and_unexpected_entries_rejected(self): - curated=self.root/'provider';M.curate(curated,self.aliases) - unknown=curated/'unexpected';unknown.write_text('x') - with self.assertRaises(ValueError):M.curated_seal(curated,time.monotonic()+5,self.ui) - unknown.unlink();target=curated/'libgtk-4.1.dylib';target.unlink();os.mkfifo(target) - with self.assertRaises(ValueError):M.curated_seal(curated,time.monotonic()+5,self.ui) - - def test_alias_retarget_or_byte_change_changes_manifest(self): - curated=self.root/'provider';M.curate(curated,self.aliases) - before=M.curated_seal(curated,time.monotonic()+5,self.ui) - self.aliases['libgtk-4.1.dylib'].write_text('changed') - self.assertNotEqual(before,M.curated_seal(curated,time.monotonic()+5,self.ui)) - path=curated/'libgtk-4.1.dylib';path.unlink();path.symlink_to(self.aliases['libglib-2.0.0.dylib']) - self.assertNotEqual(before,M.curated_seal(curated,time.monotonic()+5,self.ui)) - - def test_private_copy_is_recorded_as_distinct_identity(self): - curated=self.root/'mixed';M.curate(curated,self.aliases) - path=curated/'libglib-2.0.0.dylib';path.unlink();path.write_bytes(self.aliases[path.name].read_bytes()) - row=M.curated_seal(curated,time.monotonic()+5,self.ui)[path.name] - self.assertIsNone(row['link']);self.assertEqual(row['file']['canonical_path'],str(path)) - - def test_directory_permissions_and_symlink_root_rejected(self): - curated=self.root/'provider';M.curate(curated,self.aliases);curated.chmod(0o755) - with self.assertRaises(ValueError):M.curated_seal(curated,time.monotonic()+5,self.ui) - alias=self.root/'alias';alias.symlink_to(curated,target_is_directory=True) - with self.assertRaises(ValueError):M.curated_seal(alias,time.monotonic()+5,self.ui) - - -class RuntimeOutputControls(unittest.TestCase): - def test_exact_mode_summary_and_display_inventory(self): - self.assertEqual(M.runtime_output(b'UI runtime: 4459 checks passed (--display)\n','--display'),{'mode':'--display','checks':4459}) - self.assertEqual(M.runtime_output(b'UI runtime: 27 checks passed (--darwin-worker-first)\n','--darwin-worker-first')['checks'],27) - - def test_static_modes_require_complete_exact_assertion_counts(self): - expected={'--provider-present':19,'--provider-absent':20,'--no-display':20, - '--darwin-worker-first':27,'--darwin-mixed-provider':31} - for mode,count in expected.items(): - with self.subTest(mode=mode): - self.assertEqual(M.runtime_output(f'UI runtime: {count} checks passed ({mode})\n'.encode(),mode)['checks'],count) - for wrong in (count-1,count+1): - with self.assertRaises(ValueError): - M.runtime_output(f'UI runtime: {wrong} checks passed ({mode})\n'.encode(),mode) - with self.assertRaises(ValueError):M.runtime_output(b'UI runtime: 20 checks passed (--unknown)\n','--unknown') - - def test_wrong_mode_empty_skipped_or_partial_success_rejected(self): - for raw in (b'',b'SKIP\n',b'UI runtime: 1 checks passed (--display)\n', - b'UI runtime: 4459 checks passed (--no-display)\n',b'UI runtime: 4459 checks passed (--display)\nextra\n'): - with self.subTest(raw=raw),self.assertRaises(ValueError):M.runtime_output(raw,'--display') - - def test_clean_environment_preserves_only_explicit_provider_resources(self): - env=M.runtime_environment(Path('/private/work'),{'prefix':'/private/provider'}, - {'DYLD_LIBRARY_PATH':'bad','DYLD_INSERT_LIBRARIES':'bad','NIL_UI_GTK_DIRECTORY':'bad','NIL_UI_GTK_TEST_PRELOAD_GTK':'bad', - 'DEVELOPER_DIR':'bad','TOOLCHAINS':'bad','PYTHONPATH':'bad','GSK_RENDERER':'vulkan'}) - for key in ('DYLD_LIBRARY_PATH','DYLD_INSERT_LIBRARIES','NIL_UI_GTK_DIRECTORY','NIL_UI_GTK_TEST_PRELOAD_GTK','DEVELOPER_DIR','TOOLCHAINS','PYTHONPATH'): - self.assertNotIn(key,env) - self.assertEqual(env['GSK_RENDERER'],'cairo');self.assertEqual(env['GDK_BACKEND'],'macos') - self.assertEqual(env['GSETTINGS_SCHEMA_DIR'],'/private/provider/share/glib-2.0/schemas') - - -if __name__=='__main__':unittest.main() From d881f4ec7bda89a47335110de314e81441d114c8 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 22:03:35 -0500 Subject: [PATCH 2/2] Give macOS a language-level desktop contract nil.ui-display skipped on macOS because the contract required Linux, Xvfb and xauth. macOS has no detachable display to create, so the Darwin path uses the runner's own window server session and skips only when there is none, which is a missing session rather than a provider fault. It runs the provider fixture, the lifecycle fixture and the Matrix desktop suite, and asserts every language case passed. The lifecycle observer needed a macOS answer too. Its question is platform-neutral -- was a window really released, or merely invalidated -- so only the answerer changes: AppKit is asked for the application's windows, which counts them whether or not they are on screen, as GTK's registry does. Its retired GTK-on-macOS branch, which dlopened dylibs from NIL_UI_GTK_DIRECTORY, is gone. The observer is Objective-C++ on Darwin, so the lifecycle fixture is compiled as Objective-C++ there. The interaction suite is deliberately not part of the macOS contract and the contract says so when it passes. That suite delivers keystrokes to another process, and macOS requires accessibility trust for posting events across processes, which a hosted runner does not grant; the limit is cross-process injection, not the provider. Real input belongs in an in-process probe like the Win32 fixture's, which is the next step. The workflow gains a scope input: provider keeps the minutes-long provider check, display builds the compiler, interpreter and test runner and runs the language-level contract. Linux is unchanged at 572 registered, 0 failed and 3 environment skips. Co-Authored-By: Claude Opus 5 --- .github/workflows/macos-appkit-provider.yml | 49 +++++++++++ CMakeLists.txt | 6 ++ tests/tools/ui_display_contract.py | 42 +++++++++- tests/ui_registry_observer.hpp | 90 ++++++--------------- 4 files changed, 121 insertions(+), 66 deletions(-) diff --git a/.github/workflows/macos-appkit-provider.yml b/.github/workflows/macos-appkit-provider.yml index a66168f4..ff3ee393 100644 --- a/.github/workflows/macos-appkit-provider.yml +++ b/.github/workflows/macos-appkit-provider.yml @@ -8,6 +8,11 @@ name: macOS AppKit provider checks type: choice options: [both, x86_64, arm64] default: both + scope: + description: provider contract only, or the language-level display contract + type: choice + options: [provider, display] + default: provider permissions: contents: read @@ -21,6 +26,7 @@ concurrency: # than a full source campaign. jobs: provider: + if: ${{ inputs.scope == 'provider' }} name: macOS ${{ matrix.host.arch }} AppKit provider runs-on: ${{ matrix.host.runner }} timeout-minutes: 30 @@ -66,3 +72,46 @@ jobs: - name: Provider contract against a real session timeout-minutes: 5 run: ./build/ci/bin/nil_ui_runtime_appkit_tests --display + + display: + if: ${{ inputs.scope == 'display' }} + name: macOS ${{ matrix.host.arch }} AppKit display contract + runs-on: ${{ matrix.host.runner }} + timeout-minutes: 60 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + host: ${{ fromJSON(inputs.architecture == 'arm64' && '[{"runner":"macos-15","arch":"arm64"}]' || inputs.architecture == 'x86_64' && '[{"runner":"macos-15-intel","arch":"x86_64"}]' || '[{"runner":"macos-15-intel","arch":"x86_64"},{"runner":"macos-15","arch":"arm64"}]') }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - name: Report the desktop session + timeout-minutes: 2 + run: | + /usr/bin/python3 -c " + import ctypes, ctypes.util + core = ctypes.CDLL(ctypes.util.find_library('CoreGraphics')) + core.CGMainDisplayID.restype = ctypes.c_uint32 + print('CGMainDisplayID:', core.CGMainDisplayID()) + " + # The language-level contract needs the compiler, interpreter and test + # runner as well as the provider, so this is a whole build; LLVM stays + # off to keep it to one route rather than a full source campaign. + - name: Configure without LLVM + timeout-minutes: 8 + run: | + cmake -S . -B build/ci \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTING=ON \ + -DNIL_ENABLE_LLVM=OFF + - name: Build + timeout-minutes: 40 + run: cmake --build build/ci --parallel 3 + - name: Language-level desktop contract + timeout-minutes: 15 + run: ctest --test-dir build/ci -R 'nil.ui' --output-on-failure diff --git a/CMakeLists.txt b/CMakeLists.txt index f91660b9..9c4ca481 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -279,6 +279,12 @@ if(BUILD_TESTING) add_executable(nil_ui_lifecycle_tests tests/ui_lifecycle_tests.cpp) target_link_libraries(nil_ui_lifecycle_tests PRIVATE nilcompiler_core nilruntime ${CMAKE_DL_LIBS}) target_compile_features(nil_ui_lifecycle_tests PRIVATE cxx_std_17) + if(APPLE) + # Its registry observer asks AppKit for the application's windows, so + # the fixture is Objective-C++ on Darwin. Cocoa arrives with nilruntime. + set_source_files_properties(tests/ui_lifecycle_tests.cpp PROPERTIES + COMPILE_OPTIONS "-x;objective-c++") + endif() add_executable(ny_native_owned_tests tests/native_owned_tests.cpp) target_link_libraries(ny_native_owned_tests PRIVATE nilruntime Threads::Threads) diff --git a/tests/tools/ui_display_contract.py b/tests/tools/ui_display_contract.py index 1c90744b..f64bdc1e 100644 --- a/tests/tools/ui_display_contract.py +++ b/tests/tools/ui_display_contract.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""Exercise the optional UI provider on a private, authenticated X11 display.""" +"""Exercise the desktop UI provider: a private X11 display on Linux, the +ambient window server session on macOS.""" from __future__ import annotations import argparse @@ -244,6 +245,43 @@ def checked(command, env, timeout=180): if process.stderr: process.stderr.close() +def darwin(args): + """The AppKit contract. macOS has no detachable display to create, so the + runner's own window server session is used; without one there is nothing + to test and the contract skips rather than reporting a provider fault.""" + core = c.CDLL(ctypes.util.find_library('CoreGraphics')) + core.CGMainDisplayID.restype = c.c_uint32 + if not core.CGMainDisplayID(): + print('SKIP: macOS display contracts need a window server session') + return 77 + if args.probe: + print('macOS window server session present') + return 0 + assert all((args.tester, args.compiler, args.interpreter, args.sdk, args.source)) + env = dict(os.environ) + if args.provider_test: + checked([args.provider_test.resolve(), '--display'], env) + if args.lifecycle_test: + checked([args.lifecycle_test.resolve(), '--display'], env) + base = [args.tester.resolve(), 'run', '--compiler', args.compiler.resolve(), + '--interpreter', args.interpreter.resolve(), '--sdk-path', args.sdk.resolve(), + '--format', 'json', '--jobs', '1', '--timeout', '30'] + desktop = checked([*base, '--target', 'all' if args.llvm == 'ON' else 'vm', + '--filter', 'nil.std.ui.gtk.desktop', args.source.resolve()], env) + report = json.loads(desktop.stdout) + assert report['tests'] and not report['errors'], report + assert all(test['status'] == 'passed' for test in report['tests']), report + # The interaction suite is deliberately not run here. It needs keystrokes + # delivered to another process, and on macOS posting events to a different + # process requires accessibility trust that a hosted runner does not grant. + # Real input is covered in-process instead, by the provider fixture's own + # input probe, so this is a limit of cross-process injection rather than of + # the provider. Saying so beats quietly reporting a narrower contract. + print(f'macOS desktop contract passed: {len(report["tests"])} language cases, ' + 'interaction suite not covered (cross-process input needs accessibility trust)') + return 0 + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--xvfb', default=shutil.which('Xvfb')) @@ -258,6 +296,8 @@ def main(): parser.add_argument('--lifecycle-test', type=Path) parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') args = parser.parse_args() + if sys.platform == 'darwin': + return darwin(args) if sys.platform != 'linux' or not args.xvfb or not Path(args.xvfb).is_file() or not shutil.which('xauth'): print('SKIP: GTK display contracts need Linux, Xvfb and xauth') return 77 diff --git a/tests/ui_registry_observer.hpp b/tests/ui_registry_observer.hpp index 3760388f..b185cc78 100644 --- a/tests/ui_registry_observer.hpp +++ b/tests/ui_registry_observer.hpp @@ -6,12 +6,10 @@ #include #include #include -#if defined(__linux__) || defined(__APPLE__) +#if defined(__linux__) #include -#if defined(__APPLE__) -#include -#include -#endif +#elif defined(__APPLE__) +#import #elif defined(_WIN32) #ifndef NOMINMAX #define NOMINMAX @@ -21,34 +19,19 @@ // Test-only, independent observation of the toolkit's real live top-level // windows, so a lifecycle test can tell an actually released window from a -// merely invalidated handle. GTK is asked for its registry; Win32 has no such -// registry, so this counts the operating system's own top-level windows. +// merely invalidated handle. The question is the same on every platform and +// only the answerer differs. GTK is asked for its registry. AppKit is asked +// for the application's windows, which, like that registry, counts them +// whether or not they are on screen. Win32 has no registry at all, so the +// operating system's own top-level windows are counted instead. +// +// On macOS this header is Objective-C++, so whatever includes it is compiled +// as Objective-C++ too. class UiRegistryObserver { -#if !defined(_WIN32) +#if defined(__linux__) void *(*list_)() = nullptr; unsigned (*size_)(void *) = nullptr; -#endif -#if defined(__linux__) || defined(__APPLE__) void *library_ = nullptr; -#if defined(__APPLE__) - void *gio_ = nullptr; - int (*initialized_)() = nullptr; - static std::filesystem::path selected(const char *name) { - const char *directory = std::getenv("NIL_UI_GTK_DIRECTORY"); - if (!directory || !*directory || !std::filesystem::path(directory).is_absolute()) - throw std::runtime_error("GTK registry observer requires an absolute selected provider"); - auto file = std::filesystem::canonical(std::filesystem::path(directory) / name); - if (!std::filesystem::is_regular_file(file)) throw std::runtime_error("GTK registry dependency is not a regular file"); - return file; - } - static bool matches(void *symbol, const std::filesystem::path &file) { - Dl_info info{}; - std::error_code error; - return symbol && dladdr(symbol, &info) && info.dli_fname && - std::filesystem::path(info.dli_fname).is_absolute() && - std::filesystem::equivalent(file, info.dli_fname, error) && !error; - } -#endif #elif defined(_WIN32) // The provider's own window class, which must match window_class in // nilcompiler/src/ui_runtime_win32.cpp. Counting by class keeps the console @@ -72,59 +55,36 @@ class UiRegistryObserver { if (!library_) throw std::runtime_error("load GTK registry observer"); list_ = reinterpret_cast(dlsym(library_, "gtk_window_get_toplevels")); size_ = reinterpret_cast(dlsym(library_, "g_list_model_get_n_items")); -#elif defined(__APPLE__) - const auto gtk = selected("libgtk-4.1.dylib"); - const auto gio = selected("libgio-2.0.0.dylib"); - // Test-only GIO alias must identify GTK's already loaded dependency. Never - // introduce another provider while trying to independently count windows. - library_ = dlopen(gtk.c_str(), RTLD_NOLOAD | RTLD_NOW | RTLD_LOCAL); - gio_ = dlopen(gio.c_str(), RTLD_NOLOAD | RTLD_NOW | RTLD_LOCAL); - if (library_ && gio_) { - auto list = dlsym(library_, "gtk_window_get_toplevels"); - auto size = dlsym(gio_, "g_list_model_get_n_items"); - auto initialized = dlsym(library_, "gtk_is_initialized"); - if (matches(list, gtk) && matches(initialized, gtk) && matches(size, gio) && - matches(dlsym(library_, "g_list_model_get_n_items"), gio)) { - list_ = reinterpret_cast(list); - size_ = reinterpret_cast(size); - initialized_ = reinterpret_cast(initialized); - } - } -#endif -#if !defined(_WIN32) if (!list_ || !size_) { -#if defined(__linux__) || defined(__APPLE__) - if (library_) dlclose(library_); + dlclose(library_); library_ = nullptr; -#if defined(__APPLE__) - if (gio_) dlclose(gio_); - gio_ = nullptr; -#endif -#endif throw std::runtime_error("GTK registry observer symbols unavailable"); } +#elif defined(__APPLE__) + // The provider creates the shared application before any window, so a nil + // NSApp means nothing has been observed yet rather than an empty registry. + if (!NSApp) + throw std::runtime_error("AppKit registry observer requires an initialized application"); #endif } ~UiRegistryObserver() { -#if defined(__linux__) || defined(__APPLE__) +#if defined(__linux__) if (library_) dlclose(library_); -#if defined(__APPLE__) - if (gio_) dlclose(gio_); -#endif #endif } UiRegistryObserver(const UiRegistryObserver &) = delete; UiRegistryObserver &operator=(const UiRegistryObserver &) = delete; -#if defined(_WIN32) +#if defined(__linux__) + unsigned count() const { return size_(list_()); } +#elif defined(__APPLE__) + unsigned count() const { return static_cast(NSApp ? NSApp.windows.count : 0); } +#elif defined(_WIN32) unsigned count() const { unsigned total = 0; EnumWindows(&tally, reinterpret_cast(&total)); return total; } #else - unsigned count() const { return size_(list_()); } -#endif -#if defined(__APPLE__) - bool initialized() const { return initialized_() != 0; } + unsigned count() const { throw std::runtime_error("no registry observer for this platform"); } #endif };