Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions docs/internal/agent-rules/toolchain.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,41 @@ hand on a machine with a simulator, where
bytes it wrote into Annex-B and counts each tag, and `ffprobe out.264` says
whether they decode.

## The simulator jail

The same script builds `src/drivers/ios/jail/` (Swift, ours, no upstream) into
`dist/jail/`: `libsimlock-jail.dylib` for the iOS Simulator and `simlock-jail`
for the Mac, with `profile.sb` copied beside them. Each binary is compiled by
`swiftc` once per CPU (arm64 and x86_64) and joined by `lipo`; one that did not
build, or lost a slice, is left out with a warning, and the profile ships only
beside both. Nothing in the driver uses them yet: the three files are the
whole sandbox, and booting a simulator under it is done by hand.

All of it rests on private Apple interfaces (`src/drivers/ios/jail/private.h`,
the profile language, the `SIMCTL_CHILD_` environment of `simctl boot`), so a
new macOS, Xcode or iOS runtime needs a check by hand:

1. `simlock-jail compile profile.sb <out> NAME=VALUE ...` with the values
`profile.sb` lists at its top, every path a real path.
2. `simctl boot` (never `bootstatus -b`, which drops the environment) with
`SIMCTL_CHILD_DYLD_INSERT_LIBRARIES` naming the library,
`SIMCTL_CHILD_SIMLOCK_JAIL_PROFILE` the compiled profile and
`SIMCTL_CHILD_SIMLOCK_JAIL_TOKEN` the same token the profile was given.
3. `simlock-jail check` with the pid of that simulator's `launchd_sim` and of
its children exits 0, Settings opens, and an app installed from a folder
inside the simulator's own folder cannot list the worker's home.

That was done on macOS 26.6 with Xcode 27.2 and the iOS 27.2 runtime, on Apple
silicon, with an XCTest run and an agent-device session inside the jail. The
x86_64 library slice has not run in a simulator. The unit lane covers only
what the script does with the tools' results (`src/build-capture.test.ts`).

What the jail changes for whoever boots under it: `simctl install`,
`addmedia` and Xcode's test-runner install read their source inside the
simulator, so it must be in a folder the profile allows; `simctl spawn` of a
program of the Mac's is refused; a loopback port is reachable only when it
was named at compile time.

## Slow lane

Tests that start real simulators or emulators. Run them only through
Expand Down
77 changes: 75 additions & 2 deletions scripts/build-capture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
// program of vendor/screen-capture/ is built with its own `swift build --product` and copied to
// dist/bin/ — one failing does not skip the other, and the daemon reports the streams it lost.
// Anywhere else the Swift build is skipped with a note, and the daemon reports iOS streams as
// unavailable.
// unavailable. On the same Mac the simulator jail of src/drivers/ios/jail/ is built too: its
// library for the iOS Simulator and its `simlock-jail` program for the Mac, into dist/jail/ beside
// the profile the program compiles.
// Each artifact ships with its upstream's NOTICE.md and LICENSES/ in dist/vendor/<dir>/, because the
// package publishes dist/ and Apache-2.0 §4(a) asks that whoever gets a binary gets its license too.
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { basename, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");
Expand Down Expand Up @@ -106,5 +108,76 @@
if (copied.length > 0) copyNotices("screen-capture");
}

// why: SwiftPM builds for the Mac only, and the jail library is loaded inside simulator processes,
// so each artifact is compiled by `swiftc` against the SDK it runs on, one slice per CPU, and
// `lipo` joins the slices. Both CPUs, because an Intel Mac is a worker too and its simulators
// run x86_64 code.
function buildUniversalSwift({ output, what, sdk, triple, source, flags }) {

Check failure on line 115 in scripts/build-capture.mjs

View workflow job for this annotation

GitHub Actions / Fallow

High CRAP score (moderate)

Function 'buildUniversalSwift' has a CRAP score of 30 (threshold: 30). • Severity: moderate • Cyclomatic: 5 • Cognitive: 5 • CRAP: 30 (threshold: 30) • Lines: 35 CRAP combines complexity with coverage: high CRAP means changes here carry high risk. Consider adding tests, simplifying the function, or both.
const jail = join(root, "src/drivers/ios/jail");
const scratch = join(root, "node_modules/.cache/simlock-jail");
const slices = [];
for (const arch of ["arm64", "x86_64"]) {
const slice = join(scratch, arch, basename(output));
mkdirSync(dirname(slice), { recursive: true });
const args = [
"--sdk",
sdk,
"swiftc",
"-O",
"-module-name",
"SimlockJail",
"-target",
triple(arch),
];
args.push("-import-objc-header", join(jail, "private.h"), ...flags, join(jail, source));
const compiled = spawnSync("xcrun", [...args, "-o", slice], { stdio: "inherit" });
if (compiled.status === 0) slices.push(slice);
}
mkdirSync(dirname(output), { recursive: true });
const joined =
slices.length === 2 &&
spawnSync("xcrun", ["lipo", "-create", ...slices, "-output", output], { stdio: "inherit" })
.status === 0;
if (!joined) {
console.warn(
`build-capture: could not build ${basename(output)} (is Xcode installed and selected?); ${what} will be unavailable`,
);
return false;
}
chmodSync(output, 0o755);
return true;
}

