diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa59d10ca9..db8943303e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ All notable changes to scriptc will be documented in this file.
## Unreleased
+### Features
+
+- **Library archives build for iOS and Android.** `SCRIPTC_TARGET=aarch64-apple-ios`, `aarch64-apple-ios-simulator`, and `aarch64-linux-android` produce library-mode static archives for an embedding app to link — Xcode projects on the Apple side, Gradle/NDK builds on the Android side. iOS archives compile against the selected Xcode SDK with an iOS 15.0 minimum (stamped into every object's `LC_BUILD_VERSION`) and localize with the macOS host linker; Android archives compile against the NDK's bionic headers at API level 26 and use the same in-process ELF localization as the Linux cross targets. Multi-instance (`abi.localize_runtime`) and thread-instanced (`abi.instance_per_thread`) profiles carry over unchanged, verified by simulator- and emulator-executed probes; standalone executable builds refuse these targets with a pointer to `--lib`.
+
## 0.0.28
diff --git a/docs/src/app/platforms/page.mdx b/docs/src/app/platforms/page.mdx
index fbfbce8242..cb2c415a6b 100644
--- a/docs/src/app/platforms/page.mdx
+++ b/docs/src/app/platforms/page.mdx
@@ -35,6 +35,26 @@ fib.exe: PE32+ executable (console) x86-64, for MS Windows
The full corpus runs in a differential lane against Windows Node, including `--dynamic` programs and `child_process`. The Windows fixture lanes also exercise real loopback traffic through `net`, `http`, `https`, `tls`, `http2`, `dgram`, and `dns`, plus the native `fetch` implementation (including redirects, streaming bodies, compression, cancellation, and proxy handling).
+### iOS and Android (arm64, library mode)
+
+Three mobile triples build **library-mode static archives** for an embedding app to link — a mobile app is the executable, so `scriptc build` without `--lib` rejects these targets with `SC3002`:
+
+
+ SCRIPTC_TARGET=aarch64-apple-ios
+ - iOS device archives (Mach-O, arm64). Requires a macOS host with Xcode's iPhoneOS SDK. Every object carries
LC_BUILD_VERSION with minimum OS 15.0.
+ SCRIPTC_TARGET=aarch64-apple-ios-simulator
+ - iOS simulator archives (Mach-O, arm64, simulator platform). Requires a macOS host with Xcode's iPhoneSimulator SDK. Same iOS 15.0 minimum.
+ SCRIPTC_TARGET=aarch64-linux-android
+ - Android archives (ELF, arm64) compiled against the NDK's bionic headers at API level 26 — the embedder's
minSdkVersion must be 26 or higher. Requires an Android NDK: ANDROID_NDK_ROOT, or the newest ndk/<version> under ANDROID_HOME or the default SDK location.
+
+
+```console
+$ SCRIPTC_CC=zigcc SCRIPTC_TARGET=aarch64-apple-ios scriptc build --lib --profile app.profile.json
+$ SCRIPTC_CC=zigcc SCRIPTC_TARGET=aarch64-linux-android scriptc build --lib --profile app.profile.json
+```
+
+The full library-mode feature set applies: profile-declared exports and ABI entry points, contract sidecars, determinism fences, `abi.localize_runtime` (multi-instance archives — Mach-O localization runs the macOS host linker for both iOS platforms; Android rides the same in-process ELF localization as the Linux cross targets), and `abi.instance_per_thread` (thread-instanced state). The archive's external-symbol contract is unchanged: undefined references only to the target's C/math runtime and system APIs, resolved by Xcode's link against the selected SDK or the NDK clang link at API 26+. Simulator and emulator execution of the archive probes is part of the test matrix; device-architecture archives are build- and link-verified.
+
### WebAssembly (WASI Preview 1)
Set SCRIPTC_CC=zigcc and SCRIPTC_TARGET=wasm32-wasi to produce a standalone .wasm module. Without -o, scriptc build hello.ts writes .scriptc/hello.wasm. scriptc run hosts the module with Node's WASI implementation, inherits stdio and environment, preopens the current working directory as /, and maps the host platform's temporary directory to the guest's /tmp. A built module can run in another WASI Preview 1 host instead.
@@ -47,6 +67,8 @@ The remaining executable boundary is host capability, not language coverage. WAS
- `--sanitize` is a host-build lane.
- Library-mode static archives are native embedder artifacts; wasm32-wasi rejects scriptc build --lib with SC3002.
+- Mobile triples are library-mode-only: standalone executable builds reject with SC3002, and only the library-admissible surface (the async-free static tier a library archive links) is supported there.
+- iOS targets build on macOS hosts only (the Apple SDK sysroot and Mach-O localization); Android targets build from any host with an NDK.
- WASI cannot host APIs for capabilities missing from Preview 1, as described above.
## Summary
@@ -75,6 +97,16 @@ The remaining executable boundary is host capability, not language coverage. WAS
SCRIPTC_CC=zigcc SCRIPTC_TARGET=x86_64-windows-gnu |
Static and dynamic surfaces incl. servers, TLS, fetch, and child_process; verified against Windows Node |
+
+ | iOS arm64 (device and simulator) |
+ SCRIPTC_CC=zigcc SCRIPTC_TARGET=aarch64-apple-ios or aarch64-apple-ios-simulator, macOS host with Xcode |
+ Library mode only (--lib): static archives for Xcode projects, iOS 15.0 minimum; multi-instance and thread-instanced profiles; simulator-executed test matrix |
+
+
+ | Android arm64 |
+ SCRIPTC_CC=zigcc SCRIPTC_TARGET=aarch64-linux-android, any host with an NDK |
+ Library mode only (--lib): static archives for Gradle/NDK projects, API level 26 minimum; multi-instance and thread-instanced profiles; emulator-executed test matrix |
+
| WebAssembly / WASI Preview 1 |
SCRIPTC_CC=zigcc SCRIPTC_TARGET=wasm32-wasi |
diff --git a/packages/compiler/src/backend/cc.ts b/packages/compiler/src/backend/cc.ts
index 67e9b9e03d..94a00daa25 100644
--- a/packages/compiler/src/backend/cc.ts
+++ b/packages/compiler/src/backend/cc.ts
@@ -1,6 +1,6 @@
-import { execFile } from "node:child_process";
+import { execFile, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
-import { constants as fsConstants } from "node:fs";
+import { constants as fsConstants, existsSync, readdirSync } from "node:fs";
import { createRequire } from "node:module";
import { access, chmod, copyFile, link, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, unlink, utimes, writeFile } from "node:fs/promises";
import { availableParallelism, homedir, tmpdir } from "node:os";
@@ -426,18 +426,213 @@ export function runtimeSrcDir(): string {
* _WIN32 block in scr_runtime.h), linking -ladvapi32 for its CSPRNG
* (RtlGenRandom) and GetUserNameA. Native zigcc builds (no SCRIPTC_TARGET)
* support everything: same platform, same archives, just a different
- * driver binary. */
+ * driver binary.
+ * Mobile triples (aarch64-apple-ios, aarch64-apple-ios-simulator,
+ * aarch64-linux-android — see the mobile-targets block below) are
+ * LIBRARY-MODE targets: compileLibArchive accepts them, compile()/compileC
+ * refuse the executable lane with the pointer to --lib. */
export interface CcDriver {
/** The compiler argv prefix: ["clang"] (default) or ["zig", "cc"]. */
argv: string[];
/** The SCRIPTC_TARGET triple, or null for a host-native build. */
target: string | null;
+ /** The spelling handed to `zig cc -target` (and the relocatable-merge
+ * link). Identical to `target` except for the mobile triples, whose
+ * canonical LLVM spellings map to zig's own (`aarch64-apple-ios` →
+ * `aarch64-ios.15.0`), pinning the minimum OS version in the same
+ * breath. Null for a host-native build. */
+ zigTarget: string | null;
/** Extra compile args the produced platform demands. */
targetArgs: string[];
/** Platform libraries appended after every object/archive input. */
linkArgs: string[];
}
+/* ── mobile targets (library mode) ─────────────────────────────────────────
+ * Three mobile triples are admitted, and only for LIBRARY-MODE archive
+ * builds — the consuming pattern is an embedding app linking the archive,
+ * never a standalone executable (compile()/compileC refuse the executable
+ * lane with the pointer to --lib):
+ *
+ * aarch64-apple-ios device archives; zig `aarch64-ios.15.0`
+ * aarch64-apple-ios-simulator simulator archives; zig
+ * `aarch64-ios.15.0-simulator`
+ * aarch64-linux-android zig `aarch64-linux-android.26`
+ *
+ * The minimum-version floors are part of the target contract: iOS archives
+ * build for iOS 15.0 (IPHONEOS_MIN_VERSION), Android archives for API level
+ * 26 (ANDROID_MIN_API) — LC_BUILD_VERSION minos and the bionic stub level
+ * both come from the pinned zig spelling above, so an embedder's deployment
+ * target at or above the floor links cleanly.
+ *
+ * Zig bundles no Apple or bionic libc, so both families compile against an
+ * explicit sysroot discovered here and spelled into targetArgs (where every
+ * cache tier already keys it):
+ *
+ * iOS darwin hosts only — `xcrun --show-sdk-path` selects the
+ * iPhoneOS/iPhoneSimulator SDK; compiles add `-isysroot `
+ * plus `-isystem /usr/include` (zig's driver manages libc
+ * header search itself and would otherwise find no headers).
+ * Android any host with an NDK — ANDROID_NDK_ROOT/ANDROID_NDK_HOME, or
+ * the newest ndk/ under ANDROID_HOME/ANDROID_SDK_ROOT
+ * or the platform-default SDK location; compiles add the NDK
+ * sysroot's generic and per-triple include directories.
+ *
+ * Library archives never link, so the sysroot's LIBRARIES are the
+ * embedder's side of the contract: Xcode links iOS archives against the
+ * selected SDK, and Gradle/NDK builds link Android archives against the
+ * API-26+ bionic stubs. */
+export const IPHONEOS_MIN_VERSION = "15.0";
+export const ANDROID_MIN_API = 26;
+
+const MOBILE_LIBRARY_TARGETS = [
+ "aarch64-apple-ios",
+ "aarch64-apple-ios-simulator",
+ "aarch64-linux-android",
+] as const;
+
+export function isIosTarget(target: string | null): boolean {
+ return target === "aarch64-apple-ios" || target === "aarch64-apple-ios-simulator";
+}
+
+export function isAndroidTarget(target: string | null): boolean {
+ return target === "aarch64-linux-android";
+}
+
+export function isMobileTarget(target: string | null): boolean {
+ return isIosTarget(target) || isAndroidTarget(target);
+}
+
+/** The canonical mobile triple SCRIPTC_TARGET selects, or null when the
+ * environment names none. Pure string inspection — safe to consult before
+ * any toolchain discovery runs. */
+export function mobileLibraryTarget(env: NodeJS.ProcessEnv = process.env): string | null {
+ const target = env["SCRIPTC_TARGET"] ?? "";
+ return isMobileTarget(target) ? target : null;
+}
+
+/** The admission verdict for a mobile-family triple: null when the spelling
+ * and host pairing are supported, otherwise the refusal text (the same text
+ * resolveCc throws and compileLibrary reports as SC3002). Pure string/host
+ * inspection — no discovery, no subprocess. */
+export function mobileTargetRefusal(
+ target: string,
+ hostPlatform: NodeJS.Platform = process.platform,
+): string | null {
+ if (isIosTarget(target)) {
+ return hostPlatform === "darwin"
+ ? null
+ : `${target} library archives build on macOS hosts only (the Apple iOS SDK sysroot and Mach-O symbol localization live there); this host is ${hostPlatform}`;
+ }
+ if (isAndroidTarget(target)) return null;
+ // A near-miss mobile spelling must refuse with the supported set named,
+ // never reach zig with no sysroot wired (the compile would fail on the
+ // first libc header) or produce an artifact for an unverified device
+ // class.
+ if (/(?:^|-)(?:ios|tvos|watchos|visionos|android)/.test(target)) {
+ return `unsupported mobile target '${target}' (supported: ${MOBILE_LIBRARY_TARGETS.join(", ")})`;
+ }
+ return null;
+}
+
+/** The Apple SDK root for one mobile platform, discovered through xcrun the
+ * way Xcode's own build system selects it. Memoized per SDK name and
+ * selection environment: production rediscovers per process, and the two
+ * selection variables (DEVELOPER_DIR/SDKROOT) are already mutable-input
+ * keys that disable persistent caching. */
+const appleSdkMemos = new Map();
+function appleSdkRoot(sdk: "iphoneos" | "iphonesimulator", env: NodeJS.ProcessEnv): string {
+ const key = [sdk, env["PATH"] ?? "", env["DEVELOPER_DIR"] ?? "", env["SDKROOT"] ?? ""].join("\0");
+ const memo = appleSdkMemos.get(key);
+ if (memo !== undefined) return memo;
+ const probe = spawnSync("xcrun", ["--sdk", sdk, "--show-sdk-path"], {
+ encoding: "utf8",
+ env,
+ });
+ const path = probe.status === 0 ? (probe.stdout ?? "").trim() : "";
+ if (path === "" || !existsSync(join(path, "usr", "include"))) {
+ throw new Error(
+ `the ${sdk} SDK was not found (xcrun --sdk ${sdk} --show-sdk-path failed) — ` +
+ `iOS targets need Xcode with the ${sdk === "iphoneos" ? "iPhoneOS" : "iPhoneSimulator"} SDK installed`,
+ );
+ }
+ appleSdkMemos.set(key, path);
+ return path;
+}
+
+/** Compare dotted-numeric NDK version directory names, newest first. */
+function compareNdkVersionsDesc(a: string, b: string): number {
+ const as = a.split(".").map((s) => Number.parseInt(s, 10));
+ const bs = b.split(".").map((s) => Number.parseInt(s, 10));
+ for (let i = 0; i < Math.max(as.length, bs.length); i++) {
+ const d = (bs[i] ?? 0) - (as[i] ?? 0);
+ if (d !== 0 && Number.isFinite(d)) return d;
+ }
+ return a < b ? 1 : a > b ? -1 : 0;
+}
+
+/** The Android NDK sysroot for the selected environment: an explicit
+ * ANDROID_NDK_ROOT/ANDROID_NDK_HOME wins; otherwise the newest ndk/
+ * under ANDROID_HOME, ANDROID_SDK_ROOT, or the platform-default SDK
+ * location. The prebuilt host directory is discovered rather than guessed —
+ * the NDK ships exactly one per host OS. Memoized per selection
+ * environment. */
+const ndkSysrootMemos = new Map();
+function androidNdkSysroot(env: NodeJS.ProcessEnv): string {
+ const key = ["ANDROID_NDK_ROOT", "ANDROID_NDK_HOME", "ANDROID_HOME", "ANDROID_SDK_ROOT"]
+ .map((name) => env[name] ?? "")
+ .join("\0");
+ const memo = ndkSysrootMemos.get(key);
+ if (memo !== undefined) return memo;
+ const ndkRoots: string[] = [];
+ const explicit = [env["ANDROID_NDK_ROOT"], env["ANDROID_NDK_HOME"]]
+ .find((root): root is string => root !== undefined && root !== "");
+ if (explicit !== undefined) {
+ ndkRoots.push(explicit);
+ } else {
+ const sdkRoots = [
+ env["ANDROID_HOME"],
+ env["ANDROID_SDK_ROOT"],
+ process.platform === "darwin"
+ ? join(homedir(), "Library", "Android", "sdk")
+ : process.platform === "win32"
+ ? join(env["LOCALAPPDATA"] ?? join(homedir(), "AppData", "Local"), "Android", "Sdk")
+ : join(homedir(), "Android", "Sdk"),
+ ].filter((root): root is string => root !== undefined && root !== "");
+ for (const root of sdkRoots) {
+ let versions: string[] = [];
+ try {
+ versions = readdirSync(join(root, "ndk")).filter((name) => /^\d/.test(name));
+ } catch {
+ continue;
+ }
+ versions.sort(compareNdkVersionsDesc);
+ ndkRoots.push(...versions.map((version) => join(root, "ndk", version)));
+ }
+ }
+ for (const ndk of ndkRoots) {
+ const prebuilt = join(ndk, "toolchains", "llvm", "prebuilt");
+ let hosts: string[] = [];
+ try {
+ hosts = readdirSync(prebuilt).sort();
+ } catch {
+ continue;
+ }
+ for (const host of hosts) {
+ const sysroot = join(prebuilt, host, "sysroot");
+ if (existsSync(join(sysroot, "usr", "include", "aarch64-linux-android"))) {
+ ndkSysrootMemos.set(key, sysroot);
+ return sysroot;
+ }
+ }
+ }
+ throw new Error(
+ "no Android NDK sysroot was found — install an NDK (sdkmanager 'ndk;') and/or set " +
+ "ANDROID_NDK_ROOT to it (ANDROID_HOME with an ndk/ directory also works). " +
+ "aarch64-linux-android compiles against the NDK's bionic headers.",
+ );
+}
+
/** Resolve native platform flags independently of the machine running tests,
* so the host-Linux contract remains pinned on every development host. */
function nativePlatformArgs(platform: NodeJS.Platform): Pick {
@@ -459,21 +654,68 @@ export function resolveCc(
`SCRIPTC_TARGET=${target} requires SCRIPTC_CC=zigcc — the default clang path has no cross-target sysroots.`,
);
}
- return { argv: ["clang"], target: null, ...hostArgs };
+ return { argv: ["clang"], target: null, zigTarget: null, ...hostArgs };
}
if (cc !== "zigcc") {
throw new Error(`unknown SCRIPTC_CC '${cc}' (supported: clang, zigcc)`);
}
- if (target === "") return { argv: ["zig", "cc"], target: null, ...hostArgs };
+ if (target === "") return { argv: ["zig", "cc"], target: null, zigTarget: null, ...hostArgs };
if (target.includes("wasi") && target !== "wasm32-wasi") {
throw new Error(`unsupported WASI target '${target}' (supported: wasm32-wasi)`);
}
+ const mobileRefusal = mobileTargetRefusal(target, hostPlatform);
+ if (mobileRefusal !== null) throw new Error(mobileRefusal);
+ if (isIosTarget(target)) {
+ // Library-mode-only target (compile()/compileC own the executable-lane
+ // refusal). Zig bundles no Apple libc: the compile rides the selected
+ // SDK sysroot, with the libc header directory spelled explicitly
+ // because zig's driver manages libc search itself and consults no
+ // -isysroot for it. The zig spelling pins the iOS 15.0 floor into
+ // every object's LC_BUILD_VERSION minos.
+ const simulator = target === "aarch64-apple-ios-simulator";
+ const sdk = appleSdkRoot(simulator ? "iphonesimulator" : "iphoneos", env);
+ const zigTarget = `aarch64-ios.${IPHONEOS_MIN_VERSION}${simulator ? "-simulator" : ""}`;
+ return {
+ argv: ["zig", "cc"],
+ target,
+ zigTarget,
+ targetArgs: ["-target", zigTarget, "-isysroot", sdk, "-isystem", join(sdk, "usr", "include")],
+ linkArgs: [],
+ };
+ }
+ if (isAndroidTarget(target)) {
+ // Library-mode-only target. Zig bundles no bionic: compiles ride the
+ // NDK sysroot's generic and per-triple include directories. Bionic
+ // supports _GNU_SOURCE like glibc (and hides some POSIX declarations
+ // without it); the zig spelling pins the API 26 floor, which the NDK's
+ // versioned stub libraries enforce at the embedder's link. API 26
+ // bionic carries everything the library-lane units call (arc4random_buf
+ // included), so no shim TU joins the archive.
+ const sysroot = androidNdkSysroot(env);
+ const zigTarget = `aarch64-linux-android.${ANDROID_MIN_API}`;
+ return {
+ argv: ["zig", "cc"],
+ target,
+ zigTarget,
+ targetArgs: [
+ "-target",
+ zigTarget,
+ "-D_GNU_SOURCE",
+ "-isystem",
+ join(sysroot, "usr", "include"),
+ "-isystem",
+ join(sysroot, "usr", "include", "aarch64-linux-android"),
+ ],
+ linkArgs: ["-lm"],
+ };
+ }
const linux = target.includes("linux");
const wasi = target.includes("wasi");
const musl = target.includes("linux-musl");
return {
argv: ["zig", "cc"],
target,
+ zigTarget: target,
targetArgs: [
"-target",
target,
@@ -504,6 +746,10 @@ export function isMuslTarget(driver: Pick): boolean {
export function targetPlatform(driver: CcDriver): string {
if (driver.target === null) return process.platform;
if (driver.target.includes("wasi")) return "wasi";
+ // iOS is a darwin-family target: Mach-O objects, ld64 localization,
+ // POSIX path/EOL semantics. Android falls to the linux arm below —
+ // bionic is a linux libc and its archives are ordinary ELF.
+ if (isIosTarget(driver.target)) return "darwin";
if (driver.target.includes("linux")) return "linux";
if (driver.target.includes("windows")) return "win32";
return driver.target.includes("macos") || driver.target.includes("darwin") ? "darwin" : "other";
@@ -1136,8 +1382,9 @@ export interface LibArchiveOptions {
* sanitizer ABI in instrumented builds) keep their global binding. Windows
* embedders additionally link advapi32, iphlpapi, and ws2_32. Omitted = the
* classic archive, byte-for-byte. Admitted for darwin/linux/win32 native
- * hosts, linux and windows cross triples from any host, and macos cross
- * triples from a darwin host (compileLibrary owns the refusal fence). */
+ * hosts, linux/android/windows cross triples from any host, and macos/ios
+ * cross triples from a darwin host (compileLibrary owns the refusal
+ * fence). */
localizeSymbols?: readonly string[];
/** Thread-instanced state (the profile's abi.instance_per_thread): every
* TU of the archive compiles with -DSCR_THREAD_INSTANCES, moving the
@@ -1583,9 +1830,12 @@ export async function compileLibArchive(opts: LibArchiveOptions): Promise
* private extern, and -r without -keep_private_externs writes
* private externs out as non-external symbols. Apple ASan's
* image-registration COMMON remains shared so the final Mach-O
- * image registers its globals once. ld64 reads every macOS
- * architecture, so darwin-host macos cross triples ride the
- * same arm; compileLibrary refuses macos targets elsewhere.
+ * image registers its globals once. ld64 reads every Apple
+ * platform's objects — macOS architectures and the iOS/
+ * iOS-simulator triples alike (LC_BUILD_VERSION platform and
+ * minos survive the merge) — so darwin-host macos AND ios
+ * targets ride the same arm; compileLibrary refuses those
+ * targets elsewhere.
* ELF, native linux host — ld -r merges with --force-group-allocation
* (ASan's instrumented globals ride ELF section groups whose
* signatures repeat across archives sharing runtime objects;
@@ -1663,11 +1913,13 @@ async function localizeLibraryObjects(
// Cross ELF: the cross driver's own lld performs the relocatable merge
// (with the staging archive's member semantics); demotion and section-
// group resolution happen in process. -nostdlib keeps zig from feeding
- // libc/compiler-rt inputs into the merge.
+ // libc/compiler-rt inputs into the merge. Android rides this arm
+ // unchanged: bionic archives are ordinary aarch64 ELF64, and the merge
+ // uses the driver's zig spelling (which pins the API floor).
await run([
driver.argv[0] ?? "zig",
...driver.argv.slice(1),
- "-target", driver.target!,
+ "-target", driver.zigTarget ?? driver.target!,
"-nostdlib",
"-r", programObject, staging,
"-o", combined,
@@ -3103,6 +3355,16 @@ export async function compileC(opts: CcOptions): Promise {
const http = (opts.http ?? false) || nativeFetch || netIsland;
const tls = (opts.tls ?? false) || nativeFetch || netIsland;
const driver = resolveCc();
+ // Mobile triples produce library archives, never standalone executables:
+ // the executable-lane runtime (event loop, sockets, child processes) is
+ // not verified on those device classes. compile() reports the SC3002
+ // diagnostic first; this is the backstop for direct compileC callers.
+ if (isMobileTarget(driver.target)) {
+ throw new Error(
+ `SCRIPTC_TARGET=${driver.target} builds library-mode static archives only — ` +
+ `compile with a library profile (SCRIPTC_CC=zigcc scriptc build --lib --profile ) and link the archive from the app project.`,
+ );
+ }
const runtimeSources = targetPlatform(driver) === "wasi"
? RUNTIME_SOURCES.filter((source) => source !== "scr_child.c")
: RUNTIME_SOURCES;
diff --git a/packages/compiler/src/coverage/surface-manifest.ts b/packages/compiler/src/coverage/surface-manifest.ts
index 73841d83d6..0291c060d2 100644
--- a/packages/compiler/src/coverage/surface-manifest.ts
+++ b/packages/compiler/src/coverage/surface-manifest.ts
@@ -93,6 +93,7 @@ const COVERAGE_NOTES: string[] = [
`The engine-free fetch projection targets Node ${NODE24_FETCH_COMPAT_PROFILE.target.node} with bundled Undici ${NODE24_FETCH_COMPAT_PROFILE.target.undici}. Each projected row names the differential evidence that guards it; changing the pinned Node or Undici version is an explicit profile update.`,
"The fetch profile also contains a runtime-reflected census of the selected fetch, abort, Headers, and readable-stream interfaces plus RequestInit/ResponseInit dictionary reads. Static, dynamic-only, and unsupported census rows are projected here; its explicitly out-of-scope metadata rows and adjacent-interface exclusions remain in the profile so absence is deliberate rather than ambiguous.",
"Process-level diagnostic codes are not surface entries: SC0001-SC0004 are preflight gates, SC1110 is a comptime evaluation failure, SC3001/SC3002 are backend/target tier refusals, SC9001/SC9002 are internal errors.",
+ "Entry statuses are projected for the desktop targets. The mobile targets (aarch64-apple-ios, aarch64-apple-ios-simulator, aarch64-linux-android) compile library-mode archives only: the library-admissible surface (what SC4005's async_free requirement and the library link set admit) is supported there, the executable lane refuses those triples with SC3002, and no entry outside the library-admissible surface carries a mobile support claim. iOS archives build for iOS 15.0 on darwin hosts; Android archives build against NDK API level 26.",
"No scheduling metadata is published; entry ids are the stable diff keys across releases.",
];
diff --git a/packages/compiler/src/index.ts b/packages/compiler/src/index.ts
index b39affd11e..85058839cd 100644
--- a/packages/compiler/src/index.ts
+++ b/packages/compiler/src/index.ts
@@ -1,6 +1,6 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
-import { CcCompileError, compileC, compileLibArchive, resolveCc, targetPlatform } from "./backend/cc.js";
+import { CcCompileError, compileC, compileLibArchive, mobileLibraryTarget, mobileTargetRefusal, resolveCc, targetPlatform } from "./backend/cc.js";
import { emitModule } from "./backend/emission/emitter.js";
import { emitLlvmModule, LlvmUnsupportedError } from "./backend/llvm/emitter.js";
import { checkerPanicDiag, ffiNativeBuildDiag, libAsyncExportDiag, libAsyncSurfaceDiag, libExportUnresolvedDiag, libGenericExportDiag, libIntBoundaryDiag, libNpmIneligibleDiag, libSidecarDiag, libUnmappableSignatureDiag, iceDiag, isCheckerPanic, LIB_INBOUND_BYTES_TRAP_CODE, LIB_RUNTIME_TRAP_CODES, type ScrDiagnostic } from "./diagnostics/diagnostic.js";
@@ -36,6 +36,7 @@ import { loadFfiProfile, type FfiProfile } from "./ffi/profile.js";
export const VERSION = "0.0.1";
export { compileC, runtimeSrcDir, type CcOptions } from "./backend/cc.js";
+export { ANDROID_MIN_API, IPHONEOS_MIN_VERSION, isAndroidTarget, isIosTarget, isMobileTarget, mobileLibraryTarget, mobileTargetRefusal } from "./backend/cc.js";
export { emitModule } from "./backend/emission/emitter.js";
export type { ScrDiagnostic } from "./diagnostics/diagnostic.js";
export { renderAll, renderDiagnostic } from "./diagnostics/render.js";
@@ -834,6 +835,36 @@ export async function compile(entryPath: string, opts: CompileOptions): Promise<
ffi = loaded.profile;
}
const buildPlatform = buildTargetPlatform();
+ // Mobile triples are library-mode targets: the archive an embedding app
+ // links is the artifact, and only the library-admissible runtime surface
+ // is verified on those device classes. The executable lane refuses before
+ // any frontend work — a pure env check, so the refusal needs no toolchain.
+ {
+ const entryLoc: SrcLoc = { file: entryPath, start: 0, end: 0 };
+ const mobileTarget = mobileLibraryTarget();
+ if (mobileTarget !== null) {
+ return {
+ ok: false,
+ diagnostics: [
+ targetRefusalDiag(
+ mobileTarget,
+ "standalone executable builds — mobile targets produce library-mode static archives (SCRIPTC_CC=zigcc scriptc build --lib --profile ) for an embedding app to link",
+ entryLoc,
+ ),
+ ],
+ sourceTexts: new Map(),
+ };
+ }
+ const rawTarget = process.env["SCRIPTC_TARGET"] ?? "";
+ const mobileRefusal = mobileTargetRefusal(rawTarget);
+ if (mobileRefusal !== null) {
+ return {
+ ok: false,
+ diagnostics: [{ code: "SC3002", message: mobileRefusal, loc: entryLoc }],
+ sourceTexts: new Map(),
+ };
+ }
+ }
const fe = runFrontend(entryPath, opts.npmStatic);
let lowered: LowerResult;
let entryText: string;
@@ -1455,14 +1486,35 @@ export async function compileLibrary(opts: CompileLibraryOptions): Promise {
expect(() => resolveCc({ SCRIPTC_CC: "zigcc", SCRIPTC_TARGET: "wasm64-wasi" })).toThrow(/supported: wasm32-wasi/);
});
+test("an empty ANDROID_NDK_ROOT does not mask ANDROID_NDK_HOME", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "scr-android-ndk-home-"));
+ const home = join(dir, "ndk-home");
+ const sysroot = join(home, "toolchains", "llvm", "prebuilt", "test-host", "sysroot");
+ await mkdir(join(sysroot, "usr", "include", "aarch64-linux-android"), { recursive: true });
+
+ const driver = resolveCc({
+ SCRIPTC_CC: "zigcc",
+ SCRIPTC_TARGET: "aarch64-linux-android",
+ ANDROID_NDK_ROOT: "",
+ ANDROID_NDK_HOME: home,
+ });
+ expect(driver.targetArgs).toContain(join(sysroot, "usr", "include"));
+});
+
+test.skipIf(process.platform === "win32")("iOS SDK discovery uses the resolver's explicit environment", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "scr-ios-sdk-env-"));
+ const bin = join(dir, "bin");
+ const sdk = join(dir, "Custom.sdk");
+ await mkdir(bin);
+ await mkdir(join(sdk, "usr", "include"), { recursive: true });
+ const xcrun = join(bin, "xcrun");
+ await writeFile(xcrun, '#!/bin/sh\nprintf "%s\\n" "$SCRIPTC_TEST_SDK_PATH"\n');
+ await chmod(xcrun, 0o755);
+
+ const driver = resolveCc({
+ PATH: bin,
+ SCRIPTC_CC: "zigcc",
+ SCRIPTC_TARGET: "aarch64-apple-ios",
+ DEVELOPER_DIR: join(dir, "CustomXcode.app", "Contents", "Developer"),
+ SCRIPTC_TEST_SDK_PATH: sdk,
+ }, "darwin");
+ expect(driver.targetArgs).toContain(sdk);
+});
+
test("zigcc resolves to `zig cc`; linux triples add their libc target flags", () => {
const native = resolveCc({ SCRIPTC_CC: "zigcc" }, "darwin");
expect(native.argv).toEqual(["zig", "cc"]);
diff --git a/tests/harness/library-multi.test.ts b/tests/harness/library-multi.test.ts
index 9d976d8679..0254acc930 100644
--- a/tests/harness/library-multi.test.ts
+++ b/tests/harness/library-multi.test.ts
@@ -75,16 +75,44 @@
* box (SCRIPTC_WIN=1) — including the M7-style
* thread-instanced+localized composition there
*
+ * Mobile library targets (aarch64-apple-ios, aarch64-apple-ios-simulator,
+ * aarch64-linux-android — library-mode-only triples):
+ *
+ * M12 admission always-run refusal shape: an iOS triple off a
+ * darwin host refuses SC3002 before any toolchain
+ * runs; near-miss mobile spellings refuse with the
+ * supported set named; the executable lane refuses
+ * mobile triples with the pointer to --lib
+ * M13 iOS SCRIPTC_IOS=1 (darwin host, Xcode with the
+ * iPhoneOS + iPhoneSimulator SDKs, zig): localized
+ * a/b archives build per target and emission with
+ * M1's symbol exactness, the ambient audit, and the
+ * iOS 15.0 LC_BUILD_VERSION floor; simulator probes
+ * EXECUTE on a booted simulator (simctl spawn) —
+ * the M2 two-instance acceptance run and the M6
+ * four-thread instancing run, byte-for-byte against
+ * the desktop expectations; device-arch archives
+ * are build+link verified (no device to execute)
+ * M14 Android SCRIPTC_ANDROID=1 (an NDK plus adb/emulator):
+ * localized a/b archives build per emission with
+ * the same symbol/audit bars, probes link with the
+ * NDK's API-26 clang, and EXECUTE on an emulator
+ * (a running device is reused; otherwise a headless
+ * arm64 AVD is created and booted) — the M2 and M6
+ * acceptance runs, byte-for-byte
+ *
* Windows hosts run M1/M2/M6/M7 natively through the same gates as darwin
* and linux: probes compile with `zig cc` (the box's toolchain), archives
* carry CRLF-normalized probe output (the mingw CRT's text-mode stdout),
* and symbol checks ride llvm-nm when plain nm is absent.
*/
-import { execFileSync, spawnSync } from "node:child_process";
-import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { execFileSync, spawn, spawnSync } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
import { delimiter, join } from "node:path";
-import { describe, expect, test } from "vitest";
-import { compileLibrary, loadLibraryProfile } from "@scriptc/compiler";
+import { afterAll, describe, expect, test } from "vitest";
+import { compile, compileLibrary, IPHONEOS_MIN_VERSION, ANDROID_MIN_API, loadLibraryProfile } from "@scriptc/compiler";
const repoRoot = join(import.meta.dirname, "../..");
const fixtureDir = join(repoRoot, "tests/library-mode/multi");
@@ -718,7 +746,7 @@ type CrossTarget = (typeof CROSS_TARGETS)[number];
function buildInstanceCross(
instance: "a" | "b",
emission: Emission,
- target: CrossTarget,
+ target: CrossTarget | MobileTarget,
): Promise {
const key = `x-${instance}-${emission}-${target}`;
let archive = built.get(key);
@@ -952,3 +980,800 @@ describe.skipIf(!crossOn)("cross-target localization", () => {
);
});
});
+
+/* ── M12–M14: mobile library targets ──────────────────────────────────────
+ * M12 runs everywhere (pure admission shape, no toolchain). The executed
+ * lanes are env-gated like M10/M11: SCRIPTC_IOS=1 needs a darwin host with
+ * Xcode's iPhoneOS/iPhoneSimulator SDKs, zig, and a bootable simulator;
+ * SCRIPTC_ANDROID=1 needs an NDK plus adb (a running emulator/device is
+ * reused; otherwise a headless arm64 AVD is created and booted). Mobile
+ * builds are plain-flavor: the sanitized lanes stay host contracts. */
+
+const MOBILE_TARGETS = [
+ "aarch64-apple-ios",
+ "aarch64-apple-ios-simulator",
+ "aarch64-linux-android",
+] as const;
+type MobileTarget = (typeof MOBILE_TARGETS)[number];
+
+const iosOn = process.env["SCRIPTC_IOS"] === "1";
+const androidOn = process.env["SCRIPTC_ANDROID"] === "1";
+
+/** Run a fixture build with SCRIPTC_CC/SCRIPTC_TARGET threaded through the
+ * env the cc driver reads (the buildInstanceCross pattern, for arbitrary
+ * fixture profiles). */
+async function withMobileTarget(target: string, body: () => Promise): Promise {
+ const prevCc = process.env["SCRIPTC_CC"];
+ const prevTarget = process.env["SCRIPTC_TARGET"];
+ process.env["SCRIPTC_CC"] = "zigcc";
+ process.env["SCRIPTC_TARGET"] = target;
+ try {
+ return await body();
+ } finally {
+ if (prevCc === undefined) delete process.env["SCRIPTC_CC"];
+ else process.env["SCRIPTC_CC"] = prevCc;
+ if (prevTarget === undefined) delete process.env["SCRIPTC_TARGET"];
+ else process.env["SCRIPTC_TARGET"] = prevTarget;
+ }
+}
+
+/* ── M12: admission (always runs — no toolchain, no SDKs) ────────────────── */
+
+test("M12: an iOS target refuses library builds off a darwin host with SC3002", async () => {
+ const outDir = join(cacheDir, "mobile-host-refusal");
+ mkdirSync(outDir, { recursive: true });
+ const profile = JSON.parse(readFileSync(join(fixtureDir, "profile_a.json"), "utf8")) as {
+ entry: string;
+ };
+ profile.entry = join(fixtureDir, profile.entry);
+ const profilePath = join(outDir, "profile.json");
+ writeFileSync(profilePath, JSON.stringify(profile, null, 2));
+ // The refusal is a pure env/host check that fires before any toolchain
+ // discovery, so neither zig nor an SDK need exist here.
+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform")!;
+ Object.defineProperty(process, "platform", { ...platformDescriptor, value: "linux" });
+ try {
+ await withMobileTarget("aarch64-apple-ios", async () => {
+ const result = await compileLibrary({ profilePath, outDir });
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.diagnostics[0]!.code).toBe("SC3002");
+ expect(result.diagnostics[0]!.message).toContain("aarch64-apple-ios");
+ expect(result.diagnostics[0]!.message).toContain("macOS hosts");
+ }
+ });
+ } finally {
+ Object.defineProperty(process, "platform", platformDescriptor);
+ }
+});
+
+test.each(["aarch64-ios", "x86_64-linux-android", "armv7-linux-androideabi"])(
+ "M12: near-miss mobile triple %s refuses with the supported set named",
+ async (target) => {
+ const outDir = join(cacheDir, `mobile-spelling-refusal-${target}`);
+ mkdirSync(outDir, { recursive: true });
+ const profile = JSON.parse(readFileSync(join(fixtureDir, "profile_a.json"), "utf8")) as {
+ entry: string;
+ };
+ profile.entry = join(fixtureDir, profile.entry);
+ const profilePath = join(outDir, "profile.json");
+ writeFileSync(profilePath, JSON.stringify(profile, null, 2));
+ await withMobileTarget(target, async () => {
+ const result = await compileLibrary({ profilePath, outDir });
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.diagnostics[0]!.code).toBe("SC3002");
+ expect(result.diagnostics[0]!.message).toContain(target);
+ for (const supported of MOBILE_TARGETS) {
+ expect(result.diagnostics[0]!.message).toContain(supported);
+ }
+ }
+ });
+ },
+);
+
+test.each(MOBILE_TARGETS)(
+ "M12: the executable lane refuses %s with the pointer to --lib",
+ async (target) => {
+ const outDir = join(cacheDir, `mobile-exe-refusal-${target}`);
+ mkdirSync(outDir, { recursive: true });
+ const entry = join(outDir, "main.ts");
+ writeFileSync(entry, 'console.log("hi");\n');
+ await withMobileTarget(target, async () => {
+ const result = await compile(entry, { outDir, outPath: join(outDir, "main") });
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.diagnostics[0]!.code).toBe("SC3002");
+ expect(result.diagnostics[0]!.message).toContain(target);
+ expect(result.diagnostics[0]!.message).toContain("SCRIPTC_CC=zigcc scriptc build --lib --profile ");
+ }
+ });
+ },
+);
+
+test.each([
+ ["arm64-v8a,armeabi-v7a", "26", true],
+ ["arm64-v8a", "35", true],
+ ["x86_64,x86", "35", false],
+ ["arm64-v8a", "25", false],
+ ["arm64-v8a", "not-an-api", false],
+] as const)(
+ "M12: Android device compatibility filters ABI %s at API %s",
+ (abiList, sdkLevel, expected) => {
+ expect(isCompatibleAndroidDevice(abiList, sdkLevel)).toBe(expected);
+ },
+);
+
+test("M12: Android emulator port claims skip live serials and do not collide", () => {
+ let first: AndroidPortClaim | null = null;
+ let second: AndroidPortClaim | null = null;
+ try {
+ first = claimAndroidLanePort([`emulator-${ANDROID_PORT_MIN}`]);
+ second = claimAndroidLanePort([`emulator-${ANDROID_PORT_MIN}`]);
+ expect(first.port).not.toBe(ANDROID_PORT_MIN);
+ expect(second.port).not.toBe(ANDROID_PORT_MIN);
+ expect(second.port).not.toBe(first.port);
+ } finally {
+ if (second !== null) releaseAndroidLanePort(second);
+ if (first !== null) releaseAndroidLanePort(first);
+ }
+});
+
+/* ── M13: iOS (SCRIPTC_IOS=1) ─────────────────────────────────────────────── */
+
+const APPLE_MOBILE_TARGETS = ["aarch64-apple-ios", "aarch64-apple-ios-simulator"] as const;
+
+function appleSdkName(target: string): "iphoneos" | "iphonesimulator" {
+ return target === "aarch64-apple-ios" ? "iphoneos" : "iphonesimulator";
+}
+
+/** Link a probe against iOS archives with the host Xcode clang — exactly
+ * what an embedder's Xcode build performs. Link success asserts every
+ * undefined in the localized member resolves against the selected SDK. */
+function buildAppleProbe(archives: string[], source: string, tag: string, target: string): string {
+ const outDir = join(cacheDir, "probes");
+ mkdirSync(outDir, { recursive: true });
+ const bin = join(outDir, `probe-${tag}`);
+ const clangTarget = `arm64-apple-ios${IPHONEOS_MIN_VERSION}${target === "aarch64-apple-ios" ? "" : "-simulator"}`;
+ execFileSync("xcrun", [
+ "--sdk", appleSdkName(target),
+ "clang",
+ "-std=c11",
+ "-pthread",
+ "-target", clangTarget,
+ source,
+ ...archives,
+ "-lm",
+ "-o", bin,
+ ]);
+ return bin;
+}
+
+/** The booted simulator the execution legs share: an already-booted device
+ * is reused; otherwise the first available iPhone boots headlessly and the
+ * suite shuts it down again. */
+let bootedSimulator: { udid: string; bootedByUs: boolean } | null = null;
+type SimulatorDevice = { udid: string; state: string; name: string };
+type SimulatorListing = { devices: Record };
+
+function availableIphoneSimulators(listing: SimulatorListing): SimulatorDevice[] {
+ return Object.entries(listing.devices)
+ .filter(([runtime]) => runtime.includes(".SimRuntime.iOS-"))
+ .flatMap(([, devices]) => devices)
+ .filter((device) => device.name.startsWith("iPhone"));
+}
+
+test("M12: simulator reuse ignores booted devices from non-iOS runtimes", () => {
+ const devices = availableIphoneSimulators({
+ devices: {
+ "com.apple.CoreSimulator.SimRuntime.tvOS-26-0": [
+ { udid: "tv", state: "Booted", name: "Apple TV" },
+ ],
+ "com.apple.CoreSimulator.SimRuntime.iOS-26-0": [
+ { udid: "phone", state: "Shutdown", name: "iPhone 17" },
+ { udid: "tablet", state: "Booted", name: "iPad Pro" },
+ ],
+ },
+ });
+ expect(devices.map((device) => device.udid)).toEqual(["phone"]);
+});
+
+function shutdownOwnedSimulator(): void {
+ if (bootedSimulator?.bootedByUs !== true) return;
+ const owned = bootedSimulator;
+ bootedSimulator = null;
+ try {
+ execFileSync("xcrun", ["simctl", "shutdown", owned.udid]);
+ } catch {
+ /* shutdown is best-effort — never mask a real failure */
+ }
+}
+
+function ensureBootedSimulator(): string {
+ if (bootedSimulator !== null) return bootedSimulator.udid;
+ const listing = JSON.parse(
+ execFileSync("xcrun", ["simctl", "list", "devices", "available", "--json"], { encoding: "utf8" }),
+ ) as SimulatorListing;
+ const devices = availableIphoneSimulators(listing);
+ const booted = devices.find((device) => device.state === "Booted");
+ if (booted !== undefined) {
+ bootedSimulator = { udid: booted.udid, bootedByUs: false };
+ return booted.udid;
+ }
+ const candidate = devices[0];
+ if (candidate === undefined) {
+ throw new Error("SCRIPTC_IOS=1 needs at least one available simulator (xcrun simctl list devices available).");
+ }
+ execFileSync("xcrun", ["simctl", "boot", candidate.udid]);
+ bootedSimulator = { udid: candidate.udid, bootedByUs: true };
+ try {
+ execFileSync("xcrun", ["simctl", "bootstatus", candidate.udid, "-b"], { timeout: 300_000 });
+ } catch (err) {
+ shutdownOwnedSimulator();
+ throw err;
+ }
+ return candidate.udid;
+}
+
+describe.skipIf(!iosOn)("mobile targets: iOS (SCRIPTC_IOS=1)", () => {
+ afterAll(() => {
+ shutdownOwnedSimulator();
+ });
+
+ test("the iOS toolchain is present", () => {
+ // Fail, never skip: SCRIPTC_IOS=1 promises an iOS verdict.
+ for (const sdk of ["iphoneos", "iphonesimulator"] as const) {
+ const path = execFileSync("xcrun", ["--sdk", sdk, "--show-sdk-path"], { encoding: "utf8" }).trim();
+ expect(path, `xcrun --sdk ${sdk} --show-sdk-path`).not.toBe("");
+ }
+ execFileSync("zig", ["version"], { encoding: "utf8" });
+ });
+
+ describe.each(APPLE_MOBILE_TARGETS)("target %s", (target) => {
+ describe.each(EMISSIONS)("%s emission", (emission) => {
+ test("M13: localized archives build; symbols exact, ambient audit holds, iOS 15.0 floor stamped, probe links", async (ctx) => {
+ if (nmTool === null) ctx.skip("no nm on PATH for the symbol-exactness check");
+ const archiveA = await buildInstanceCross("a", emission, target);
+ const archiveB = await buildInstanceCross("b", emission, target);
+ for (const [archive, declared] of [
+ [archiveA, A_SYMBOLS],
+ [archiveB, B_SYMBOLS],
+ ] as const) {
+ const { defined, undef } = nmSymbols(archive);
+ expect([...defined].sort()).toEqual([...declared].sort());
+ expect([...undef].filter((s) => s.startsWith("scr_") || s.startsWith("ma_") || s.startsWith("mb_"))).toEqual([]);
+ for (const banned of ["sigaction", "signal", "pthread_create", "atexit", "setvbuf"]) {
+ expect(undef.has(banned), `undefined reference to ${banned}`).toBe(false);
+ }
+ // The version floor is part of the target contract: every member
+ // carries LC_BUILD_VERSION with the device (2) or simulator (7)
+ // platform and minos 15.0.
+ const loadCommands = execFileSync("otool", ["-l", archive], { encoding: "utf8" });
+ expect(loadCommands).toContain("LC_BUILD_VERSION");
+ expect(loadCommands).toContain(`minos ${IPHONEOS_MIN_VERSION}`);
+ expect(loadCommands).toContain(`platform ${target === "aarch64-apple-ios" ? "2" : "7"}`);
+ }
+ buildAppleProbe([archiveA, archiveB], join(fixtureDir, "probe.c"), `ios-${emission}-${target}`, target);
+ }, 240_000);
+ });
+ });
+
+ describe("M13 simulator execution", () => {
+ test.for(EMISSIONS)(
+ "the two-instance probe runs on a booted simulator (%s emission)",
+ async (emission) => {
+ const target = "aarch64-apple-ios-simulator";
+ const archiveA = await buildInstanceCross("a", emission, target);
+ const archiveB = await buildInstanceCross("b", emission, target);
+ const probe = buildAppleProbe(
+ [archiveA, archiveB],
+ join(fixtureDir, "probe.c"),
+ `ios-run-${emission}`,
+ target,
+ );
+ const udid = ensureBootedSimulator();
+ const out = execFileSync("xcrun", ["simctl", "spawn", udid, probe], {
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ expect(out).toBe(PROBE_EXPECTED);
+ },
+ 600_000,
+ );
+
+ test("a thread-instanced and runtime-localized archive runs on the simulator", async () => {
+ const target = "aarch64-apple-ios-simulator";
+ const key = `ios-t-llvm-${target}`;
+ let archive = built.get(key);
+ if (archive === undefined) {
+ archive = withMobileTarget(target, async () => {
+ const outDir = join(cacheDir, key);
+ mkdirSync(outDir, { recursive: true });
+ const profile = JSON.parse(readFileSync(join(threadFixtureDir, "profile_t.json"), "utf8")) as {
+ entry: string;
+ emission: string;
+ abi: Record;
+ };
+ profile.emission = "llvm";
+ profile.entry = join(threadFixtureDir, profile.entry);
+ profile.abi["localize_runtime"] = true;
+ const profilePath = join(outDir, "profile.json");
+ writeFileSync(profilePath, JSON.stringify(profile, null, 2));
+ const result = await compileLibrary({ profilePath, outDir });
+ if (!result.ok) {
+ throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
+ }
+ return result.archivePath;
+ });
+ built.set(key, archive);
+ }
+ const probe = buildAppleProbe([await archive], join(threadFixtureDir, "probe.c"), "ios-run-t", target);
+ const udid = ensureBootedSimulator();
+ const out = execFileSync("xcrun", ["simctl", "spawn", udid, probe], {
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ expect(out).toBe(THREADED_EXPECTED);
+ }, 600_000);
+ });
+});
+
+/* ── M14: Android (SCRIPTC_ANDROID=1) ─────────────────────────────────────── */
+
+/** The SDK roots the NDK/emulator discovery searches: the explicit
+ * environment first, then the platform-default install location. */
+function androidSdkRoots(): string[] {
+ return [
+ process.env["ANDROID_HOME"],
+ process.env["ANDROID_SDK_ROOT"],
+ process.platform === "darwin"
+ ? join(homedir(), "Library", "Android", "sdk")
+ : join(homedir(), "Android", "Sdk"),
+ ].filter((root): root is string => root !== undefined && root !== "" && existsSync(root));
+}
+
+/** The NDK's clang driver — the embedder-side link tool (what a Gradle/NDK
+ * build invokes), used here to link probes at the API 26 floor. */
+function androidNdkClang(): string | null {
+ const ndkRoots: string[] = [];
+ const explicit = [process.env["ANDROID_NDK_ROOT"], process.env["ANDROID_NDK_HOME"]]
+ .find((root): root is string => root !== undefined && root !== "");
+ if (explicit !== undefined) ndkRoots.push(explicit);
+ for (const sdk of androidSdkRoots()) {
+ const ndkDir = join(sdk, "ndk");
+ if (!existsSync(ndkDir)) continue;
+ ndkRoots.push(...readdirSync(ndkDir).sort().reverse().map((version) => join(ndkDir, version)));
+ }
+ for (const ndk of ndkRoots) {
+ const prebuilt = join(ndk, "toolchains", "llvm", "prebuilt");
+ if (!existsSync(prebuilt)) continue;
+ for (const host of readdirSync(prebuilt).sort()) {
+ const clang = join(prebuilt, host, "bin", "clang");
+ if (existsSync(clang)) return clang;
+ }
+ }
+ return null;
+}
+
+function androidTool(name: "adb" | "emulator"): string {
+ for (const sdk of androidSdkRoots()) {
+ const path = join(sdk, name === "adb" ? "platform-tools" : "emulator", name);
+ if (existsSync(path)) return path;
+ }
+ return name; // PATH fallback
+}
+
+function buildAndroidProbe(archives: string[], source: string, tag: string): string {
+ const outDir = join(cacheDir, "probes");
+ mkdirSync(outDir, { recursive: true });
+ const bin = join(outDir, `probe-${tag}`);
+ const clang = androidNdkClang();
+ if (clang === null) throw new Error("SCRIPTC_ANDROID=1 needs an NDK (ANDROID_NDK_ROOT or /ndk).");
+ execFileSync(clang, [
+ `--target=aarch64-linux-android${ANDROID_MIN_API}`,
+ "-std=c11",
+ source,
+ ...archives,
+ "-lm",
+ "-o", bin,
+ ]);
+ return bin;
+}
+
+/** The device the execution legs share: a running emulator/device is
+ * reused when it carries arm64-v8a and API 26+; otherwise a headless arm64
+ * AVD is written directly (the emulator reads ~/.android/avd — no
+ * avdmanager/Java dependency) and booted on an exclusively claimed port,
+ * then torn down by the suite. The UUID-scoped AVD name and ownership
+ * marker keep concurrent lanes and pre-existing user AVDs out of scope. */
+interface AndroidPortClaim {
+ port: number;
+ lockPath: string;
+}
+
+type AndroidDevice =
+ | { serial: string; startedByUs: false }
+ | {
+ serial: string;
+ startedByUs: true;
+ adbOwned: boolean;
+ emulator: ReturnType;
+ portClaim: AndroidPortClaim;
+ };
+
+let androidDevice: AndroidDevice | null = null;
+const ANDROID_LANE_OWNER = `${process.pid}-${randomUUID()}`;
+const ANDROID_LANE_AVD = `scriptc-mobile-lane-${ANDROID_LANE_OWNER}`;
+const ANDROID_PORT_MIN = 5554;
+const ANDROID_PORT_MAX = 5682;
+const ANDROID_PORT_LOCK_ROOT = join(tmpdir(), "scriptc-mobile-emulator-ports");
+const ANDROID_AVD_OWNER_FILE = ".scriptc-owner";
+
+function adbDevices(adb: string): string[] {
+ return execFileSync(adb, ["devices"], { encoding: "utf8" })
+ .split("\n")
+ .slice(1)
+ .map((line) => line.trim())
+ .filter((line) => line.endsWith("\tdevice") || line.endsWith(" device"))
+ .map((line) => line.split(/\s+/)[0]!);
+}
+
+function isCompatibleAndroidDevice(abiList: string, sdkLevel: string): boolean {
+ const abis = abiList.split(",").map((abi) => abi.trim());
+ const sdk = Number.parseInt(sdkLevel.trim(), 10);
+ return abis.includes("arm64-v8a") && Number.isFinite(sdk) && sdk >= ANDROID_MIN_API;
+}
+
+function compatibleAndroidDevice(adb: string, serial: string): boolean {
+ const getprop = (name: string): string | null => {
+ const result = spawnSync(adb, ["-s", serial, "shell", "getprop", name], {
+ encoding: "utf8",
+ timeout: 15_000,
+ });
+ return result.status === 0 ? (result.stdout ?? "").trim() : null;
+ };
+ const abiList = getprop("ro.product.cpu.abilist") || getprop("ro.product.cpu.abi");
+ const sdkLevel = getprop("ro.build.version.sdk");
+ return abiList !== null && sdkLevel !== null && isCompatibleAndroidDevice(abiList, sdkLevel);
+}
+
+function claimAndroidLanePort(runningSerials: readonly string[]): AndroidPortClaim {
+ mkdirSync(ANDROID_PORT_LOCK_ROOT, { recursive: true });
+ const portCount = (ANDROID_PORT_MAX - ANDROID_PORT_MIN) / 2 + 1;
+ const seed = (process.pid + Number.parseInt(ANDROID_LANE_OWNER.slice(-8), 16)) % portCount;
+ for (let offset = 0; offset < portCount; offset++) {
+ const port = ANDROID_PORT_MIN + 2 * ((seed + offset) % portCount);
+ if (runningSerials.includes(`emulator-${port}`)) continue;
+ const lockPath = join(ANDROID_PORT_LOCK_ROOT, `${port}.lock`);
+ try {
+ writeFileSync(
+ lockPath,
+ JSON.stringify({ owner: ANDROID_LANE_OWNER, pid: process.pid }),
+ { flag: "wx", mode: 0o600 },
+ );
+ return { port, lockPath };
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
+ }
+ }
+ throw new Error(`no unclaimed even Android emulator port is available in ${ANDROID_PORT_MIN}-${ANDROID_PORT_MAX}`);
+}
+
+function releaseAndroidLanePort(claim: AndroidPortClaim): void {
+ try {
+ const record = JSON.parse(readFileSync(claim.lockPath, "utf8")) as { owner?: unknown };
+ if (record.owner === ANDROID_LANE_OWNER) rmSync(claim.lockPath, { force: true });
+ } catch {
+ /* a missing or foreign lock is not ours to remove */
+ }
+}
+
+function removeAndroidLaneAvd(): void {
+ const avdRoot = join(homedir(), ".android", "avd");
+ const avdDir = join(avdRoot, `${ANDROID_LANE_AVD}.avd`);
+ const iniPath = join(avdRoot, `${ANDROID_LANE_AVD}.ini`);
+ try {
+ if (readFileSync(join(avdDir, ANDROID_AVD_OWNER_FILE), "utf8") !== ANDROID_LANE_OWNER) return;
+ } catch {
+ return;
+ }
+ let ownsIni = false;
+ try {
+ ownsIni = readFileSync(iniPath, "utf8").includes(`path=${avdDir}\n`);
+ } catch {
+ /* the ini may not have been written before setup failed */
+ }
+ rmSync(avdDir, { recursive: true, force: true });
+ if (ownsIni) rmSync(iniPath, { force: true });
+}
+
+function stopOwnedAndroidDevice(): void {
+ if (androidDevice?.startedByUs !== true) return;
+ const owned = androidDevice;
+ androidDevice = null;
+ if (owned.adbOwned) {
+ try {
+ execFileSync(androidTool("adb"), ["-s", owned.serial, "emu", "kill"], { timeout: 30_000 });
+ } catch {
+ /* the emulator may have exited after its identity was verified */
+ }
+ }
+ try {
+ owned.emulator.kill("SIGTERM");
+ } catch {
+ /* process cleanup is best-effort — never mask a real failure */
+ }
+ removeAndroidLaneAvd();
+ releaseAndroidLanePort(owned.portClaim);
+}
+
+function createAndroidLaneAvd(image: { sysdir: string; api: string }): void {
+ const avdRoot = join(homedir(), ".android", "avd");
+ const avdDir = join(avdRoot, `${ANDROID_LANE_AVD}.avd`);
+ mkdirSync(avdRoot, { recursive: true });
+ mkdirSync(avdDir);
+ let marked = false;
+ try {
+ writeFileSync(join(avdDir, ANDROID_AVD_OWNER_FILE), ANDROID_LANE_OWNER, { flag: "wx", mode: 0o600 });
+ marked = true;
+ writeFileSync(
+ join(avdRoot, `${ANDROID_LANE_AVD}.ini`),
+ `avd.ini.encoding=UTF-8\npath=${avdDir}\npath.rel=avd/${ANDROID_LANE_AVD}.avd\ntarget=${image.api}\n`,
+ { flag: "wx" },
+ );
+ writeFileSync(
+ join(avdDir, "config.ini"),
+ [
+ `AvdId=${ANDROID_LANE_AVD}`,
+ "PlayStore.enabled=false",
+ "abi.type=arm64-v8a",
+ "avd.ini.encoding=UTF-8",
+ "disk.dataPartition.size=2G",
+ "hw.cpu.arch=arm64",
+ "hw.cpu.ncore=4",
+ "hw.gpu.enabled=no",
+ "hw.gpu.mode=off",
+ "hw.keyboard=yes",
+ "hw.lcd.density=440",
+ "hw.lcd.height=2280",
+ "hw.lcd.width=1080",
+ "hw.ramSize=2048",
+ "hw.sdCard=no",
+ `image.sysdir.1=${image.sysdir}`,
+ "tag.display=Google APIs",
+ "tag.id=google_apis",
+ "",
+ ].join("\n"),
+ { flag: "wx" },
+ );
+ } catch (err) {
+ if (marked) removeAndroidLaneAvd();
+ else rmSync(avdDir, { recursive: true, force: true });
+ throw err;
+ }
+}
+
+function androidEmulatorAvdName(adb: string, serial: string): string | null {
+ const result = spawnSync(adb, ["-s", serial, "emu", "avd", "name"], {
+ encoding: "utf8",
+ timeout: 15_000,
+ });
+ if (result.status !== 0) return null;
+ return (result.stdout ?? "")
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .find((line) => line !== "" && line !== "OK") ?? null;
+}
+
+async function ensureAndroidDevice(): Promise {
+ if (androidDevice !== null) return androidDevice.serial;
+ const adb = androidTool("adb");
+ const running = adbDevices(adb);
+ const compatible = running.find((serial) => compatibleAndroidDevice(adb, serial));
+ if (compatible !== undefined) {
+ androidDevice = { serial: compatible, startedByUs: false };
+ return compatible;
+ }
+ // No device: write the AVD and boot it headless. The system image is the
+ // newest installed arm64-v8a one.
+ const image = ((): { sdk: string; sysdir: string; api: string } | null => {
+ for (const sdk of androidSdkRoots()) {
+ const imagesDir = join(sdk, "system-images");
+ if (!existsSync(imagesDir)) continue;
+ const apis = readdirSync(imagesDir)
+ .filter((name) => {
+ const api = Number.parseInt(name.replace(/^android-/, ""), 10);
+ return name.startsWith("android-") && Number.isFinite(api) && api >= ANDROID_MIN_API;
+ })
+ .sort(
+ (a, b) =>
+ Number.parseInt(b.replace(/^android-/, ""), 10) -
+ Number.parseInt(a.replace(/^android-/, ""), 10),
+ );
+ for (const api of apis) {
+ for (const tag of readdirSync(join(imagesDir, api)).sort()) {
+ const abiDir = join(imagesDir, api, tag, "arm64-v8a");
+ if (existsSync(abiDir)) {
+ return { sdk, sysdir: `system-images/${api}/${tag}/arm64-v8a/`, api };
+ }
+ }
+ }
+ }
+ return null;
+ })();
+ if (image === null) {
+ throw new Error(
+ "SCRIPTC_ANDROID=1 needs a compatible running device or an installed API-26+ arm64-v8a system image " +
+ "(sdkmanager 'system-images;android-;google_apis;arm64-v8a') to boot one.",
+ );
+ }
+ const portClaim = claimAndroidLanePort(running);
+ try {
+ createAndroidLaneAvd(image);
+ } catch (err) {
+ releaseAndroidLanePort(portClaim);
+ throw err;
+ }
+ let emulator: ReturnType;
+ try {
+ emulator = spawn(
+ androidTool("emulator"),
+ [
+ "-avd", ANDROID_LANE_AVD,
+ "-port", String(portClaim.port),
+ "-no-window", "-no-audio", "-no-boot-anim", "-no-snapshot", "-gpu", "off",
+ ],
+ { detached: true, stdio: "ignore" },
+ );
+ } catch (err) {
+ removeAndroidLaneAvd();
+ releaseAndroidLanePort(portClaim);
+ throw err;
+ }
+ const serial = `emulator-${portClaim.port}`;
+ const ownedDevice: Extract = {
+ serial,
+ startedByUs: true,
+ adbOwned: false,
+ emulator,
+ portClaim,
+ };
+ androidDevice = ownedDevice;
+ let emulatorError: Error | null = null;
+ emulator.once("error", (err) => {
+ emulatorError = err;
+ });
+ emulator.unref();
+ try {
+ const deadline = Date.now() + 300_000;
+ for (;;) {
+ if (emulatorError !== null) throw emulatorError;
+ if (emulator.exitCode !== null || emulator.signalCode !== null) {
+ throw new Error(
+ `the Android emulator exited before boot completed (` +
+ (emulator.exitCode !== null ? `exit ${emulator.exitCode}` : `signal ${emulator.signalCode}`) +
+ `)`,
+ );
+ }
+ const probe = spawnSync(adb, ["-s", serial, "shell", "getprop", "sys.boot_completed"], {
+ encoding: "utf8",
+ timeout: 15_000,
+ });
+ if ((probe.stdout ?? "").trim() === "1") {
+ const avdName = androidEmulatorAvdName(adb, serial);
+ if (avdName !== ANDROID_LANE_AVD) {
+ throw new Error(
+ `${serial} belongs to AVD '${avdName ?? ""}', not this lane's '${ANDROID_LANE_AVD}'`,
+ );
+ }
+ ownedDevice.adbOwned = true;
+ break;
+ }
+ if (Date.now() > deadline) throw new Error("the Android emulator did not finish booting within 5 minutes");
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+ }
+ } catch (err) {
+ stopOwnedAndroidDevice();
+ throw err;
+ }
+ return serial;
+}
+
+/** Push a probe and run it on the device, returning its stdout. */
+function adbRun(serial: string, probe: string, tag: string): string {
+ const adb = androidTool("adb");
+ const remote = `/data/local/tmp/scriptc-mobile-lane-${tag}`;
+ execFileSync(adb, ["-s", serial, "push", probe, remote], { timeout: 60_000 });
+ try {
+ return execFileSync(adb, ["-s", serial, "shell", `chmod 755 ${remote} && ${remote}`], {
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ } finally {
+ try {
+ execFileSync(adb, ["-s", serial, "shell", `rm -f ${remote}`], { timeout: 30_000 });
+ } catch {
+ /* cleanup is best-effort — never mask the real failure */
+ }
+ }
+}
+
+describe.skipIf(!androidOn)("mobile targets: Android (SCRIPTC_ANDROID=1)", () => {
+ afterAll(() => {
+ stopOwnedAndroidDevice();
+ });
+
+ test("the Android toolchain is present", () => {
+ // Fail, never skip: SCRIPTC_ANDROID=1 promises an Android verdict.
+ expect(androidNdkClang(), "an NDK (ANDROID_NDK_ROOT or /ndk)").not.toBeNull();
+ execFileSync("zig", ["version"], { encoding: "utf8" });
+ });
+
+ describe.each(EMISSIONS)("%s emission", (emission) => {
+ test("M14: localized archives build; symbols exact, ambient audit holds, probe links at API 26", async (ctx) => {
+ if (nmTool === null) ctx.skip("no nm on PATH for the symbol-exactness check");
+ const archiveA = await buildInstanceCross("a", emission, "aarch64-linux-android");
+ const archiveB = await buildInstanceCross("b", emission, "aarch64-linux-android");
+ for (const [archive, declared] of [
+ [archiveA, A_SYMBOLS],
+ [archiveB, B_SYMBOLS],
+ ] as const) {
+ const { defined, undef } = nmSymbols(archive);
+ expect([...defined].sort()).toEqual([...declared].sort());
+ expect([...undef].filter((s) => s.startsWith("scr_") || s.startsWith("ma_") || s.startsWith("mb_"))).toEqual([]);
+ for (const banned of ["sigaction", "signal", "pthread_create", "atexit", "setvbuf"]) {
+ expect(undef.has(banned), `undefined reference to ${banned}`).toBe(false);
+ }
+ }
+ buildAndroidProbe([archiveA, archiveB], join(fixtureDir, "probe.c"), `android-${emission}`);
+ }, 240_000);
+ });
+
+ describe("M14 emulator execution", () => {
+ test.for(EMISSIONS)(
+ "the two-instance probe runs on the emulator (%s emission)",
+ async (emission) => {
+ const archiveA = await buildInstanceCross("a", emission, "aarch64-linux-android");
+ const archiveB = await buildInstanceCross("b", emission, "aarch64-linux-android");
+ const probe = buildAndroidProbe(
+ [archiveA, archiveB],
+ join(fixtureDir, "probe.c"),
+ `android-run-${emission}`,
+ );
+ const serial = await ensureAndroidDevice();
+ expect(adbRun(serial, probe, `m2-${emission}`)).toBe(PROBE_EXPECTED);
+ },
+ 600_000,
+ );
+
+ test("a thread-instanced and runtime-localized archive runs on the emulator", async () => {
+ const key = "android-t-llvm";
+ let archive = built.get(key);
+ if (archive === undefined) {
+ archive = withMobileTarget("aarch64-linux-android", async () => {
+ const outDir = join(cacheDir, key);
+ mkdirSync(outDir, { recursive: true });
+ const profile = JSON.parse(readFileSync(join(threadFixtureDir, "profile_t.json"), "utf8")) as {
+ entry: string;
+ emission: string;
+ abi: Record;
+ };
+ profile.emission = "llvm";
+ profile.entry = join(threadFixtureDir, profile.entry);
+ profile.abi["localize_runtime"] = true;
+ const profilePath = join(outDir, "profile.json");
+ writeFileSync(profilePath, JSON.stringify(profile, null, 2));
+ const result = await compileLibrary({ profilePath, outDir });
+ if (!result.ok) {
+ throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
+ }
+ return result.archivePath;
+ });
+ built.set(key, archive);
+ }
+ const probe = buildAndroidProbe([await archive], join(threadFixtureDir, "probe.c"), "android-run-t");
+ const serial = await ensureAndroidDevice();
+ expect(adbRun(serial, probe, "m6")).toBe(THREADED_EXPECTED);
+ }, 600_000);
+ });
+});