#!/usr/bin/env bash # Build the Rust core's two iOS slices and wrap them in the ONE XCFramework the # iPhone app links. # # scripts/build-xcframework.sh [--debug] [--device-only|--simulator-only] [--dry-run] # # A CUT BUILDS THE SLICE IT SHIPS, AND ONLY THAT ONE. Under # `COTTON_CUT_ARCHIVE_ONLY=1` (the archive child the phone cut runs under # fastlane) the default is the device slice alone: the archive is # for a generic iOS device and never reads the simulator slice, and an # XCFramework holding one library is a valid one. Measured 27 Oct on one Mac, # cut 328 cross-compiled the device slice in 195 s AND the simulator slice in # 186 s it then threw away; the simulator slice is the walk and dev loop's # (`--simulator-only`), and a cut asking for it is refused rather than obeyed. # `--dry-run` names the slices and profile a run would build, and builds, # locks and keys nothing. # # Design P1: the phone is a THIRD CONSUMER of the same `cotton-ffi` — not a # second ABI and not a second crate. The six functions are the Mac's six, the # committed `include/cotton_ffi.h` is the Mac's header, and the event stream is # the Mac's event stream. So this script EXTENDS `build-rust-ffi.sh` rather than # replacing it: that script already takes `--target`, already exports a # deployment target, and already reads the archive path out of `cargo metadata` # instead of assuming `crates/target/` (CI sets CARGO_TARGET_DIR # under the lane's HOME). What is added here is the iOS deployment target, the # two triples, and `xcodebuild -create-xcframework` over the result. # # A `staticlib` and an XCFramework rather than a dylib: one binary, nothing # nested to sign, no dynamic loader, and a static archive is what lets the # linker drop everything the phone never calls. # # THREE RULES THAT COST SOMETHING WHEN BROKEN: # # * THE TWO SLICES BUILD SEQUENTIALLY, UNDER THE MACHINE-WIDE LOCK. The build # Mac is 16 GB and two heavy builds swap-crash it. This script takes # /tmp/tinmen-build.lock itself, so a caller does not have to remember — # and a caller that wraps this script in `scripts/with-build-lock.sh` # anyway is fine: that helper is RE-ENTRANT (it runs straight through when # the lock is already held by an ancestor of the asking process). What # `COTTON_XCFRAMEWORK_LOCKED` still guards is this script's re-exec of # ITSELF, which without a marker would re-exec for ever. # # * THE iOS SLICES ARE THE CLIENT BUILD: `--no-default-features` (design # P2; H1 made `host` the crate's only feature). Without it an iPhone app # links `cotton-server` and, behind it, mupdf's vendored C tree, axum, # hyper, tower, reqwest's http2 stack and rustls — none of which it runs. # `crates/cotton-ffi/tests/phone_boundary.rs` is the guard that says so # from the resolved dependency graph; this is the build that has to agree # with it. # # * `IPHONEOS_DEPLOYMENT_TARGET` is EXPORTED. An archive built without it is # tagged with whatever SDK this Mac happens to run, and iOS 26 # will not load it — the linker warns on every build and the failure lands # on a device rather than here. # # The output is a BUILD PRODUCT and gitignored: `apps/cotton/.ffi/CottonFFI.xcframework`, # the exact path `apps/cotton/Package.swift` declares its `binaryTarget` at — # UNCONDITIONALLY, since the machine-wide manifest cache made a filesystem test # there answer one worktree's question for every worktree on the Mac # (Cotton note "Repo landmines — why the build's rules exist"). When the archive is absent # `scripts/ffi-stub.sh` holds the path with a no-slice STUB, and BOTH write # paths below `rm -rf "$XCFRAMEWORK"` first, so a stub never survives beside # real slices. # # AND THE SWIFT BUILD PLAN GOES WITH IT. "An XCFramework's contents are read at # BUILD time, so nothing has to be reset" was true of the llbuild backend and is # FALSE under Swift Build (`.build/.buildSystem_debug` == `swiftbuild`), which # is what SwiftPM uses here: the archive's `Info.plist` is read while PLANNING, # and the plan decides whether a `CottonFFI` module exists at all. A no-slice # stub plans nothing, the plan is cached under `.build/manifest.pif` + # `.build/out/Intermediates.noindex/XCBuildData` keyed by the PIF and the build # REQUEST — never by the bytes under `.ffi/`, whose path is identical for a stub # and a real archive — and `swift build` and `swift test` are two different # requests with two different cached plans. So `swift test` kept the stub after # the real archive arrived, and deleting `manifest.pif` fixed `swift build` and # not `swift test` (PR #745, Cotton note "Repo landmines — why the build's rules exist"). Both write # paths below drop the plan, so the archive that is on disk is the archive the # next build plans against. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" CRATE_DIR="$ROOT/crates" HEADER="$CRATE_DIR/cotton-ffi/include/cotton_ffi.h" MODULE_MAP="$ROOT/apps/cotton/Sources/CottonFFI/module.modulemap" OUT_DIR="$ROOT/apps/cotton/.ffi" XCFRAMEWORK="$OUT_DIR/CottonFFI.xcframework" INCLUDE_DIR="$OUT_DIR/include" # A cut builds Swift outside its worktree (COTTON_SWIFT_SCRATCH); its plan is there. . "$ROOT/scripts/lib/swiftpm-cache.sh" SWIFTPM_BUILD_DIR="$(cotton_swiftpm_build_dir "$ROOT/apps/cotton")" # Drop the cached Swift Build plan, because it was planned against whatever was # at the XCFramework's path when it was made. Only the PLAN: `.build/artifacts`, # `.build/checkouts`, `.build/repositories` and `workspace-state.json` stay, so # Sparkle and Sentry are not re-fetched, and a blanket wipe of `.build` — minutes, # and a full re-resolve of every dependency — is not what this costs. invalidate_swiftpm_plan() { local p for p in "$SWIFTPM_BUILD_DIR/manifest.pif" \ "$SWIFTPM_BUILD_DIR/out/Intermediates.noindex/XCBuildData"; do [ -e "$p" ] || continue rm -rf "$p" echo "[xcframework] dropped the cached build plan at ${p#"$ROOT/"}" done } # THE ARGUMENTS, BEFORE THE LOOP EATS THEM. `shift` empties `$@`, so the lock # re-exec below has to replay a COPY — passing `"$@"` there sent an empty list # and made `--debug`, `--device-only` and `--simulator-only` silent no-ops for # every caller. Guarded by the build-xcframework-args test, # which runs this script with a stub on PATH and reads what the re-exec asked # for. ARGS=("$@") # A shipped slice is built at crates/Cargo.toml's `ios` profile (fat LTO, one # codegen unit: the linker keeps only what the phone calls, # 14 Nov 2026), a `--debug` one at the dev profile. PROFILE_ARGS=(--profile ios) PRINT_CACHE_KEY=0 DRY_RUN=0 PROFILE_DIR=ios SLICES=(device simulator) SLICES_ASKED="" while [ $# -gt 0 ]; do case "$1" in --debug) PROFILE_ARGS=(--debug); PROFILE_DIR=debug; shift ;; --device-only) SLICES=(device); SLICES_ASKED=device; shift ;; --simulator-only) SLICES=(simulator); SLICES_ASKED=simulator; shift ;; # Name what a run would build and stop: no key, no lock, no guard. --dry-run) DRY_RUN=1; shift ;; # The guard's hook: name the cache key's inputs and the key, build nothing, # take no lock. Parsed like any option. --print-cache-key) PRINT_CACHE_KEY=1; shift ;; # And the Rust half of the key alone, one input per line (the guard's). --print-rust-inputs) PRINT_CACHE_KEY=2; shift ;; *) echo "usage: build-xcframework.sh [--debug] [--device-only|--simulator-only] [--dry-run]" >&2; exit 2 ;; esac done # The cut's archive child ships the device slice only (see the header). if [ "${COTTON_CUT_ARCHIVE_ONLY:-}" = 1 ]; then if [ "$SLICES_ASKED" = simulator ]; then echo "[xcframework] a cut's archive (COTTON_CUT_ARCHIVE_ONLY=1) ships no simulator slice — refusing --simulator-only" >&2 exit 2 fi SLICES=(device) fi # THE WALK'S RUST LOOP: `--simulator-only --debug` is the coordinator's # simulator loop and nothing ships from it, so it is built for the next edit, # not for the cache. Measured 27 Oct on one Mac, the walk's simulator slice was # a release build at 3 jobs on a 12-core Mac with incremental off. Here: # * rustc's incremental mode ON, in a target directory of its own beside the # shared one (`-sim-dev`): sccache cannot key an incremental compile # and refuses to cache one, so the shared, sccache-fed, non-incremental # target is never handed incremental state, and this one is never handed # to sccache — the Mac policy's wrapper is kept, its cache wrapper dropped; # * every core but two; # * the dev profile with no LTO and unpacked split debuginfo (no dsymutil). # Every other mode, and every shipped build, is untouched by this block. DEV_LOOP=0 if [ "$PROFILE_DIR" = debug ] && [ "${SLICES[*]}" = simulator ]; then DEV_LOOP=1 fi if [ "$DRY_RUN" = 1 ]; then echo "[xcframework] would build: ${SLICES[*]} ($PROFILE_DIR$([ "$DEV_LOOP" = 1 ] && echo ", incremental"))" exit 0 fi if [ "$DEV_LOOP" = 1 ]; then export CARGO_INCREMENTAL=1 # Exported before the cache key is taken, so the key names this profile. export CARGO_PROFILE_DEV_LTO=false CARGO_PROFILE_DEV_SPLIT_DEBUGINFO=unpacked # Present and empty, so the worktree config's `[env]` does not set it. export COTTON_RUSTC_CACHE_WRAPPER="" case "$(basename "${RUSTC_WRAPPER:-}")" in sccache) export RUSTC_WRAPPER="" ;; esac cores="$(sysctl -n hw.ncpu 2>/dev/null || getconf _NPROCESSORS_ONLN)" export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-$(( cores > 3 ? cores - 2 : 1 ))}" # Idempotent across the lock re-exec, which inherits the exported name. case "${CARGO_TARGET_DIR:-}" in *-sim-dev) ;; *) shared_target="${CARGO_TARGET_DIR:-$(bash "$ROOT/scripts/ci/cargo-target-dir.sh" ffi)}" CARGO_TARGET_DIR="$(bash "$ROOT/scripts/ci/cargo-target-dir.sh" --ensure --per-ref "$(basename "$shared_target")-sim-dev" "$(dirname "$shared_target")")" export CARGO_TARGET_DIR echo "[xcframework] dev loop: incremental, $CARGO_BUILD_JOBS jobs, target $CARGO_TARGET_DIR" ;; esac fi triple_for() { case "$1" in device) echo aarch64-apple-ios ;; simulator) echo aarch64-apple-ios-sim ;; esac } # Which build each slice is (see the header): the phone's slices carry no # server. features_for() { case "$1" in device|simulator) echo "--no-default-features" ;; esac } # The iOS floor, out of `project.yml`'s `deploymentTarget:` block. Every `iOS:` # key in that file has to agree: if the app ever gives one target a different # floor, this refuses rather than picking one of them and building the archive # for the wrong iOS. PROJECT_YML="$ROOT/apps/cotton/project.yml" deployment_target() { local found found="$(sed -n 's/^[[:space:]]*iOS:[[:space:]]*"\{0,1\}\([0-9][0-9.]*\)"\{0,1\}[[:space:]]*$/\1/p' "$PROJECT_YML" | sort -u)" if [ -z "$found" ]; then echo "[xcframework] $PROJECT_YML declares no deploymentTarget.iOS — refusing to guess a floor" >&2 exit 1 fi if [ "$(printf '%s\n' "$found" | wc -l | tr -d ' ')" != 1 ]; then echo "[xcframework] $PROJECT_YML names more than one iOS floor: $(echo $found)" >&2 echo "[xcframework] one archive cannot satisfy two — give them one floor." >&2 exit 1 fi echo "[xcframework] iOS floor $found, read from ${PROJECT_YML#"$ROOT/"}" >&2 printf '%s\n' "$found" } # THE DEPLOYMENT TARGET IS READ, NOT RESTATED. iOS 26 is the floor for the app # and its share extension, and `apps/cotton/project.yml` is where that floor is # declared — a second number written here is a constant that drifts the day the # app raises its own and nothing goes red. # A plain assignment, never `export VAR=$(...)`: for a declaration builtin bash # reports the BUILTIN's status, so a `set -e` script sails past a failed # substitution with an empty floor. if [ -z "${IPHONEOS_DEPLOYMENT_TARGET:-}" ]; then IPHONEOS_DEPLOYMENT_TARGET="$(deployment_target)" || exit 1 fi export IPHONEOS_DEPLOYMENT_TARGET export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-3}" # THE CACHE: A BUILT XCFRAMEWORK IS A PURE FUNCTION OF ITS INPUTS, SO NAME IT. # # `build-main.yml` runs daily and `verify-main.yml`'s `ios` job runs on every PR # that touches the phone's graph. Most of those runs are handed a `crates/` tree # byte-identical to one this machine has already cross-compiled twice — and the # two iOS slices are the expensive half of both lanes. A target directory cannot # answer that (cargo keys freshness by mtime against one path, and each lane has # its own path); a content key can. # # THE KEY IS EVERY INPUT THAT CAN CHANGE THE BYTES, and nothing else: # * THE RUST THE SLICES ACTUALLY COMPILE (`xc_rust_inputs`, 29 Sep 2026): # cotton-ffi's dependency closure, for the feature set each asked slice is # built with — `--no-default-features` for the iOS slices — read from # `cargo metadata`: # each workspace crate in it by its committed TREE hash (its sources, its # manifest, its build script, its `cotton_ffi.h`), each registry or git # package by its id (name, version, source — immutable), and the # workspace's `Cargo.toml` (profiles, `[patch]`) and `rust-toolchain.toml`. # Until then it was `HEAD:crates`, the whole workspace, so a change to a # crate no slice links — cotton-server for the phone, cotton-gen or the # conformance recorder for both — missed every time (measured: the swift # job's framework step 3m04 on a miss). NO CRATE IN EITHER CLOSURE READS A # FILE OUTSIDE ITS OWN DIRECTORY (`include_str!`, `include_bytes!`, # `#[path]` — the guard walks them), so a crate's tree is its whole input. # `cargo metadata` unifies features across the workspace and lists every # platform's dependencies, so each closure is a superset of what the build # reads — a spare input costs a miss, never a stale hit. When the closure # cannot be read (no cargo or jq yet, metadata refused, cotton-ffi absent, # a crate outside `crates/`), the key falls back to `HEAD:crates`. # * the module map, which does NOT live under `crates/` and IS copied in. # * THIS SCRIPT AND `build-rust-ffi.sh`, by their committed blob hashes: the # cargo invocation, the features per slice and the deployment floors are # decided here, so an edit here is an edit to the bytes. (Added 27 Sep 2026 # when the cache became shared between Macs — a key that omitted them # would serve one Mac's build to another Mac running a newer script.) # * the profile (debug archives are not release archives), the slice list # (a `--device-only` build is not an XCFramework of both), the resolved # iOS deployment floor, which is stamped INTO each archive. # * `rustc -V`. A toolchain bump changes the code generator and nothing else # on this list moves. # * `xcodebuild -version` — Xcode's clang compiles SQLite's amalgamation and # MuPDF into the archive, its SDK sets the linked floors, and # `-create-xcframework` is its tool. # * EVERY ENVIRONMENT VARIABLE CARGO OR RUSTC READS THAT CHANGES CODEGEN: # `CARGO_PROFILE_*` (the CI lanes set `CARGO_PROFILE_DEV_DEBUG=0`; a # developer's shell does not, and those are different bytes under the same # tree), `RUSTFLAGS` and cargo's two spellings of it, `RUSTC`, # `RUSTC_BOOTSTRAP`, `CARGO_UNSTABLE_*`. Not `RUSTC_WRAPPER` (sccache # changes nothing about the output) and not `CARGO_BUILD_JOBS`. # * every cargo config file cargo would read — the repo's, `crates/`', the # user's — by content, because `[build] rustflags` lives there. A # developer's worktree carries one (`worktree-new.sh` writes target-dir # and the sccache wrapper into it), and it is keyed rather than refused so # that two developers with the same config share. # # WHAT THE KEY DOES NOT COVER, DELIBERATELY: where the sources sat. Two Macs # compiling the same tree from different paths produce archives that differ # only in the source-path STRINGS embedded for panic messages (`file!()` of a # registry crate is its absolute path under CARGO_HOME). Nothing executes # differently, and keying on paths would make every lane its own cache again — # which is the state this key exists to end. # # IT IS OFF THE MOMENT THE TREE IS DIRTY, in either direction — no read and no # write. `HEAD:crates` describes what is COMMITTED, and a developer mid-edit has # a workspace that hash does not describe; serving them a cached archive of # somebody else's code is the worst failure this script could have, and writing # their half-finished build under a committed tree's name is the second worst. # The two scripts are held to the same rule. CI checkouts are clean by # construction, which is where the saving is anyway. # # THE SHARED STORE. The local cache is asked first; on a miss the CI artifact # store on the Linux box (over the tailnet) is # asked for the same key and its answer becomes the local entry; after a build # the local entry is handed to the store. `scripts/ci/artifact-store.sh` is # fail-open in every direction — no store, a store that is away, a body that # does not unpack — so this script never fails a build over its cache. What the # store buys: one cross-compile per distinct set of inputs across every Mac, # instead of one per Mac that meets the commit (measured 27 Sep 2026: the same # tree compiled on one Mac for `swift`, on another for `ios`, on a third for the re-push). # # BOUNDED, LIKE EVERY OTHER CACHE ON THESE MACHINES: the newest # COTTON_XCFRAMEWORK_CACHE_KEEP (default 12) entries survive, oldest first out. # Retain enough distinct slice/profile combinations for concurrent lanes. # Hits refresh the entry mtime, so eviction follows use rather than build age. XC_CACHE_ROOT="${COTTON_XCFRAMEWORK_CACHE:-$HOME/.cache/cottondb/xcframework}" # shellcheck source=/dev/null . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/owned-root.sh" refuse_wide_root "the xcframework cache (COTTON_XCFRAMEWORK_CACHE)" "$XC_CACHE_ROOT" XC_CACHE_KEEP="${COTTON_XCFRAMEWORK_CACHE_KEEP:-12}" XC_CACHE_DIR="" # The two scripts whose text decides the bytes, relative to the repo root. XC_KEY_SCRIPTS=(scripts/build-xcframework.sh scripts/build-rust-ffi.sh) # The environment cargo and rustc read that changes what they emit — sorted, # one line, so the same shell always spells it the same way. `xc_codegen_env` # is a function so the guard can call it with a controlled environment. # And COTTON_CORE_KIT: the one app kit whose pictures the core carries # (crates/cotton-core/src/kit_pictures.rs; unset is the whole core). It is in # the key, or one app's archive would be served to another from the cache. xc_codegen_env() { env | LC_ALL=C grep -E '^(COTTON_CORE_KIT|CARGO_PROFILE_[A-Za-z0-9_]+|RUSTFLAGS|CARGO_ENCODED_RUSTFLAGS|CARGO_BUILD_RUSTFLAGS|CARGO_BUILD_TARGET|CARGO_UNSTABLE_[A-Za-z0-9_]+|RUSTC|RUSTC_BOOTSTRAP)=' \ | LC_ALL=C sort | tr '\n' ' ' } # Every cargo config file cargo would read for a build from `crates/`, by # content. Absent files contribute nothing; present ones contribute their hash. xc_cargo_configs() { local f for f in "$ROOT/.cargo/config.toml" "$ROOT/.cargo/config" \ "$ROOT/crates/.cargo/config.toml" "$ROOT/crates/.cargo/config" \ "${CARGO_HOME:-$HOME/.cargo}/config.toml" "${CARGO_HOME:-$HOME/.cargo}/config"; do [ -f "$f" ] && git -C "$ROOT" hash-object "$f" 2>/dev/null done | tr '\n' ' ' } # cotton-ffi's closure: one line per package, `path ` for a # workspace crate and `pkg ` for anything else. Dev-only edges are not # followed — no dev-dependency is compiled into an archive. XC_CLOSURE_JQ=' (.resolve.nodes | map({key: .id, value: [.deps[] | select(any(.dep_kinds[]; .kind != "dev")) | .pkg]}) | from_entries) as $edges | (.packages | map({key: .id, value: .}) | from_entries) as $pk | ([.packages[] | select(.name == $root) | .id]) as $start | {seen: $start, todo: $start} | until(.todo | length == 0; .todo[0] as $x | .seen as $s | ([($edges[$x] // [])[] | select(. as $n | ($s | index([$n])) == null)] | unique) as $new | .seen += $new | .todo = .todo[1:] + $new) | .seen | map($pk[.]) | .[] | if .source == null then "path \(.name) \(.manifest_path)" else "pkg \(.id)" end' # The Rust half of the key, one input per line, sorted. See THE KEY above. xc_rust_inputs() { local whole flags=() flag s meta closure="" kind name rest rel tree real_root lines="" whole="tree $(git -C "$ROOT" rev-parse HEAD:crates 2>/dev/null)" for s in ${SLICES[@]+"${SLICES[@]}"}; do case "$s" in device|simulator) flags+=(--no-default-features); break ;; esac done if [ "${#flags[@]}" -eq 0 ] || ! command -v cargo >/dev/null 2>&1 || ! command -v jq >/dev/null 2>&1; then echo "$whole"; return 0 fi for flag in "${flags[@]}"; do meta="$(cd "$ROOT/crates" && cargo metadata --format-version 1 "$flag" --locked 2>/dev/null)" || { echo "$whole"; return 0; } closure+="$(jq -r --arg root cotton-ffi "$XC_CLOSURE_JQ" <<<"$meta" 2>/dev/null)"$'\n' || { echo "$whole"; return 0; } done grep -q '^path cotton-ffi ' <<<"$closure" || { echo "$whole"; return 0; } real_root="$(cd "$ROOT" && pwd -P)" while read -r kind name rest; do case "$kind" in path) rel="$(dirname "$rest")"; rel="${rel#"$real_root"/}"; rel="${rel#"$ROOT"/}" case "$rel" in crates/*) ;; *) echo "$whole"; return 0 ;; esac tree="$(git -C "$ROOT" rev-parse "HEAD:$rel" 2>/dev/null)" || { echo "$whole"; return 0; } lines+="path $name $tree"$'\n' ;; pkg) lines+="pkg $name"$'\n' ;; '') ;; *) echo "$whole"; return 0 ;; esac done <<<"$closure" lines+="workspace $(git -C "$ROOT" rev-parse HEAD:crates/Cargo.toml HEAD:crates/rust-toolchain.toml 2>/dev/null | paste -sd ' ' -)"$'\n' printf '%s' "$lines" | LC_ALL=C sort -u } xc_cache_key() { local tree modmap rustc_v xcode_v dirty scripts # Not a git checkout at all (a tarball, a vendored copy): no key, no cache. tree="$(git -C "$ROOT" rev-parse HEAD:crates 2>/dev/null || true)" [ -n "$tree" ] || { echo "[xcframework] cache off: crates/ has no committed tree hash here" >&2; return 1; } dirty="$(git -C "$ROOT" status --porcelain -- crates "$MODULE_MAP" "${XC_KEY_SCRIPTS[@]}" 2>/dev/null || true)" if [ -n "$dirty" ]; then echo "[xcframework] cache off: crates/, the module map or a build script differs from HEAD, so HEAD's hashes do not describe this build" >&2 return 1 fi modmap="$(git -C "$ROOT" hash-object "$MODULE_MAP" 2>/dev/null || true)" [ -n "$modmap" ] || return 1 # The scripts by their COMMITTED blobs (the dirty check above says they are # what HEAD holds), so a Mac on an older commit of this file never reads a # newer Mac's archive as its own. scripts="$(git -C "$ROOT" rev-parse "HEAD:${XC_KEY_SCRIPTS[0]}" "HEAD:${XC_KEY_SCRIPTS[1]}" 2>/dev/null | tr '\n' ' ' || true)" [ -n "$scripts" ] || { echo "[xcframework] cache off: the build scripts have no committed blobs here" >&2; return 1; } # NO PLACEHOLDER HERE. A toolchain bump changes the code generator and nothing # else on this list moves, so a key that shrugged at a missing `rustc` would # serve the old compiler's archives after the upgrade. No rustc, no cache. rustc_v="$(rustc -V 2>/dev/null || true)" [ -n "$rustc_v" ] || { echo "[xcframework] cache off: no rustc on PATH to name in the key" >&2; return 1; } # Same rule for Xcode: its clang and SDK are in the archive. xcode_v="$(xcodebuild -version 2>/dev/null | tr '\n' ' ' || true)" [ -n "$xcode_v" ] || { echo "[xcframework] cache off: no xcodebuild on PATH to name in the key" >&2; return 1; } local -a sum if command -v shasum >/dev/null 2>&1; then sum=(shasum -a 256) elif command -v sha256sum >/dev/null 2>&1; then sum=(sha256sum) else echo "[xcframework] cache off: neither shasum nor sha256sum on PATH" >&2; return 1; fi # The Rust the asked slices compile, not the whole workspace (THE KEY). tree="rust:$(xc_rust_inputs | "${sum[@]}" | cut -c1-40)" printf '%s\n' "$tree $modmap $scripts $PROFILE_DIR ${SLICES[*]} $IPHONEOS_DEPLOYMENT_TARGET $rustc_v $xcode_v $(xc_codegen_env) $(xc_cargo_configs)" \ | "${sum[@]}" | cut -c1-32 } # Testing hook: print the key's inputs and the key, without building. if [ "$PRINT_CACHE_KEY" = 2 ]; then xc_rust_inputs exit $? fi if [ "$PRINT_CACHE_KEY" = 1 ]; then echo "codegen-env: $(xc_codegen_env)" echo "cargo-configs: $(xc_cargo_configs)" xc_cache_key exit $? fi xc_in_place() { printf '%s %s\n' "$1" "$(stat -f '%i:%m' "$XCFRAMEWORK/Info.plist" "$INCLUDE_DIR" 2>/dev/null | tr '\n' ' ')" } if key="$(xc_cache_key)" && [ -n "$key" ]; then XC_CACHE_DIR="$XC_CACHE_ROOT/$key" # THE STORE, on a local miss. Its client writes the whole entry by rename or # nothing at all, so the check below reads either a hit or the same miss. if [ ! -d "$XC_CACHE_DIR/CottonFFI.xcframework" ]; then bash "$ROOT/scripts/ci/artifact-store.sh" get xcframework "$key" "$XC_CACHE_DIR" || true fi # ALREADY IN PLACE: a cut's lane builds in one stable worktree, and # copying the same framework over itself # gives its headers new mtimes, so every Swift module importing CottonFFI # would recompile on a commit that changed no Rust. The marker names the key # AND the inode and mtime of what it was written beside, so a stub or any # other rewrite of the directory reads as a miss, never as this key. if [ -d "$XCFRAMEWORK" ] && [ -f "$OUT_DIR/.cache-key" ] && [ "$(cat "$OUT_DIR/.cache-key")" = "$(xc_in_place "$key")" ]; then touch "$XC_CACHE_DIR" 2>/dev/null || true echo "[xcframework] $XCFRAMEWORK is already $key — left untouched" exit 0 fi if [ -d "$XC_CACHE_DIR/CottonFFI.xcframework" ]; then echo "[xcframework] cache HIT $key — copying instead of cross-compiling ${SLICES[*]}" # The whole directory goes, `scripts/ffi-stub.sh`'s placeholder included: a # stub beside real slices would be an XCFramework nobody can read. rm -rf "$XCFRAMEWORK" "$INCLUDE_DIR" mkdir -p "$OUT_DIR" cp -R "$XC_CACHE_DIR/CottonFFI.xcframework" "$XCFRAMEWORK" cp -R "$XC_CACHE_DIR/include" "$INCLUDE_DIR" # Touched so the eviction below reads "recently used" rather than # "recently built" — a key everybody keeps hitting must not age out. touch "$XC_CACHE_DIR" invalidate_swiftpm_plan xc_in_place "$key" > "$OUT_DIR/.cache-key" echo "[xcframework] $XCFRAMEWORK — $(du -sh "$XCFRAMEWORK" | cut -f1) ($PROFILE_DIR, from cache)" exit 0 fi echo "[xcframework] cache MISS $key — building ${SLICES[*]}" fi # A miss takes the lock before building; a cache hit above never queues. `BUILD_LOCK_LABEL` names who is waiting in # somebody else's log line, so a queue on this Mac is readable. If a caller # already holds the lock, the helper says "re-entered" and runs on. if [ "${COTTON_XCFRAMEWORK_LOCKED:-}" != "1" ] && [ "$PRINT_CACHE_KEY" = 0 ]; then export COTTON_XCFRAMEWORK_LOCKED=1 # `${ARGS[@]+...}` because an empty array under `set -u` is an unbound # variable, not an empty expansion. exec env BUILD_LOCK_LABEL="${BUILD_LOCK_LABEL:-cotton-ios-xcframework}" \ bash "$ROOT/scripts/with-build-lock.sh" bash "${BASH_SOURCE[0]}" \ ${ARGS[@]+"${ARGS[@]}"} fi # `target/` on this Mac has stood at 68 GB against a 228 GB boot disk, and two # more iOS slices are not free. The release workflow already runs this before a # heavy build; the iOS lanes do the same (design P1). # # NOT WHEN ONLY THE KEY IS ASKED FOR. `--print-cache-key` is a question, and a # question has no side effects: it skipped the lock above, and it must skip the # guard here too. Until it did, every test that printed the key ran the guard # against the machine's real HOME — on the Linux CI host, where `df -g` read # 0G, that was the guard's deep tier emptying sccache and every per-branch # target under a running job, 19 times on 28 Sep 2026 (run 613). if [ "$PRINT_CACHE_KEY" = 0 ] && [ -x "$ROOT/scripts/disk-guard.sh" ]; then bash "$ROOT/scripts/disk-guard.sh" --pre-build fi # A toolchain that is INSTALLED but not on PATH is the other half of the same # question, and it is the one a non-interactive shell hits: rustup writes # `~/.cargo/bin` and a line in the profile, and nothing that is not a login # shell reads that line. Asked first, because `rustup` itself lives there too — # without this the check below fails as `rustup: command not found`. CARGO_PATH_LOG_PREFIX="[xcframework]" # shellcheck source=lib/cargo-path.sh . "$ROOT/scripts/lib/cargo-path.sh" ensure_cargo_on_path || exit 1 # The Rust toolchain has to actually carry the two iOS targets. Checked BY NAME # up front rather than met as a cargo error four hundred lines in, and the fix # is one line the message carries. # # The check itself is `scripts/lib/rust-targets.sh`, which keeps rustup's stderr # instead of discarding it: a rustup that cannot resolve a toolchain here fails # with an empty list, and reading that as "no iOS targets" sends the reader to # install what is already installed. RUST_TARGETS_LOG_PREFIX="[xcframework]" # shellcheck source=lib/rust-targets.sh . "$ROOT/scripts/lib/rust-targets.sh" triples=() for slice in "${SLICES[@]}"; do triples+=("$(triple_for "$slice")") done require_rust_targets "${triples[@]}" || exit 1 archives=() for slice in "${SLICES[@]}"; do triple="$(triple_for "$slice")" features="$(features_for "$slice")" echo "[xcframework] $slice ($triple), iOS $IPHONEOS_DEPLOYMENT_TARGET, $features (the client build), pictures: ${COTTON_CORE_KIT:-every kit}" started=$(date +%s) # SEQUENTIAL. Never `&` and never two of these in parallel: see the header. # `$features` is unquoted on purpose: it is one or two words for cargo. # shellcheck disable=SC2086 archive="$(bash "$ROOT/scripts/build-rust-ffi.sh" \ ${PROFILE_ARGS[@]+"${PROFILE_ARGS[@]}"} \ --target "$triple" \ $features \ --print-archive)" [ -f "$archive" ] || { echo "[xcframework] no archive for $triple" >&2; exit 1; } echo "[xcframework] $slice: $(du -h "$archive" | cut -f1) unstripped in $(( $(date +%s) - started ))s" archives+=("$archive") done # The headers directory the XCFramework carries. BOTH files are copied from # their one committed source on every run, which is what keeps "no second # declaration of the ABI" true for a build product: the only way to make one of # these is to run this script, and this script cannot make a stale one. [ -f "$HEADER" ] || { echo "[xcframework] the committed header is missing: $HEADER" >&2; exit 1; } [ -f "$MODULE_MAP" ] || { echo "[xcframework] the module map is missing: $MODULE_MAP" >&2; exit 1; } rm -rf "$INCLUDE_DIR" mkdir -p "$INCLUDE_DIR" cp "$HEADER" "$INCLUDE_DIR/cotton_ffi.h" cp "$MODULE_MAP" "$INCLUDE_DIR/module.modulemap" # `-create-xcframework` REFUSES to overwrite, with a message about the output # already existing rather than about anything you did — and this is also what # takes `scripts/ffi-stub.sh`'s placeholder out of the way. rm -rf "$XCFRAMEWORK" mkdir -p "$OUT_DIR" create=(xcodebuild -create-xcframework) for archive in "${archives[@]}"; do create+=(-library "$archive" -headers "$INCLUDE_DIR") done create+=(-output "$XCFRAMEWORK") echo "[xcframework] ${create[*]}" "${create[@]}" # INTO THE CACHE, under the key computed before the build. Written to a # neighbouring directory and renamed, so a run killed halfway never leaves a # half-copied XCFramework under a name the next run will trust: `mv` of a # directory within one filesystem is atomic, a `cp -R` into the final name is # not. if [ -n "$XC_CACHE_DIR" ]; then staging="$XC_CACHE_DIR.partial.$$" rm -rf "$staging" mkdir -p "$staging" if cp -R "$XCFRAMEWORK" "$staging/CottonFFI.xcframework" && cp -R "$INCLUDE_DIR" "$staging/include"; then rm -rf "$XC_CACHE_DIR" mv "$staging" "$XC_CACHE_DIR" echo "[xcframework] cached as $(basename "$XC_CACHE_DIR")" # AND TO THE STORE, so the next Mac that meets this key copies instead of # compiling. Fail-open: the client never exits non-zero for a store that # is off or away, and `|| true` holds the line under `set -e` regardless. bash "$ROOT/scripts/ci/artifact-store.sh" put xcframework "$key" "$XC_CACHE_DIR" || true # Oldest out, newest KEEP kept. `ls -dt` orders by mtime, and the hit path # above touches what it uses, so this is least-recently-USED. # shellcheck disable=SC2012 ls -dt "$XC_CACHE_ROOT"/* 2>/dev/null | { retained=0 while IFS= read -r old; do # Another builder may be copying a staging entry right now. Only # completed, published entries count towards the cache allowance. case "$old" in *.partial.*) continue ;; esac [ ! -L "$old" ] && [ -d "$old/CottonFFI.xcframework" ] && [ -d "$old/include" ] || continue retained=$(( retained + 1 )) [ "$retained" -gt "$XC_CACHE_KEEP" ] || continue case "$old" in "$XC_CACHE_ROOT"/?*) rm -rf "$old"; echo "[xcframework] evicted $(basename "$old") — beyond the $XC_CACHE_KEEP most recently used" ;; esac done } else # A cache that cannot be written is not a build failure. Say so and move on. rm -rf "$staging" echo "[xcframework] could not write the cache under $XC_CACHE_ROOT — the build itself is fine" >&2 fi fi invalidate_swiftpm_plan [ -z "$XC_CACHE_DIR" ] || xc_in_place "$key" > "$OUT_DIR/.cache-key" echo "[xcframework] $XCFRAMEWORK — $(du -sh "$XCFRAMEWORK" | cut -f1) ($PROFILE_DIR)"