function buildSimulatorJail() {
if (process.platform !== "darwin") {
console.log("build-capture: not macOS, skipping the simulator jail");
return;
}
// why: iOS 16 is the oldest runtime the iOS driver leases, and macOS 14 the oldest Mac the
// capture programs run on.
const library = buildUniversalSwift({
output: join(dist, "jail/libsimlock-jail.dylib"),
what: "the simulator jail",
sdk: "iphonesimulator",
triple: (arch) => `${arch}-apple-ios16.0-simulator`,
source: "Jail.swift",
flags: ["-parse-as-library", "-emit-library"],
});
const program = buildUniversalSwift({
output: join(dist, "jail/simlock-jail"),
what: "the simulator jail's profile compiler",
sdk: "macosx",
triple: (arch) => `${arch}-apple-macos14.0`,
source: "main.swift",
flags: ["-lsandbox"],
});
// why: the profile is compiled per simulator on the worker, so it ships as text; it is of no
// use without both of the others.
if (library && program) {
copyFileSync(join(root, "src/drivers/ios/jail/profile.sb"), join(dist, "jail/profile.sb"));
}
}

copyScrcpyServer();
buildIosCapture();
buildSimulatorJail();
84 changes: 84 additions & 0 deletions src/build-capture.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
Expand All @@ -30,6 +31,8 @@ function scratchRepo(server: string, digest: string): string {
mkdirSync(join(root, "scripts"));
mkdirSync(join(root, "vendor", "scrcpy"), { recursive: true });
cpSync(SCRIPT, join(root, "scripts", "build-capture.mjs"));
mkdirSync(join(root, "src", "drivers", "ios", "jail"), { recursive: true });
writeFileSync(join(root, "src", "drivers", "ios", "jail", "profile.sb"), "the jail's profile");
writeFileSync(join(root, "vendor", "scrcpy", "scrcpy-server-v5.0.1"), server);
writeFileSync(
join(root, "vendor", "scrcpy", "SHA256SUMS.txt"),
Expand Down Expand Up @@ -85,6 +88,40 @@ function fakeSwift(repo: string): string {
return bin;
}

// why: an `xcrun` that writes what `swiftc` and `lipo` would, so the claim about the slices is
// checked without Xcode: a slice holds its target and SDK, and `lipo` joins the slices it is given.
// It fails the outputs and the targets named in SIMLOCK_FAKE_XCRUN_FAIL, so a test can lose one
// artifact or one slice.
function fakeXcrun(repo: string): string {
const bin = join(repo, "fake-xcrun");
mkdirSync(bin, { recursive: true });
writeFileSync(
join(bin, "xcrun"),
[
"#!/bin/sh",
'sdk=""; target=""; out=""; tool=""; slices=""',
'while [ "$#" -gt 0 ]; do',
' case "$1" in',
' --sdk) shift; sdk="$1" ;;',
' -target) shift; target="$1" ;;',
' -o|-output) shift; out="$1" ;;',
' swiftc|lipo) tool="$1" ;;',
' */arm64/*|*/x86_64/*) slices="$slices $1" ;;',
" esac",
" shift",
"done",
'name="$(/usr/bin/basename "$out")"',
'case ",$SIMLOCK_FAKE_XCRUN_FAIL," in *",$name,"*) exit 1 ;; esac',
'if [ -n "$target" ]; then',
' case ",$SIMLOCK_FAKE_XCRUN_FAIL," in *",$target,"*) exit 1 ;; esac',
"fi",
'if [ "$tool" = swiftc ]; then echo "$target on $sdk" > "$out"; else /bin/cat $slices > "$out"; fi',
].join("\n"),
);
chmodSync(join(bin, "xcrun"), 0o755);
return bin;
}

function sha256(text: string): string {
return createHash("sha256").update(text).digest("hex");
}
Expand Down Expand Up @@ -165,4 +202,51 @@ describe("scripts/build-capture.mjs", () => {
expect(existsSync(join(shipped, "NOTICE.md"))).toBe(true);
},
);

it.skipIf(process.platform !== "darwin")(
"builds the simulator jail's library for the iOS Simulator and its `simlock-jail` program for the Mac, each from an arm64 and an x86_64 slice, ships the profile only beside both, and ships neither a lone slice nor a program that did not build",
() => {
const repo = scratchRepo("the real server", sha256("the real server"));
const run = (path: string, fail = "") =>
spawnSync(process.execPath, [join(repo, "scripts", "build-capture.mjs")], {
encoding: "utf8",
env: { ...process.env, PATH: path, SIMLOCK_FAKE_XCRUN_FAIL: fail },
});
const library = join(repo, "dist", "jail", "libsimlock-jail.dylib");
const compiler = join(repo, "dist", "jail", "simlock-jail");
const profile = join(repo, "dist", "jail", "profile.sb");

run("");
expect(existsSync(library)).toBe(false);
expect(existsSync(compiler)).toBe(false);
expect(existsSync(profile)).toBe(false);

run(fakeXcrun(repo));
expect(readFileSync(library, "utf8")).toBe(
"arm64-apple-ios16.0-simulator on iphonesimulator\nx86_64-apple-ios16.0-simulator on iphonesimulator\n",
);
expect(readFileSync(compiler, "utf8")).toBe(
"arm64-apple-macos14.0 on macosx\nx86_64-apple-macos14.0 on macosx\n",
);
expect(statSync(compiler).mode & 0o777).toBe(0o755);
expect(readFileSync(profile, "utf8")).toBe("the jail's profile");

rmSync(join(repo, "dist"), { force: true, recursive: true });
const libraryFailed = run(fakeXcrun(repo), "libsimlock-jail.dylib");
expect(existsSync(library)).toBe(false);
expect(existsSync(compiler)).toBe(true);
expect(existsSync(profile)).toBe(false);
expect(libraryFailed.stdout + libraryFailed.stderr).toMatch(
/the simulator jail will be unavailable/iu,
);

rmSync(join(repo, "dist"), { force: true, recursive: true });
const intelSliceFailed = run(fakeXcrun(repo), "x86_64-apple-macos14.0");
expect(existsSync(library)).toBe(true);
expect(existsSync(compiler)).toBe(false);
expect(intelSliceFailed.stdout + intelSliceFailed.stderr).toMatch(
/the simulator jail's profile compiler will be unavailable/iu,
);
},
);
});
63 changes: 63 additions & 0 deletions src/drivers/ios/jail/Jail.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// why: this library is loaded into `launchd_sim` (DYLD_INSERT_LIBRARIES on `simctl boot`) and, with
// the environment `launchd_sim` passes on, into every process of that simulator. Nothing in the
// driver boots a simulator with it yet.
import Darwin

// why: a stock simulator has no sandbox, so there every advisory check answers "allowed" and "is
// this process sandboxed?" answers no. iOS daemons ask before they talk to each other (SpringBoard
// stops when a lookup check says no) and `log` refuses to run sandboxed, so they get the stock
// answer. Only honest processes are helped: the kernel and the host's launchd still refuse.
@_cdecl("simlock_jail_allowed") func jailAllowed() -> Int32 { 0 }

// why: `launchd_sim` makes its socket folders in /private/var/tmp, which every simulator of the
// worker shares. A per-simulator token in the name lets a profile allow this simulator's folders
// and no other's. The name keeps its length, because the caller owns the buffer.
@_cdecl("simlock_jail_mkdtemp")
func jailMkdtemp(_ template: UnsafeMutablePointer<CChar>?) -> UnsafeMutablePointer<CChar>? {
let prefix = "/private/var/tmp/com.apple.launchd."
let length = prefix.utf8.count
if let template, let token = getenv("SIMLOCK_JAIL_TOKEN"), strlen(token) == 6,
strncmp(template, prefix, length) == 0, strcmp(template + length, "XXXXXXXXXX") == 0
{
memcpy(template + length, token, 6)
}
return mkdtemp(template)
}

typealias Check = @convention(c) () -> Int32
typealias SelfCheck = @convention(c) (pid_t, UnsafePointer<CChar>?, Int32) -> Int32
typealias MakeTemp = @convention(c) (UnsafeMutablePointer<CChar>?) -> UnsafeMutablePointer<CChar>?

// why: dyld reads this section as (replacement, original) pairs and redirects every other image's
// calls; calls made from this library still reach the original.
@used @section("__DATA,__interpose")
let interposeCheck: (Check, SelfCheck) = (jailAllowed, sandbox_check)
@used @section("__DATA,__interpose")
let interposeCheckByToken: (Check, Check) = (jailAllowed, sandbox_check_by_audit_token)
@used @section("__DATA,__interpose")
let interposeCheckById: (Check, Check) = (jailAllowed, sandbox_check_by_uniqueid)
@used @section("__DATA,__interpose")
let interposeMakeTemp: (MakeTemp, MakeTemp) = (jailMkdtemp, mkdtemp)

// why: dyld runs this before the process's own code. `launchd_sim` is not sandboxed yet, so it
// applies the compiled profile there; the kernel gives the same sandbox to every child, which is
// why a process that is already sandboxed does nothing. A simulator that cannot be jailed must not
// run, so every failure ends the process.
@used @section("__DATA,__mod_init_func")
let enterJail: @convention(c) () -> Void = {
guard let path = getenv("SIMLOCK_JAIL_PROFILE") else { return }
if sandbox_check(getpid(), nil, 0) == 1 { return }
let file = open(path, O_RDONLY)
guard file >= 0 else { _exit(78) }
var bytes = [UInt8](repeating: 0, count: 1 << 20)
let count = read(file, &bytes, bytes.count)
close(file)
guard count > 0 else { _exit(78) }
let applied = bytes.withUnsafeBufferPointer { buffer in
var profile = simlock_jail_profile(
data: buffer.baseAddress, size: count, container: nil, container_len: 0)
return __sandbox_ms("Sandbox", 0, &profile)
}
guard applied == 0 else { _exit(78) }
_sandbox_enter_notify_libxpc()
}
66 changes: 66 additions & 0 deletions src/drivers/ios/jail/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// why: the host half of the simulator jail, `simlock-jail`:
// compile <profile.sb> <output> [NAME=VALUE ...] a simulator runtime carries no profile
// compiler, so the profile is compiled on the Mac and the jail library applies the bytes
// check <pid> [<pid> ...] exits 0 only when every process is sandboxed, so whoever booted a
// simulator can refuse one whose jail did not take
import Darwin

func fail(_ code: Int32, _ message: String) -> Never {
fputs("simlock-jail: \(message)\n", stderr)
exit(code)
}

func compile(_ arguments: [String]) {
guard arguments.count >= 2 else { usage() }
// why: libsandbox looks a relative name up among its built-in profiles, not in the working folder.
guard let source = realpath(arguments[0], nil) else { fail(66, "cannot read \(arguments[0])") }
guard let parameters = sandbox_create_params() else { fail(70, "cannot create parameters") }
for pair in arguments.dropFirst(2) {
guard let equals = pair.firstIndex(of: "="), equals != pair.startIndex else {
fail(64, "\(pair) is not NAME=VALUE")
}
let name = String(pair[..<equals])
let value = String(pair[pair.index(after: equals)...])
// why: libsandbox keeps the two pointers instead of copying the text, so they must outlive
// the compile; a temporary Swift hands over is gone by then.
guard sandbox_set_param(parameters, strdup(name), strdup(value)) == 0 else {
fail(70, "cannot set \(name)")
}
}
var message: UnsafeMutablePointer<CChar>?
guard let profile = sandbox_compile_file(source, parameters, &message) else {
fail(65, message.map { String(cString: $0) } ?? "unknown error")
}
guard let output = fopen(arguments[1], "wb") else { fail(73, "cannot write \(arguments[1])") }
let written = fwrite(profile.pointee.data, 1, profile.pointee.size, output)
guard fclose(output) == 0, written == profile.pointee.size else {
fail(73, "cannot write \(arguments[1])")
}
}

func check(_ arguments: [String]) {
guard !arguments.isEmpty else { usage() }
var free: [String] = []
for argument in arguments {
guard let pid = pid_t(argument), pid > 0 else { fail(64, "\(argument) is not a process id") }
if sandbox_check(pid, nil, 0) != 1 { free.append(argument) }
}
if !free.isEmpty { fail(1, "not sandboxed: \(free.joined(separator: " "))") }
}

func usage() -> Never {
fputs(
"""
usage: simlock-jail compile <profile.sb> <output> [NAME=VALUE ...]
simlock-jail check <pid> [<pid> ...]

""", stderr)
exit(64)
}

let arguments = Array(CommandLine.arguments.dropFirst())
switch arguments.first {
case "compile": compile(Array(arguments.dropFirst()))
case "check": check(Array(arguments.dropFirst()))
default: usage()
}
Loading
Loading