diff --git a/.crumb b/.crumb index 08aab5a1..d33237e8 100644 --- a/.crumb +++ b/.crumb @@ -27,33 +27,33 @@ "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "4b1e9c63f6fd3b920b9f3f87060222ce2fba8342db53734ffc1748ba15fb74b5", - "last_commit": "fef6fe4", + "digest": "3337a47e3776a3c4a11e1b1d54403261f7fd4bccbdd70a4b61528b8a9e389a43", + "last_commit": "f4c8d8d", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "754f7fe4dd0eafbab2cf6a9f33ccbaca08497dfca1459dc30c76214322d7d9cb", - "last_commit": "fef6fe4", + "digest": "d541968b3f618a0abccebffc9b2c5d8500cf7449cc274a1787583b0e13f729d4", + "last_commit": "9b759de", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "7911dc6ee76b1fbf7fdc8a7593a34cccf8736783af2ae03ad52f57315bad24eb", - "last_commit": "f65912a", + "digest": "6a8bd5f9f008c9388ba829899949836325b9dee35482324ae0ad5159334806e2", + "last_commit": "4b0e3db", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:6a476ae427333981961fd6201076130a343900a26eb56ddb1e17c1497fbda567", - "compiled_at": "2026-10-08T11:48:48Z", + "children_root": "sha256:e60582e62ccdfb58ae53484f5e6b39516c08b54758c9d97ac7f4daa675bc5cd1", + "compiled_at": "2026-10-08T13:03:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:b13a40c5aac9c951cf183f268592b44cc5e922de708a2f9b7d61d0f8ba507ab9", + "digest": "sha256:ce114d472fa32d50d7a74c26ee35cd573f8a7669362f54463ab86bb8b2b639c5", "evidence_files": 153, "evidence_root": "sha256:29aa8775feb12d9e0e64b41fc1fc48b97e32dc16bf9176562cbe9fe1ea934f00", - "files": 2957, - "generated_at_commit": "f65912aa75332b739f2d408118af9f2de7ee6c57", - "source_tree": "sha256:24fbeb88683bdbe3807edbc167f9748dc197d4d435e01be63065c013d3770ebc" + "files": 2970, + "generated_at_commit": "4b0e3dbcc3ea6eae9000be3953a5121763f34d8c", + "source_tree": "sha256:84a4ccee747e7071ba3915d60c1e7ea0895d7203b3ade97105363ed209f5fbbd" }, "owner_lane": "", "provenance": { diff --git a/docs/.crumb b/docs/.crumb index d22610cc..c9e1521f 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -18,7 +18,7 @@ "children": [ { "digest": "97b2985e62f1f3cd6977c23c0c924cd7ce02c2aa635a06eb424c6b1fe9ebd3f0", - "last_commit": "94e8d58", + "last_commit": "fef6fe4", "name": "adr", "purpose": "Directory docs/adr. Purpose not yet described by a human." }, @@ -30,14 +30,14 @@ } ], "children_root": "sha256:b45190ec82f8e2a2101aed670d7e48b08c2e55d9674785ff0c784dff76ab2468", - "compiled_at": "2026-10-08T10:54:55Z", + "compiled_at": "2026-10-08T11:41:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:4b1e9c63f6fd3b920b9f3f87060222ce2fba8342db53734ffc1748ba15fb74b5", + "digest": "sha256:3337a47e3776a3c4a11e1b1d54403261f7fd4bccbdd70a4b61528b8a9e389a43", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 61, - "generated_at_commit": "94e8d58c6598d71f67ecf7b94ab65cb369a63bf6", - "source_tree": "sha256:8e92139bff44fab9183e57cd8a95fdcd24e0a31c836e805c1a6d77cc20bf9490" + "files": 62, + "generated_at_commit": "f4c8d8dc15d73c80929fd3128caaa01d96ce3fb5", + "source_tree": "sha256:67c9b4f88ce6396ca42e9d45548682bfd35b287e1b49150d69d0c21ea7e04916" }, "owner_lane": "", "provenance": { diff --git a/docs/osc-launch.md b/docs/osc-launch.md new file mode 100644 index 00000000..5c80b719 --- /dev/null +++ b/docs/osc-launch.md @@ -0,0 +1,125 @@ +# OSC unit task launch (C3-3a) + +Label for everything below: **QEMU (aarch64 virt), TEST signer, not physical.** Nothing here has run on a +Spark or any real machine. Contract: `OSC_UNIT_ARTIFACT.md` section 9 (aien-protocols PR #17). Gate: +`scripts/qemu_ck_osc_launch_test.sh` (`OSC_LAUNCH` row in `scripts/ck_gates.sh`, notes in +`native/kernel/GATES.md`). + +## What runs + +An admitted unit (`struct osc_accept` from `osc_unit_admit`) is run as one function call in an EL0 task with +its own address space, by `ck_osc_launch` (`core/osc_task.c`): look up the function by exact name, check the +arguments, copy and re-hash the code, map, enter EL0, wait, classify, tear down. One call at a time, one slot. + +## The call signature (what an entry gets) + +- **x0..x5:** the arguments in `reg_kind` order. A slice takes two registers: pointer, then length (`bytes` + length in bytes, `cells` length in 8-byte cells). Scalars are checked for their kind first (bool 0/1, + narrow ints in range, signed ints canonically sign-extended). +- **x7:** `OscRt *`, a unit-space address (base + 0x1000). It points at the 13-pointer vtable of + `runtime_abi_version` 1 (offsets 0..96). The page is **read-only and never executable** to the unit; the + pointers lead to read-execute stubs (base + 0x2000), each `svc #i`. Only the `trap` stub (offset 16) and the + return stub are serviced. +- **x30:** the return stub. The entry function's `ret` reaches it and the kernel reads **x0** as the result. + Every other register is zero. **sp** is the top of a stack of the declared `max_stack_bytes`. +- **Slices:** `bytes` pointers must lie in the input window (read-only to the unit, at most 4096 bytes copied + from the caller, address from `ck_osc_va_in()`). `cells` pointers must be 8-byte aligned and lie in the + caller's workspace (read-write, caller-sized 0 to 32 pages, `ck_osc_va_ws()`). A zero-length slice may carry a null pointer and + is never touched. A pointer anywhere else is refused with 41 before the first instruction. +- **Return value:** one u64 in x0 (`RETURNED.value`); a void function (`ret_kind` 0) reports 0, as the spec says (not exercised by the gate: no + void function in the test units). Narrow return kinds are not re-canonicalized. + +## The ticks budget + +The unit is **timer ticks**: one tick is one EL1 physical-timer interrupt, `CNTFRQ/100` counter counts = +**10 ms** (the C kernel's scheduler tick, `arch/timer.c`). The budget is the unit's declared `cpu_ticks`, +lowered (never raised) by `max_ticks` in the request. The timer is armed only for the duration of the task; +the Nth tick that arrives while EL0 is running ends the task. A task shorter than one tick is never charged +(`ticks=0`); the limit is accurate to one tick. + +`OUTCOME_UNKNOWN` reaches the caller as `struct osc_result`: `cls == OSC_RES_UNKNOWN (4)` and +`unknown_reason`: 1 FAULT, 2 TICK_OVERRUN, 3 LAUNCH_LOST, 4 TRAP_CODE_UNKNOWN, 255 OTHER (the spec's values). +The other classes: `RETURNED (1)` with `value`, `TRAPPED (2)` with `trap_code` 1..14, `REFUSED (3)` with +`refused_code` (40, 41, 30, 16 or 14). The reason is diagnostic and never changes the class. + +## Re-entry: yes, with a caller-owned workspace + +A unit can be called again and see state left in a **caller-owned `cells` workspace**: pass the same +`struct ck_osc_ws` (`{ mem, pages }`, page aligned, `pages` chosen by the caller, 0 to 32) in `ck_osc_launch_req.ws`. The kernel maps the caller's pages read-write (never executable) +and does not clear them at teardown; the unit's own stack and registers are not kept, nothing else persists. +The gate calls `counter(ws, 1)` three times on one workspace (1, 2, 3), once on a fresh one (1 again), and twice on a +23-page workspace (the OSH resumable size, 91,648 bytes) touching its very last cell: 1, then 2, state preserved. +Section 9 allows this: borrows last for one call and the runtime keeps no reference. An OSH step that returns +NEED_MORE_INPUT and is called again therefore works if all its state lives in that workspace. Not provided: +`alloc`, arenas and pools (the runtime services behind vtable offsets 0 and 24..96), so a step that allocates +through `OscRt` ends `OUTCOME_UNKNOWN(OTHER)`. + +## What is enforced + +- **W^X:** code and runtime stubs are read-execute and never writable; data, stack, input window, OscRt table + and workspace are never executable (UXN) and PXN is set on every user page. Kernel mappings are EL1-only. +- **OscRt and kernel memory are not writable by the unit:** a write to the table, to code or to any kernel + address is a contained fault. The stack has an unmapped page below it: overflow is a fault. +- **Code integrity:** the code is copied into private pages and hashed again against `code_sha256` before it + is mapped (spec 8.2); a mismatch is refused 16. +- **No system calls from unit context (9.1.1 item 1):** an SVC anywhere but a runtime stub (with the stub's own + immediate) ends the task as `OUTCOME_UNKNOWN(FAULT)`. Admission already refuses every SVC word (8.4). +- **Arguments before the first instruction:** 9.2 exactly (verified against the spec's C reference) plus + ownership (9.1.1 item 4). Unknown name: 40. Bad shape or range: 41. +- **Results:** RETURNED only through the return stub; TRAPPED only through the trap stub with a code in + 1..14; a `brk` reached directly, any CPU fault, a trap code outside 1..14 and a budget overrun are + `OUTCOME_UNKNOWN`, never RETURNED or TRAPPED. +- **Timers:** EL0 access to the timers, counters and event stream is switched off for the task (CNTKCTL_EL1 bits 0-3, 8, 9 cleared, restored after), whatever firmware left there. +- **Teardown:** tables, runtime pages, input, code and stack are zeroed and unmapped; `page_tables_zeroed=1` (every page-table entry and the L0 slot are zero; this says nothing about frame contents, which are cleared by memset) and the + slot is free for the next launch. Caches are cleaned and the TLB invalidated. + +## Decisions (simplest honest option, with reasons) + +1. **A bare `brk` is a fault, not TRAPPED.** The brief said "TRAPPED with the BRK immediate for BRK 1..14". + Spec 8.4 says a unit that reaches a `brk` has faulted and the platform reports `OUTCOME_UNKNOWN(FAULT)`, + "never TRAPPED"; 9.3 says a launcher never maps a fault to TRAPPED. The spec wins. TRAPPED comes from the + real compiler sequence: the unit calls the runtime trap service with the code (`ldr x16,[rt,#16]; blr x16`, + code in x1), served by the `trap` stub. The gate shows TRAPPED 3 and 14 that way, and `brk` reached + directly as FAULT. +2. **The ticks budget uses the existing 10 ms timer interrupt**, armed only while a task runs, with no + preemption between tasks. This keeps the C kernel's scheduler untouched. Cost: 10 ms granularity. +3. **A caller cap on the budget** (`max_ticks`), because the declared maximum of a signer is up to 1e9 ticks + (a loop would run 115 days). The cap only lowers. +4. **Launcher hard maxima are stricter than the container's.** Spec 8.2 step 16: a signer-declared budget + above a hard maximum is refused `LIMIT_EXCEEDED` (14) before any reservation, nothing runs. The only declared + budget the launcher bounds is `max_stack_bytes`, at 64 KiB: a stack of 65552 (65536 + 16, the smallest legal value above the maximum: the container needs a multiple of 16) gives 14 (gate line, unit + `l02_stack_over`), and so does `a06_valid_limits_at_max` (1 MiB). `cpu_ticks` is never refused here; the caller + cap `max_ticks` only lowers it (decision 3). `pool_slots` is not bounded: no pool service exists, a call to one + ends `OUTCOME_UNKNOWN(OTHER)` (decision 6). Real reservation failures keep 30 (`RESOURCE_UNAVAILABLE`): + code larger than 64 KiB, input over 4 KiB, task slot busy, no free address-space slot. The container has no + workspace field (spec section 7), so there is no declared workspace to refuse. + `cpu_ticks` and `pool_slots` have no launcher hard maximum, so they never get 14 from the launcher: the + container already bounds them at admission (cpu_ticks up to 1e9, pool_slots up to 64), a lower tick limit is + the caller's `max_ticks` (decision 3), and pool_slots reserves nothing because no pool service exists. +4a. **The workspace is caller-sized, capped at 32 pages (128 KiB, `OSC_WS_MAX_PAGES`).** The only workspace bound + is the caller's. OSH needs 23 pages. 0 pages means no workspace. The cap bounds the user pages, page-table + slots and kernel bss; it is the kernel's choice, never read from the container. A request over the cap, with + a null or non-page-aligned `mem`, or overlapping the launcher's own state or the input buffer, is refused + before anything is mapped with 30 (`RESOURCE_UNAVAILABLE`), the code spec 8.3 gives to a failed reservation + of pages. The workspace is mapped read-write into EL0, so it MUST be memory the caller owns. The kernel has no + region it limits workspaces to; beyond those checks it trusts the caller (also stated in `osc_task.h`). The + mapping is never executable, is not cleared at teardown, and `cells` pointer checks use the actual size. +5. **Ownership failures use code 41.** The spec gives no separate code for 9.1.1 item 4. +6. **Unprovided runtime services end the task as `OUTCOME_UNKNOWN(OTHER)`** instead of being faked. +7. **Hand-assembled test unit.** The extra gate units (trap, spin, faults, counter) are written in assembly + (`tests/fixtures/osc_unit/launch/l01.S`) and signed with the spec's own generator helpers; `oscc` emits + only digests, and OSC has no way to loop forever or fault. The IR section is `min.ir`, so the IR does not + describe that code (attested, never checked: spec section 10). + +## Not done (later cuts) + +- **Capability authority:** the capability table delivered to the task is empty. CAPS requests are admitted but + not granted or enforced; admission still treats every pinned generation as stale. +- **Generation** (`required_generation`, the 32/64-bit bridge, conflict C1). +- **IPC and console input**, and any runtime service behind `OscRt` other than trap: alloc, arenas, pools. +- **Concurrency:** one task slot, one call at a time, no preemption between tasks, no SMP use. +- **Return canonicalization:** x0 is reported as-is for every kind except void (reported as 0). +- Kernel entry for launches outside the gate: the self-test driver (`CK_OSC_LAUNCH_TEST`, qualification + builds only) is the only caller. No Store-driven or shell-driven launch exists yet. +- **Nothing is physical.** No Spark, no hardware, no release signer; the only key is the spec's throwaway + TEST key. diff --git a/native/.crumb b/native/.crumb index cc871e16..a88b0c33 100644 --- a/native/.crumb +++ b/native/.crumb @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "8db3b02f3a745d27072e98f7aa2954da4399ad7ca309fde516daecb483ee57fd", - "last_commit": "1ab797d", + "digest": "68428fe30e4288db519473766287af05b2c4e84a4dfab6f501b1037e2ed1c105", + "last_commit": "9b759de", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -109,15 +109,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:e1837301912bc5862254dd4fb533126db5cfe18b0a03e5085c054320179b8fe5", - "compiled_at": "2026-10-08T11:03:01Z", + "children_root": "sha256:ef14904f89b154b2f19af5273d6d225a72641d22f9fd619c747ec2a6209706d2", + "compiled_at": "2026-10-08T12:24:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:754f7fe4dd0eafbab2cf6a9f33ccbaca08497dfca1459dc30c76214322d7d9cb", + "digest": "sha256:d541968b3f618a0abccebffc9b2c5d8500cf7449cc274a1787583b0e13f729d4", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 389, - "generated_at_commit": "1ab797d6c0c42fee6b5fbebebaa81e1e86a55609", - "source_tree": "sha256:d00a64548c8e59e284a47837e329161f0823d4f5c32f9890bb72bd523ea1e2b0" + "files": 400, + "generated_at_commit": "9b759de6e9c8ed316bfe012011bac39831deb10b", + "source_tree": "sha256:c3bbb2b61c77333b3914592a66be03ffa5bd5f852b3fd6a04eb1e430e53b0a30" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 31933e96..20f0e632 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -51,14 +51,14 @@ "purpose": "Directory native/kernel/arch. Purpose not yet described by a human." }, { - "digest": "b7c024fa610faa124f2f26fd002815ea178595962647d544e98ea5a39735f214", - "last_commit": "527a980", + "digest": "90a737e620d9c654ae347aae26b4635b55477d4ef45c68ac10e983019f6af11c", + "last_commit": "f4c8d8d", "name": "artifact", "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { - "digest": "fd9456ff602f0eaa5937f04b46762e8dd4c2692707a6b78076b3da4667f4b4ff", - "last_commit": "bde85f8", + "digest": "a4a7b49093c9c40aaa7238ec33f45790d68e3a52613720c6ba73609c1b3cefab", + "last_commit": "f4c8d8d", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, @@ -87,8 +87,8 @@ "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { - "digest": "1b900c32e47ab5317c6fc9ed443f06496eb9c261857f0c7eec3cd65c97eaddcf", - "last_commit": "1ab797d", + "digest": "e2fcb936b8b24ceb35368fafc1065d042999862da4b9938bb0b708bbd327f018", + "last_commit": "9b759de", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, @@ -99,15 +99,15 @@ "purpose": "Directory native/kernel/tools. Purpose not yet described by a human." } ], - "children_root": "sha256:e378e3a6ed3c6635280cdec9532d1ee6f5535e69cd8b2cd82b887e69fef9684e", - "compiled_at": "2026-10-08T11:03:01Z", + "children_root": "sha256:9e22840d1313e585199be50e51e6c8c29ec5440502b8b03c57e216aee9730877", + "compiled_at": "2026-10-08T12:24:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:8db3b02f3a745d27072e98f7aa2954da4399ad7ca309fde516daecb483ee57fd", + "digest": "sha256:68428fe30e4288db519473766287af05b2c4e84a4dfab6f501b1037e2ed1c105", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 225, - "generated_at_commit": "1ab797d6c0c42fee6b5fbebebaa81e1e86a55609", - "source_tree": "sha256:dd3b1d432eace5c18052e4153139a27e7451fd6cc96e80ffd1263ceddb4dc061" + "files": 236, + "generated_at_commit": "9b759de6e9c8ed316bfe012011bac39831deb10b", + "source_tree": "sha256:a31ea27a8ece70c950d99365ee6b948b0f3b48d08280950862ac31af15eb7be8" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 390c0a22..c5bd32ef 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -730,3 +730,31 @@ Serial input is typed from outside the guest through a QEMU pipe chardev, USB ke Mutation self-test (red before green): `scripts/qemu_ck_console_test.sh --mutation` builds `make full CK_CONSOLE_SESSION=1 CK_TEST_CONSOLE_MUTATION=bm-left-on-after-exit` (TEST-ONLY, announces itself with a `WARNING: TEST-ONLY console session MUTATION BUILD` line, refused with `CK_HARDWARE_STAGING=1`, `CK_QEMU_UNSAFE_DMA=1` and without `CK_CONSOLE_SESSION=1`, by the Makefile and by `#error`), which leaves the xHCI bus master on after the session exit. With the SMMU on, row 151 must FAIL (the revoke prints `revoke FAILED`, the COMMAND read back shows bus_master=on) while the boot still reaches the final report with row 146 passing. The reset-time quiesce hook then revokes the leftover bus master, which is after the session window the row reads. `scripts/ck_gates.sh` takes CONSOLE from this child only (NOT_RUN with exit 3 while the QEMU gate lock is held or the quiet flag exists). + +## OSC_LAUNCH: OSC unit task launch (C-only, Campaign 3 cut C3-3a) -> CK `OSC_LAUNCH` (scripts/qemu_ck_osc_launch_test.sh) + +Contract: `OSC_UNIT_ARTIFACT.md` section 9 (calling convention, launch requirements, argument checks, result +shape), 8.4 and 11. Code: `native/kernel/artifact/osc_launch.{h,c}` (pure: argument rule, range ownership, +ticks budget, result classification) and `native/kernel/core/osc_task.{h,c}` (maps and runs the EL0 task, tears +it down). What is enforced, what is not, and the decisions taken: `docs/osc-launch.md`. + +- Host tests: `tests/test_osc_launch.c`, part of `make test` and `make sanitize`. It runs every line of + `launch.txt` (16), compares the argument rule with the spec's own C reference `osc-launch-check.c` on 3000 + pseudo-random cases (0 mismatches), and classifies all 64 exception classes, every trap code 0..255 and + every stub/SVC placement (RETURNED only from the return stub, TRAPPED only from the trap stub with 1..14). +- QEMU gate: one boot of the qualification image built with `CK_SEED0B_TEST_ANCHOR=1 CK_OSC_LAUNCH_TEST=1` + (TEST ONLY; the flag is refused without the TEST anchor). Two TEST-signed units are in the sealed Store: the + spec's `a01_valid_min.unit` and the hand-assembled `l01_launch_fns.unit` (`tests/fixtures/osc_unit/launch/`, + built by `make-l01.sh` with the spec's generator helpers; its IR section is min.ir, so the IR does not + describe that code, which the spec says the kernel never checks). 44 launches, each printed as one + `osc_launch:` line carrying the label: RETURNED with exact values; refused wrong argument count, unknown name, + wrong case, slice outside the input window, misaligned cells; TRAPPED 3 and 14 through the trap service; trap + code 15 and a brk reached directly are OUTCOME_UNKNOWN (never TRAPPED); budget exhaustion (TICK_OVERRUN); + contained faults (null read, write to OscRt, jump into the stack, stack overflow), each followed by a + successful launch in the same boot; every task torn down (`page_tables_zeroed=1 slot_free=1`); a caller-owned + workspace keeping state across calls, a 23-page workspace touched at its last cell with state kept, and a + 33-page workspace refused 30 (over the 32-page cap); stack over the maximum (a06 1 MiB, l02 65552) refused LIMIT_EXCEEDED 14; kernel-address read, branch into workspace and into input (UXN), read just past the workspace end: each OUTCOME_UNKNOWN FAULT, contained, relaunch succeeds; x1..x29 zero at entry after a dirtying task; null, unaligned, state-overlapping and input-overlapping workspaces refused 30. +- Mutants (run by hand, restored): dropping the execute-never bit on data turns the W^X line, and the lines + after it, red; serving an SVC from unit context turns the host classification test red (no admitted unit can + execute an SVC, so only the host test reaches that lock). +- Labels: QEMU (aarch64 virt), TEST signer, not physical. Nothing here ran on a Spark. diff --git a/native/kernel/Makefile b/native/kernel/Makefile index ac8f5024..e09a5e1a 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -439,6 +439,14 @@ endif ifeq ($(strip $(CK_TEST_FWCFG_ARTIFACTS)),1) ART_TRUST_FLAGS += -DCK_TEST_FWCFG_ARTIFACTS=1 endif +# C3-3a: the launch self-test (core/osc_admit.c) runs scripted launches of the admitted units. TEST ONLY. +CK_OSC_LAUNCH_TEST ?= +ifeq ($(strip $(CK_OSC_LAUNCH_TEST)),1) +ifeq ($(strip $(CK_SEED0B_TEST_ANCHOR)),) +$(error CK_OSC_LAUNCH_TEST needs CK_SEED0B_TEST_ANCHOR=1 (it launches TEST-signed units)) +endif +ART_TRUST_FLAGS += -DCK_OSC_LAUNCH_TEST=1 +endif # Screen hold before reset (core/console.c ck_console_fb_hold): seconds the # GOP framebuffer console keeps the last report on screen before the PSCI @@ -469,7 +477,7 @@ CORE_C := $(BOOT)/efi_main.c $(BOOT)/efi_model.c $(BOOT)/efi_gop.c \ # P2 sealed-artifact loader: format/admission/receipt (artifact/), SHA-256 # (argus), Ed25519/SHA-512 (sig). Built into the core so every image carries # the loader; the TEST-anchor qualification build is CK_SEED0B_TEST_ANCHOR=1. -ART_C := $(KDIR)/core/artifact_loader.c $(KDIR)/core/osc_admit.c $(KDIR)/artifact/format.c $(KDIR)/artifact/admission.c \ +ART_C := $(KDIR)/core/artifact_loader.c $(KDIR)/core/osc_admit.c $(KDIR)/core/osc_task.c $(KDIR)/artifact/osc_launch.c $(KDIR)/artifact/format.c $(KDIR)/artifact/admission.c \ $(KDIR)/artifact/receipt.c $(KDIR)/artifact/osc_unit.c $(NATIVE)/argus/sha256.c $(NATIVE)/sig/sha512.c \ $(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c ART_INC := -I$(KDIR)/svc/compat -I$(KDIR)/artifact -I$(NATIVE)/sig -I$(NATIVE)/argus @@ -766,7 +774,7 @@ $(FULL_EFI): $(FULL_ELF) HOST_SRCS := $(KDIR)/core/fmt.c $(KDIR)/core/acpi.c $(KDIR)/core/smmu.c $(KDIR)/mm/frames.c \ $(KDIR)/mm/pt.c $(KDIR)/mm/heap.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c $(KDIR)/core/entropy.c \ $(KDIR)/core/handoff_check.c $(KDIR)/core/fbcon.c $(KDIR)/core/acpi_dev.c -TESTS := test_fmt test_frames test_pt test_acpi test_acpi_dev test_heap test_smmu test_sched test_ipc test_artifact test_osc_unit test_osc_admit test_entropy test_handoff test_fbcon \ +TESTS := test_fmt test_frames test_pt test_acpi test_acpi_dev test_heap test_smmu test_sched test_ipc test_artifact test_osc_unit test_osc_launch test_osc_admit test_entropy test_handoff test_fbcon \ test_continuity_codec test_continuity_resolve test_continuity_commit test_continuity_recovery test_continuity_geometry \ test_continuity_subject test_continuity_subject_provision HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/tests -I$(BOOT) @@ -873,7 +881,7 @@ $(OUT)/host/ck_udp_echo: $(KDIR)/tools/ck_udp_echo.c # Artifact library host test and the in-tree C artifact tool (pack, sign with # TEST keys, negative corpus, bundle, receipt check) used by the QEMU gate. -ART_HOST_SRCS := $(KDIR)/artifact/format.c $(KDIR)/artifact/admission.c $(KDIR)/artifact/receipt.c $(KDIR)/artifact/osc_unit.c \ +ART_HOST_SRCS := $(KDIR)/artifact/format.c $(KDIR)/artifact/admission.c $(KDIR)/artifact/receipt.c $(KDIR)/artifact/osc_unit.c $(KDIR)/artifact/osc_launch.c \ $(NATIVE)/argus/sha256.c $(NATIVE)/sig/sha512.c $(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c ART_HOST_INC := -I$(KDIR)/artifact -I$(NATIVE)/sig -I$(NATIVE)/argus ART_HOST_DEPS := $(ART_HOST_SRCS) $(wildcard $(KDIR)/artifact/*.h) $(ART_HDRS) @@ -894,6 +902,19 @@ $(OUT)/host-san/test_artifact: $(KDIR)/tests/test_artifact.c $(ART_HOST_DEPS) $( @mkdir -p $(dir $@) $(HOSTCC) $(HCFLAGS) $(SANFLAGS) $(ART_HOST_INC) -o $@ $< $(ART_HOST_SRCS) +# C3-3a launch: pure parts (artifact/osc_launch.c) plus the spec's own C reference for the argument rule. +$(OUT)/host/osc-launch-check: $(KDIR)/tests/fixtures/osc_unit/launch/osc-launch-check.c + @mkdir -p $(dir $@) + $(HOSTCC) -std=c99 -O1 -Wall -Wextra -Werror -o $@ $< + +$(OUT)/host/test_osc_launch: $(KDIR)/tests/test_osc_launch.c $(ART_HOST_DEPS) $(KDIR)/tests/ck_test.h $(OUT)/host/osc-launch-check + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(ART_HOST_INC) -DOSC_FIXTURE_DIR='"$(abspath $(KDIR)/tests/fixtures/osc_unit)"' -DOSC_LAUNCH_REF='"$(abspath $(OUT)/host/osc-launch-check)"' -o $@ $< $(ART_HOST_SRCS) + +$(OUT)/host-san/test_osc_launch: $(KDIR)/tests/test_osc_launch.c $(ART_HOST_DEPS) $(KDIR)/tests/ck_test.h $(OUT)/host/osc-launch-check + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) $(ART_HOST_INC) -DOSC_FIXTURE_DIR='"$(abspath $(KDIR)/tests/fixtures/osc_unit)"' -DOSC_LAUNCH_REF='"$(abspath $(OUT)/host/osc-launch-check)"' -o $@ $< $(ART_HOST_SRCS) + # osc_admit.c reporting (oversize Store entry): host test with ck_printf captured. $(OUT)/host/test_osc_admit: $(KDIR)/tests/test_osc_admit.c $(KDIR)/core/osc_admit.c $(ART_HOST_DEPS) $(KDIR)/tests/ck_test.h @mkdir -p $(dir $@) diff --git a/native/kernel/artifact/.crumb b/native/kernel/artifact/.crumb index f2813b2d..33073bfb 100644 --- a/native/kernel/artifact/.crumb +++ b/native/kernel/artifact/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T03:06:53Z", + "compiled_at": "2026-10-08T11:41:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:b7c024fa610faa124f2f26fd002815ea178595962647d544e98ea5a39735f214", + "digest": "sha256:90a737e620d9c654ae347aae26b4635b55477d4ef45c68ac10e983019f6af11c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 7, - "generated_at_commit": "527a980c361c87b144d368120e79df5f40d47926", - "source_tree": "sha256:2f960d8a13e9bdb120b2e6b930bd32f6eef5987d13ab71defaf704a9cba6fab4" + "files": 9, + "generated_at_commit": "f4c8d8dc15d73c80929fd3128caaa01d96ce3fb5", + "source_tree": "sha256:5aa3eb22f426eb9a99897468c10bfa95c06bc083f920fd3d2376dfe5888dced5" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/artifact/osc_launch.c b/native/kernel/artifact/osc_launch.c new file mode 100644 index 00000000..c607a7c7 --- /dev/null +++ b/native/kernel/artifact/osc_launch.c @@ -0,0 +1,172 @@ +/* osc_launch.c -- see osc_launch.h. Pure. */ +#include "osc_launch.h" + +#define MAXR 6u + +static int is_slice(unsigned k) { return k == 11 || k == 12; } + +static int fits(unsigned k, uint64_t v) +{ + switch (k) { + case 1: return v <= 1; + case 2: return v <= 0xff; + case 3: return v <= 0xffff; + case 4: return v <= 0xffffffffull; + case 6: return (int64_t)v == (int8_t)v; + case 7: return (int64_t)v == (int16_t)v; + case 8: return (int64_t)v == (int32_t)v; + default: return 1; /* 5, 9 and the two registers of a slice */ + } +} + +int osc_launch_args_ok(const uint8_t *kinds, unsigned nregs, const uint64_t *args, unsigned nargs) +{ + if (nregs > MAXR || nargs != nregs) + return 0; + for (unsigned p = 0; p < nregs; p++) + if (!is_slice(kinds[p]) && !fits(kinds[p], args[p])) + return 0; + for (unsigned p = 0; p + 1 < nregs; p++) { + if (!is_slice(kinds[p])) + continue; + uint64_t ptr = args[p], n = args[p + 1], sz = n * (kinds[p] == 12 ? 8u : 1u); + if (kinds[p] == 12 && (n > UINT64_MAX / 8 || (n && (ptr & 7)))) + return 0; + if ((n && !ptr) || sz > UINT64_MAX - ptr) + return 0; + for (unsigned q = 0; q + 1 < nregs; q++) { + if (q == p || !is_slice(kinds[q])) + continue; + if (kinds[p] != 12 && kinds[q] != 12) + continue; + uint64_t qn = args[q + 1], qsz = qn * (kinds[q] == 12 ? 8u : 1u); + if (!sz || !qn || (kinds[q] == 12 && qn > UINT64_MAX / 8) || qsz > UINT64_MAX - args[q]) + continue; + if (ptr < args[q] + qsz && args[q] < ptr + sz) + return 0; + } + } + return 1; +} + +static int inside(uint64_t ptr, uint64_t size, uint64_t base, uint64_t len) +{ + return ptr >= base && ptr - base <= len && size <= len - (ptr - base); +} + +int osc_launch_ranges_owned(const uint8_t *kinds, unsigned nregs, const uint64_t *args, uint64_t in_va, + uint64_t in_len, uint64_t ws_va, uint64_t ws_len) +{ + for (unsigned p = 0; p + 1 < nregs; p++) { + if (!is_slice(kinds[p])) + continue; + uint64_t ptr = args[p], n = args[p + 1]; + if (n == 0) + continue; /* a zero-length range is never dereferenced */ + if (kinds[p] == 12) { + if (n > UINT64_MAX / 8 || !inside(ptr, n * 8, ws_va, ws_len)) + return 0; + } else if (!inside(ptr, n, in_va, in_len)) { + return 0; + } + } + return 1; +} + +uint64_t osc_launch_budget(uint64_t unit_ticks, uint64_t caller_cap) +{ + return caller_cap && caller_cap < unit_ticks ? caller_cap : unit_ticks; +} + +int osc_launch_budget_expired(uint64_t seen, uint64_t budget) +{ + return seen >= budget; +} + +static int fault_class(uint64_t ec) +{ + switch (ec) { + case 0x00: /* unknown / undefined instruction */ + case 0x07: /* FP or SIMD access */ + case 0x0e: /* illegal execution state */ + case 0x18: /* MSR, MRS or system instruction */ + case 0x20: /* instruction abort from EL0 */ + case 0x22: /* PC alignment */ + case 0x24: /* data abort from EL0 */ + case 0x26: /* SP alignment */ + case 0x3c: /* brk */ + return 1; + default: + return 0; + } +} + +static void unknown(struct osc_result *r, uint8_t why) +{ + r->cls = OSC_RES_UNKNOWN; + r->unknown_reason = why; +} + +void osc_launch_classify(const struct osc_event *e, uint64_t rt_code_va, struct osc_result *r) +{ + r->cls = 0; + r->trap_code = r->unknown_reason = r->refused_code = 0; + r->value = 0; + switch (e->kind) { + case OSC_EV_SVC: { + uint64_t imm = e->esr & 0xffff, ec = (e->esr >> 26) & 0x3f; + uint64_t site = e->elr - 4; + uint64_t off = site - rt_code_va; + if (ec != 0x15 || e->elr < 4 || site < rt_code_va || off >= (uint64_t)OSC_RT_STUBS * OSC_RT_STUB_BYTES || + off % OSC_RT_STUB_BYTES || imm != off / OSC_RT_STUB_BYTES) { + unknown(r, OSC_UNK_FAULT); /* an SVC outside the runtime entry stubs is refused (9.1.1 item 1) */ + return; + } + if (imm == OSC_SVC_RETURN) { + r->cls = OSC_RES_RETURNED; + r->value = e->x0; + } else if (imm == OSC_SVC_TRAP) { + if (e->x1 >= 1 && e->x1 <= OSC_TRAP_MAX) { + r->cls = OSC_RES_TRAPPED; + r->trap_code = (uint8_t)e->x1; + } else { + unknown(r, OSC_UNK_TRAP_CODE_UNKNOWN); + } + } else { + unknown(r, OSC_UNK_OTHER); /* alloc, arenas, pools: not provided by this cut */ + } + return; + } + case OSC_EV_SYNC: + unknown(r, fault_class((e->esr >> 26) & 0x3f) ? OSC_UNK_FAULT : OSC_UNK_OTHER); + return; + case OSC_EV_BUDGET: + unknown(r, OSC_UNK_TICK_OVERRUN); + return; + case OSC_EV_LOST: + unknown(r, OSC_UNK_LAUNCH_LOST); + return; + default: + unknown(r, OSC_UNK_OTHER); + return; + } +} + +int osc_launch_ws_pages_ok(uint64_t pages) +{ + return pages <= OSC_WS_MAX_PAGES; +} + +int osc_launch_stack_ok(uint64_t declared, uint64_t hard_max) +{ + return declared <= hard_max; +} + +int osc_launch_disjoint(uint64_t a, uint64_t alen, uint64_t b, uint64_t blen) +{ + if (alen == 0 || blen == 0) + return 1; + if (a + alen < a || b + blen < b) /* a wrapped range is never disjoint from anything */ + return 0; + return a + alen <= b || b + blen <= a; +} diff --git a/native/kernel/artifact/osc_launch.h b/native/kernel/artifact/osc_launch.h new file mode 100644 index 00000000..9808e0a2 --- /dev/null +++ b/native/kernel/artifact/osc_launch.h @@ -0,0 +1,89 @@ +/* osc_launch.h -- the pure parts of launching an admitted OSC unit (OSC_UNIT_ARTIFACT.md section 9): + * the argument rule (9.2), range ownership (9.1.1 item 4), the ticks budget, and the classification + * of what an EL0 unit did into the four result classes (9.3). No globals, no I/O, no MMU: host tested + * (tests/test_osc_launch.c) and used by core/osc_launch.c, which maps and runs the task. + * QEMU only so far; nothing here is physical. */ +#ifndef AIENOS_CK_OSC_LAUNCH_H +#define AIENOS_CK_OSC_LAUNCH_H +#include +#include + +/* The OscRt vtable of runtime_abi_version 1 has 13 entries at offsets 0..96 (osc_rt.h); entry i is + * reached through the runtime stub i. Stub 2 is `trap` (offset 16). Stub 13 is not in the vtable: it is + * the return address the launcher hands the entry function in x30. */ +#define OSC_RT_SERVICES 13u +#define OSC_SVC_TRAP 2u +#define OSC_SVC_RETURN 13u +#define OSC_RT_STUBS 14u +#define OSC_RT_STUB_BYTES 8u /* `svc #i` then a spare word */ +#define OSC_TRAP_MAX 14u + +/* Kernel cap on a caller-owned workspace: 32 pages = 128 KiB. It bounds the user pages and page-table slots one + * task can map (the workspace window is 32 of the 512 leaf entries of its L3 table, clear of the stack), and the + * bss a caller must set aside. Large enough for the OSH resumable workspace (11,456 cells = 23 pages). The size is + * the caller's choice and never comes from the container. */ +#define OSC_WS_MAX_PAGES 32u + +/* Section 9.3: four classes, closed. */ +enum { OSC_RES_RETURNED = 1, OSC_RES_TRAPPED = 2, OSC_RES_REFUSED = 3, OSC_RES_UNKNOWN = 4 }; +/* unknown_reason, section 9.3 (diagnostic only; never changes the class). */ +enum { OSC_UNK_FAULT = 1, OSC_UNK_TICK_OVERRUN = 2, OSC_UNK_LAUNCH_LOST = 3, OSC_UNK_TRAP_CODE_UNKNOWN = 4, + OSC_UNK_OTHER = 255 }; + +struct osc_result { + uint8_t cls; /* OSC_RES_* */ + uint8_t trap_code; /* TRAPPED: 1..14 */ + uint8_t unknown_reason; /* OUTCOME_UNKNOWN: OSC_UNK_*; 0 for every other class */ + uint8_t refused_code; /* REFUSED_AT_ADMISSION: section 8.3 code (40, 41, 30...) */ + uint64_t value; /* RETURNED: x0 */ + uint64_t ticks; /* scheduler ticks the unit ran (diagnostic) */ +}; + +/* Section 9.2 items 1 to 4, exactly the rule of tools/osc-launch-check.c. kinds are the entry + * record's reg_kind[0..nregs); args are the register values in order; nargs must equal nregs. + * 1 = acceptable, 0 = LAUNCH_ARG_SHAPE (41). */ +int osc_launch_args_ok(const uint8_t *kinds, unsigned nregs, const uint64_t *args, unsigned nargs); + +/* Section 9.1.1 item 4 (ownership, after the shape check passes): every non-empty `bytes` range lies + * wholly in the read-only input window [in_va, in_va+in_len), every non-empty `cells` range wholly in the + * caller's writable workspace window [ws_va, ws_va+ws_len). 1 = owned. */ +int osc_launch_ranges_owned(const uint8_t *kinds, unsigned nregs, const uint64_t *args, uint64_t in_va, + uint64_t in_len, uint64_t ws_va, uint64_t ws_len); + +/* 1 if the byte ranges [a, a+alen) and [b, b+blen) do not overlap (an empty range overlaps nothing; a + * range that wraps the address space overlaps everything, so 0). */ +int osc_launch_disjoint(uint64_t a, uint64_t alen, uint64_t b, uint64_t blen); + +/* 1 if a signer-declared max_stack_bytes is within the launcher hard maximum (else LIMIT_EXCEEDED, 14). */ +int osc_launch_stack_ok(uint64_t declared, uint64_t hard_max); + +/* 1 if a workspace of this many pages is allowed (0 = none, up to OSC_WS_MAX_PAGES). */ +int osc_launch_ws_pages_ok(uint64_t pages); + +/* The ticks the task may run: the unit's declared cpu_ticks, lowered (never raised) by a nonzero caller + * cap. One tick is one scheduler timer interrupt (10 ms, CNTFRQ/100). */ +uint64_t osc_launch_budget(uint64_t unit_ticks, uint64_t caller_cap); +/* 1 once `seen` ticks have been delivered while the unit ran and that reaches the budget. */ +int osc_launch_budget_expired(uint64_t seen, uint64_t budget); + +/* What the kernel observed while the unit ran. */ +enum { OSC_EV_SVC = 1, OSC_EV_SYNC = 2, OSC_EV_BUDGET = 3, OSC_EV_LOST = 4 }; +struct osc_event { + unsigned kind; /* OSC_EV_* */ + uint64_t esr, elr; /* ESR_EL1 and ELR_EL1 of the exception (SVC and SYNC) */ + uint64_t x0, x1; /* unit registers at the exception */ +}; +/* Section 9.3 and 9.1.1: classify one terminating event into *r (cls, trap_code, unknown_reason, value). + * rt_code_va is the unit-space address of runtime stub 0. + * - SVC from a runtime stub (elr-4 is stub i and the immediate is i): return stub -> RETURNED(x0); + * trap stub with x1 in 1..14 -> TRAPPED(x1); with another x1 -> UNKNOWN(TRAP_CODE_UNKNOWN); any + * other stub (a runtime service this cut does not provide) -> UNKNOWN(OTHER). + * - SVC from anywhere else: refused, UNKNOWN(FAULT). The unit has no system calls (9.1.1 item 1). + * - SYNC with a CPU fault class (data or instruction abort, brk, undefined, alignment, FP, system + * register) -> UNKNOWN(FAULT). A brk reached directly is a fault, never TRAPPED (8.4). + * - SYNC with any other class -> UNKNOWN(OTHER); BUDGET -> UNKNOWN(TICK_OVERRUN); + * LOST -> UNKNOWN(LAUNCH_LOST). + * Nothing is ever mapped to RETURNED except the return stub. */ +void osc_launch_classify(const struct osc_event *e, uint64_t rt_code_va, struct osc_result *r); + +#endif diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb index e01ddaaf..20e247eb 100644 --- a/native/kernel/core/.crumb +++ b/native/kernel/core/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T11:00:47Z", + "compiled_at": "2026-10-08T11:41:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:fd9456ff602f0eaa5937f04b46762e8dd4c2692707a6b78076b3da4667f4b4ff", + "digest": "sha256:a4a7b49093c9c40aaa7238ec33f45790d68e3a52613720c6ba73609c1b3cefab", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 33, - "generated_at_commit": "bde85f8671a90d33a46667a5d915cb948035954a", - "source_tree": "sha256:d28907a0a28224254c6733b54992ea98304de1cfb97262aa62869d65c3fcc4d5" + "files": 35, + "generated_at_commit": "f4c8d8dc15d73c80929fd3128caaa01d96ce3fb5", + "source_tree": "sha256:5305d29267aaab8654b75212efef023d95f809ba3fa0913c58fc93f4c4c9d9ab" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/osc_admit.c b/native/kernel/core/osc_admit.c index f0e80722..3b5c4377 100644 --- a/native/kernel/core/osc_admit.c +++ b/native/kernel/core/osc_admit.c @@ -59,6 +59,186 @@ static void policy(struct osc_policy *p) #endif } + +#ifdef CK_OSC_LAUNCH_TEST +/* ====================================================================================================== + * C3-3a launch self-test (TEST ONLY, qualification build with CK_OSC_LAUNCH_TEST=1). + * Runs a fixed script of launches over the admitted units the Store handed over and prints one + * "osc_launch:" line each. QEMU (aarch64 virt), TEST signer, not physical. + * ==================================================================================================== */ +#include "osc_task.h" +#define LT_UNITS 4 +#define LT_BYTES 8192 +static struct { + char name[48]; + uint8_t bytes[LT_BYTES]; + size_t len; + struct osc_accept acc; +} lt_unit[LT_UNITS]; +static unsigned lt_n; + +static int lt_streq(const char *a, const char *b) +{ + size_t n = strlen(a); + return n == strlen(b) && memcmp(a, b, n) == 0; +} + +static void lt_save(const char *name, const uint8_t *b, size_t len) +{ + if (lt_n >= LT_UNITS || len > LT_BYTES) + return; + unsigned i = 0; + while (name[i] && i < sizeof lt_unit[0].name - 1) { + lt_unit[lt_n].name[i] = name[i]; + i++; + } + lt_unit[lt_n].name[i] = 0; + memcpy(lt_unit[lt_n].bytes, b, len); + lt_unit[lt_n].len = len; + lt_unit[lt_n].acc = acc; + lt_n++; +} + +#define IN_PTR (1ull << 62) /* placeholders for the task's input and workspace windows */ +#define WS_PTR (1ull << 63) +#define KERN_PTR (1ull << 61) /* an address in the kernel image (mapped EL1-only in the task address space) */ +struct lt_step { + const char *unit, *fn; + unsigned nargs; + uint64_t a[3]; + const char *in; + int ws; /* 0 none, 1..2 which caller workspace */ + uint64_t cap; +}; + +extern void ck_osc_state_range(uint64_t *addr, uint64_t *len); +static uint8_t lt_ws_mem1[4 * 4096], lt_ws_mem2[4 * 4096], lt_ws_mem3[23 * 4096], lt_ws_mem4[33 * 4096] + __attribute__((aligned(4096))); +static struct ck_osc_ws lt_ws[8] = { { lt_ws_mem1, 4 }, { lt_ws_mem2, 4 }, { lt_ws_mem3, 23 }, { lt_ws_mem4, 33 }, + { 0, 1 }, { lt_ws_mem1 + 8, 1 }, { 0, 1 }, { lt_ws_mem2, 4 } }; +static unsigned lt_counts[5]; + +static void lt_run(const struct lt_step *s) +{ + for (unsigned u = 0; u < lt_n; u++) { + if (!lt_streq(lt_unit[u].name, s->unit)) + continue; + struct ck_osc_launch_req rq; + memset(&rq, 0, sizeof rq); + rq.name = s->fn; + rq.name_len = strlen(s->fn); + rq.nargs = s->nargs; + rq.max_ticks = s->cap; + for (unsigned i = 0; i < s->nargs; i++) { + rq.args[i] = s->a[i]; + if (s->a[i] & IN_PTR) + rq.args[i] = ck_osc_va_in() + (s->a[i] & 0xffffff); + else if (s->a[i] & WS_PTR) + rq.args[i] = ck_osc_va_ws() + (s->a[i] & 0xffffff); + else if (s->a[i] & KERN_PTR) + rq.args[i] = (uint64_t)(uintptr_t)<_counts; + } + if (s->in) { + rq.in = (const uint8_t *)s->in; + rq.in_len = strlen(s->in); + } + if (s->ws) + rq.ws = <_ws[s->ws - 1]; + struct osc_result r; + struct ck_osc_launch_info info; + ck_osc_launch(lt_unit[u].bytes, lt_unit[u].len, <_unit[u].acc, &rq, &r, &info); + char rs[96], as[80]; + ck_osc_result_str(&r, rs, sizeof rs); + unsigned n = 0; + as[0] = 0; + for (unsigned i = 0; i < s->nargs && n < sizeof as - 24; i++) { + uint64_t v = s->a[i]; + if (v & IN_PTR) + n += (unsigned)ck_snprintf(as + n, sizeof as - n, "%sin+%u", i ? "," : "", (unsigned)(v & 0xffffff)); + else if (v & WS_PTR) + n += (unsigned)ck_snprintf(as + n, sizeof as - n, "%sws+%u", i ? "," : "", (unsigned)(v & 0xffffff)); + else if (v & KERN_PTR) + n += (unsigned)ck_snprintf(as + n, sizeof as - n, "%skernel", i ? "," : ""); + else + n += (unsigned)ck_snprintf(as + n, sizeof as - n, "%s%llu", i ? "," : "", (unsigned long long)v); + } + ck_printf("osc_launch: %s %s(%s) -> %s ticks=%llu budget=%llu pages_mapped=%u page_tables_zeroed=%u slot_free=%u; " + "QEMU (aarch64 virt), TEST signer, not physical\n", + s->unit, s->fn, as, rs, (unsigned long long)r.ticks, (unsigned long long)info.budget, + info.pages_mapped, (unsigned)info.tables_zeroed, (unsigned)info.slot_free_after); + lt_counts[r.cls]++; + return; + } + ck_printf("osc_launch: %s %s -> NOT_RUN (unit was not admitted)\n", s->unit, s->fn); +} + +static void lt_all(void) +{ + uint64_t sa, sl; + ck_osc_state_range(&sa, &sl); + lt_ws[6].mem = (uint8_t *)(uintptr_t)sa; /* a workspace aimed at the launcher's own state */ + lt_ws[6].pages = 1; + memcpy(lt_ws_mem2 + 64, "Zeta", 5); /* an input buffer that lies inside workspace 8 (index 7) */ + *(uint32_t *)(lt_ws_mem1 + 512) = 0xd65f03c0u; /* a valid `ret` in workspace 1, cell 64, for jump_ws */ + static const struct lt_step steps[] = { + { "a01_valid_min.unit", "add", 2, { 1000000007, 998244353 }, 0, 0, 0 }, + { "a01_valid_min.unit", "add", 1, { 5 }, 0, 0, 0 }, + { "a01_valid_min.unit", "nosuch", 0, { 0 }, 0, 0, 0 }, + { "a01_valid_min.unit", "ADD", 2, { 1, 2 }, 0, 0, 0 }, + { "a01_valid_min.unit", "first_byte", 2, { IN_PTR, 4 }, "Zeta", 0, 0 }, + { "a01_valid_min.unit", "first_byte", 2, { 0x1000, 16 }, "Zeta", 0, 0 }, + { "l01_launch_fns.unit", "trap", 1, { 3 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "trap", 1, { 14 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "trap", 1, { 15 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "bare_brk", 0, { 0 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "spin", 0, { 0 }, 0, 0, 5 }, + { "a01_valid_min.unit", "add", 2, { 40, 2 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "peek0", 0, { 0 }, 0, 0, 0 }, + { "a01_valid_min.unit", "add", 2, { 20, 22 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "poke_rt", 0, { 0 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "exec_stack", 0, { 0 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "overflow", 0, { 0 }, 0, 0, 0 }, + { "a01_valid_min.unit", "add", 2, { 6, 36 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR, 1 }, 0, 1, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR, 1 }, 0, 1, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR, 1 }, 0, 1, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR, 1 }, 0, 2, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 4, 1 }, 0, 1, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 94200, 1 }, 0, 3, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 94200, 1 }, 0, 3, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR, 1 }, 0, 4, 0 }, + { "a06_valid_limits_at_max.unit", "add", 2, { 1, 2 }, 0, 0, 0 }, + { "l02_stack_over.unit", "peek0", 0, { 0 }, 0, 0, 0 }, + { "a01_valid_min.unit", "add", 2, { 3, 4 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "peek_kernel", 1, { KERN_PTR }, 0, 0, 0 }, + { "a01_valid_min.unit", "add", 2, { 5, 6 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "jump_ws", 2, { WS_PTR | 512, 1 }, 0, 1, 0 }, + { "a01_valid_min.unit", "add", 2, { 7, 8 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "jump_in", 2, { IN_PTR, 4 }, "\xc0\x03\x5f\xd6", 0, 0 }, + { "a01_valid_min.unit", "add", 2, { 9, 10 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "dirty", 0, { 0 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "regs_or", 0, { 0 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "touch_past", 2, { WS_PTR | 16376, 1 }, 0, 1, 0 }, + { "a01_valid_min.unit", "add", 2, { 11, 12 }, 0, 0, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 8, 1 }, 0, 5, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 16, 1 }, 0, 6, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 24, 1 }, 0, 7, 0 }, + { "l01_launch_fns.unit", "counter", 2, { WS_PTR | 32, 1 }, (const char *)(lt_ws_mem2 + 64), 8, 0 }, + { "a01_valid_min.unit", "add", 2, { 13, 14 }, 0, 0, 0 }, + }; + ck_printf("osc_launch_policy: units=%u code_max=%u stack_max=%u in_max=%u ws_max=%u pages; 1 tick = 10 ms; " + "QEMU (aarch64 virt), TEST signer, not physical\n", + lt_n, (unsigned)CK_OSC_CODE_MAX_BYTES, (unsigned)CK_OSC_STACK_MAX_BYTES, (unsigned)CK_OSC_IN_MAX_BYTES, + (unsigned)OSC_WS_MAX_PAGES); + for (unsigned i = 0; i < sizeof steps / sizeof steps[0]; i++) + lt_run(&steps[i]); + ck_printf("osc_launches: returned=%u trapped=%u refused=%u unknown=%u; QEMU (aarch64 virt), TEST signer, not " + "physical\n", + lt_counts[OSC_RES_RETURNED], lt_counts[OSC_RES_TRAPPED], lt_counts[OSC_RES_REFUSED], + lt_counts[OSC_RES_UNKNOWN]); +} +#endif + int ck_osc_is_unit(const uint8_t *b, size_t len) { return b && len >= 8 && memcmp(b, "OSCUNIT\0", 8) == 0; @@ -85,6 +265,9 @@ unsigned ck_osc_candidate(const char *name, const uint8_t *b, size_t len) hex(d, acc.unit_digest, 32); hex(i, acc.ir_sha256, 32); accepted++; +#ifdef CK_OSC_LAUNCH_TEST + lt_save(name, b, len); +#endif ck_printf("osc_unit: %s ACCEPT unit_digest=%s program_id=%s funcs=%u caps=%u signer=%s\n", name, d, i, (unsigned)acc.function_count, (unsigned)acc.cap_count, acc.signer_class == OSC_SIGNER_TEST ? "TEST" : "OWNER"); @@ -107,6 +290,14 @@ void ck_osc_oversize(const char *name, uint64_t len) void ck_osc_summary(void) { if (seen || oversize) +#ifdef CK_OSC_LAUNCH_TEST + { + ck_printf("osc_units: seen=%u accepted=%u refused=%u oversize=%u (admission; launches follow)\n", seen, accepted, + refused, oversize); + lt_all(); + } +#else ck_printf("osc_units: seen=%u accepted=%u refused=%u oversize=%u (admission only, nothing launched)\n", seen, accepted, refused, oversize); +#endif } diff --git a/native/kernel/core/osc_task.c b/native/kernel/core/osc_task.c new file mode 100644 index 00000000..4797a72c --- /dev/null +++ b/native/kernel/core/osc_task.c @@ -0,0 +1,353 @@ +/* osc_task.c -- launch an admitted OSC unit as an EL0 task. See osc_task.h and docs/osc-launch.md. + * + * Address space of the task (all user VAs are base + offset, base = a free L0 slot of the kernel root, so + * kernel mappings stay EL1-only; every user page is non-global): + * 0x001000 OscRt table EL0 read-only, never executable (13 pointers into the runtime stubs) + * 0x002000 runtime stubs EL0 read, execute, never writable (`svc #i`; the only SVCs a unit may reach) + * 0x010000 unit code EL0 read, execute, never writable + * 0x200000 input window EL0 read-only, never executable (the `bytes` arguments) + * 0x210000 workspace EL0 read-write, never executable (the `cells` arguments, caller-owned, 0..32 pages) + * ..0x400000 stack EL0 read-write, never executable (top down; the page below it is unmapped) + * Writable and executable never coincide (W^X). Everything the task can reach is private to the slot + * except the caller's workspace. */ +#include "arch.h" +#include "ck_internal.h" +#include "fmt.h" +#include "osc_task.h" +#include "pt.h" +#include "sha256.h" + + +/* ---- vector hooks (arch/exception.c) and asm (arch/m3.S) ---- */ +extern struct ck_frame *(*ck_tick_switch)(struct ck_frame *f); +extern int (*ck_lower_sync)(struct ck_frame *f, uint64_t esr); +void ck_el0_enter(uint64_t entry, uint64_t user_sp, const uint64_t regs[31]); +void ck_el0_resume(void); + +#define PTE_TABLE 3ull +#define PTE_PAGE 3ull +#define PTE_AP_EL0_RW (1ull << 6) +#define PTE_AP_EL0_RO (3ull << 6) +#define PTE_NG (1ull << 11) + +#define OFF_RT_TAB 0x001000ull +#define OFF_RT_CODE 0x002000ull +#define OFF_CODE 0x010000ull +#define OFF_IN 0x200000ull +#define OFF_WS 0x210000ull +#define OFF_STACK_TOP 0x400000ull + +struct slot { + uint64_t l0[512], l1[512], l2[512], l3a[512], l3b[512]; + uint8_t rt_tab[4096], rt_code[4096], in[4096]; + uint8_t code[CK_OSC_CODE_MAX_BYTES]; + uint8_t stack[CK_OSC_STACK_MAX_BYTES]; + int used; +} __attribute__((aligned(4096))); +static struct slot slot0; + +static uint64_t base_va; + +static uint64_t get_base(void) +{ + if (base_va) + return base_va; + const uint64_t *l0 = (const uint64_t *)(uintptr_t)ck_mm_report()->root; + for (unsigned i = 1; i < 256; i++) + if (!l0[i]) { + base_va = (uint64_t)i << 39; + break; + } + return base_va; +} + +uint64_t ck_osc_va_in(void) { return get_base() ? base_va + OFF_IN : 0; } +uint64_t ck_osc_va_ws(void) { return get_base() ? base_va + OFF_WS : 0; } + +static void clean_range(const void *p, size_t len, int icache) +{ + uint64_t ctr = ck_rd(ctr_el0); + uint64_t dline = 4ull << ((ctr >> 16) & 0xf), iline = 4ull << (ctr & 0xf); + uint64_t a = (uint64_t)(uintptr_t)p, end = a + len; + for (uint64_t x = a & ~(dline - 1); x < end; x += dline) + __asm__ volatile("dc civac, %0" ::"r"(x) : "memory"); + ck_dsb_ish(); + if (icache) { + for (uint64_t x = a & ~(iline - 1); x < end; x += iline) + __asm__ volatile("ic ivau, %0" ::"r"(x) : "memory"); + ck_dsb_ish(); + } + ck_isb(); +} + +static void swap_ttbr0(uint64_t ttbr0) +{ + ck_dsb_ish(); + ck_wr(ttbr0_el1, ttbr0); + ck_isb(); + __asm__ volatile("tlbi vmalle1" ::: "memory"); + ck_dsb_ish(); + ck_isb(); +} + +/* ---- page attributes: the W^X rules live here ---- */ +#define COMMON (CK_PTE_ATTRIDX(CK_MAIR_IDX_NORMAL) | CK_PTE_SH_INNER | CK_PTE_AF | PTE_NG | CK_PTE_PXN) +#define DATA_XN CK_PTE_UXN /* data, stack and input are never executable at EL0 */ +#define ATTR_RX (PTE_PAGE | PTE_AP_EL0_RO | COMMON) /* read + execute */ +#define ATTR_RO (PTE_PAGE | PTE_AP_EL0_RO | COMMON | DATA_XN) /* read only, no execute */ +#define ATTR_RW (PTE_PAGE | PTE_AP_EL0_RW | COMMON | DATA_XN) /* read + write, no execute */ + +static void map(uint64_t *l3, unsigned idx, const void *page, uint64_t attr) +{ + l3[idx] = (uint64_t)(uintptr_t)page | attr; +} + +static unsigned count_mapped(const struct slot *s) +{ + unsigned n = 0; + for (unsigned i = 0; i < 512; i++) + n += (unsigned)((s->l3a[i] & 1) + (s->l3b[i] & 1)); + return n; +} + +/* ---- the run ---- */ +static struct { + int active, done; + uint64_t ticks, budget, rt_code_va; + struct osc_result res; +} run; + +static void end_task(struct ck_frame *f, const struct osc_event *e) +{ + osc_launch_classify(e, run.rt_code_va, &run.res); + run.done = 1; + f->elr = (uint64_t)(uintptr_t)ck_el0_resume; + f->spsr = 0x3c5; /* EL1h, DAIF masked */ +} + +static int launch_sync(struct ck_frame *f, uint64_t esr) +{ + if (!run.active || run.done || (f->spsr & 0xf) != 0) + return -1; + struct osc_event e = { ((esr >> 26) & 0x3f) == 0x15 ? OSC_EV_SVC : OSC_EV_SYNC, esr, f->elr, f->x[0], + f->x[1] }; + end_task(f, &e); + return 0; +} + +static struct ck_frame *launch_tick(struct ck_frame *f) +{ + if (!run.active || run.done || (f->spsr & 0xf) != 0) + return f; + run.ticks++; + if (osc_launch_budget_expired(run.ticks, run.budget)) { + struct osc_event e = { OSC_EV_BUDGET, 0, f->elr, 0, 0 }; + end_task(f, &e); + } + return f; +} + +static void refuse(struct osc_result *res, unsigned code) +{ + memset(res, 0, sizeof *res); + res->cls = OSC_RES_REFUSED; + res->refused_code = (uint8_t)code; +} + +void ck_osc_launch(const uint8_t *unit, size_t unit_len, const struct osc_accept *a, + const struct ck_osc_launch_req *rq, struct osc_result *res, struct ck_osc_launch_info *info) +{ + struct ck_osc_launch_info local; + if (!info) + info = &local; + memset(info, 0, sizeof *info); + info->slot_free_after = 1; + info->tables_zeroed = 1; /* a refusal built no tables */ + refuse(res, OSC_RESOURCE_UNAVAILABLE); + int fi = osc_unit_lookup(a, rq->name, rq->name_len); + if (fi < 0) { + refuse(res, OSC_LAUNCH_BAD_ENTRY); + return; + } + const struct osc_entry *e = &a->entry[fi]; + /* spec 8.2 step 16: a signer-declared budget above a launcher hard maximum is LIMIT_EXCEEDED, before any + * reservation. max_stack_bytes is the only declared budget the launcher bounds: cpu_ticks is only lowered by + * the caller cap (max_ticks), and pool_slots is not bounded because no pool service is provided (a call to + * one ends OUTCOME_UNKNOWN). Real reservation failures below keep 30. */ + if (!osc_launch_stack_ok(a->max_stack_bytes, CK_OSC_STACK_MAX_BYTES)) { + refuse(res, OSC_LIMIT_EXCEEDED); + return; + } + uint64_t in_va = ck_osc_va_in(), ws_va = ck_osc_va_ws(); + /* The workspace is mapped read-write into EL0, so it must be memory the caller owns: refuse (30, nothing + * mapped) a range over the cap, null, not page aligned, or overlapping the launcher's own state (slot0: page + * tables, code copy, runtime, stack) or the caller's input buffer. The kernel has no allowed region for + * workspaces, so ownership beyond that is the caller's promise (osc_task.h). */ + if (rq->ws && rq->ws->pages && osc_launch_ws_pages_ok(rq->ws->pages) && rq->ws->mem && + (!osc_launch_disjoint((uintptr_t)rq->ws->mem, (uint64_t)rq->ws->pages * CK_OSC_PAGE, (uintptr_t)&slot0, sizeof slot0) || + !osc_launch_disjoint((uintptr_t)rq->ws->mem, (uint64_t)rq->ws->pages * CK_OSC_PAGE, (uintptr_t)rq->in, rq->in_len))) { + refuse(res, OSC_RESOURCE_UNAVAILABLE); + return; + } + if (rq->ws && (!osc_launch_ws_pages_ok(rq->ws->pages) || (rq->ws->pages && (!rq->ws->mem || ((uintptr_t)rq->ws->mem & 4095))))) { + refuse(res, OSC_RESOURCE_UNAVAILABLE); /* workspace over the cap or unusable: nothing ran */ + return; + } + uint64_t ws_len = rq->ws ? (uint64_t)rq->ws->pages * CK_OSC_PAGE : 0; + if (rq->nargs > 6 || !osc_launch_args_ok(e->reg_kind, e->nregs, rq->args, rq->nargs) || + !osc_launch_ranges_owned(e->reg_kind, e->nregs, rq->args, in_va, rq->in_len, ws_va, ws_len)) { + refuse(res, OSC_LAUNCH_ARG_SHAPE); + return; + } + /* reservation: code size, input size, busy slot, no base: RESOURCE_UNAVAILABLE and nothing runs */ + uint64_t base = get_base(); + uint32_t stack = a->max_stack_bytes; + if (!base || slot0.used || run.active || a->code_len > CK_OSC_CODE_MAX_BYTES || + rq->in_len > CK_OSC_IN_MAX_BYTES || (rq->in_len && !rq->in) || (uint64_t)a->code_off + a->code_len > unit_len || + e->code_offset >= a->code_len || (e->code_offset & 3)) + return; + struct slot *s = &slot0; + s->used = 1; + /* private copy of the code, hashed again before it is made executable (spec 8.2) */ + memset(s->code, 0, sizeof s->code); + memcpy(s->code, unit + a->code_off, a->code_len); + uint8_t dig[32]; + sha256_hash(s->code, a->code_len, dig); + if (memcmp(dig, a->code_sha256, 32) != 0) { + memset(s->code, 0, sizeof s->code); + s->used = 0; + refuse(res, OSC_CODE_HASH_MISMATCH); + return; + } + /* tables: kernel root copied (EL1-only), one free L0 slot chained to two L3 tables */ + memcpy(s->l0, (const void *)(uintptr_t)ck_mm_report()->root, sizeof s->l0); + unsigned idx = (unsigned)(base >> 39); + memset(s->l1, 0, sizeof s->l1); + memset(s->l2, 0, sizeof s->l2); + memset(s->l3a, 0, sizeof s->l3a); + memset(s->l3b, 0, sizeof s->l3b); + s->l0[idx] = (uint64_t)(uintptr_t)s->l1 | PTE_TABLE; + s->l1[0] = (uint64_t)(uintptr_t)s->l2 | PTE_TABLE; + s->l2[0] = (uint64_t)(uintptr_t)s->l3a | PTE_TABLE; + s->l2[1] = (uint64_t)(uintptr_t)s->l3b | PTE_TABLE; + uint64_t rt_code_va = base + OFF_RT_CODE, code_va = base + OFF_CODE, stack_top = base + OFF_STACK_TOP; + /* runtime: OscRt table (13 pointers) and the stubs `svc #i` */ + memset(s->rt_tab, 0, sizeof s->rt_tab); + memset(s->rt_code, 0, sizeof s->rt_code); + for (unsigned i = 0; i < OSC_RT_SERVICES; i++) + ((uint64_t *)(void *)s->rt_tab)[i] = rt_code_va + (uint64_t)i * OSC_RT_STUB_BYTES; + for (unsigned i = 0; i < OSC_RT_STUBS; i++) + ((uint32_t *)(void *)s->rt_code)[2 * i] = 0xd4000001u | (i << 5); /* svc #i */ + memset(s->in, 0, sizeof s->in); + if (rq->in_len) + memcpy(s->in, rq->in, rq->in_len); + memset(s->stack, 0, sizeof s->stack); + unsigned spages = (stack + CK_OSC_PAGE - 1) / CK_OSC_PAGE, cpages = (a->code_len + CK_OSC_PAGE - 1) / CK_OSC_PAGE; + map(s->l3a, 1, s->rt_tab, ATTR_RO); + map(s->l3a, 2, s->rt_code, ATTR_RX); + for (unsigned i = 0; i < cpages; i++) + map(s->l3a, 16 + i, s->code + i * CK_OSC_PAGE, ATTR_RX); + map(s->l3b, 0, s->in, ATTR_RO); + if (rq->ws) + for (unsigned i = 0; i < rq->ws->pages; i++) + map(s->l3b, 16 + i, rq->ws->mem + i * CK_OSC_PAGE, ATTR_RW); + for (unsigned i = 0; i < spages; i++) + map(s->l3b, 512 - spages + i, s->stack + (CK_OSC_STACK_MAX_BYTES / CK_OSC_PAGE - spages + i) * CK_OSC_PAGE, + ATTR_RW); + info->pages_mapped = count_mapped(s); + clean_range(s, 5 * 4096, 0); + clean_range(s->rt_tab, sizeof s->rt_tab, 0); + clean_range(s->rt_code, sizeof s->rt_code, 1); + clean_range(s->in, sizeof s->in, 0); + clean_range(s->code, sizeof s->code, 1); + clean_range(s->stack, sizeof s->stack, 0); + if (rq->ws) + clean_range(rq->ws->mem, (size_t)rq->ws->pages * CK_OSC_PAGE, 0); + + /* registers: arguments in x0..x5, OscRt in x7, return stub in x30; nothing else */ + uint64_t regs[31] = { 0 }; + for (unsigned i = 0; i < e->nregs; i++) + regs[i] = rq->args[i]; + regs[7] = base + OFF_RT_TAB; + regs[30] = rt_code_va + (uint64_t)OSC_SVC_RETURN * OSC_RT_STUB_BYTES; + info->budget = osc_launch_budget(a->cpu_ticks, rq->max_ticks); + + int (*old_sync)(struct ck_frame *, uint64_t) = ck_lower_sync; + struct ck_frame *(*old_tick)(struct ck_frame *) = ck_tick_switch; + uint64_t kttbr = ck_rd(ttbr0_el1), cpacr = ck_rd(cpacr_el1), cntkctl = ck_rd(cntkctl_el1); + memset(&run, 0, sizeof run); + run.budget = info->budget; + run.rt_code_va = rt_code_va; + ck_lower_sync = launch_sync; + ck_tick_switch = launch_tick; + uint64_t hz = ck_rd(cntfrq_el0); + ck_wr(cpacr_el1, (cpacr & ~(3ull << 20)) | (1ull << 20)); /* FP/SIMD traps at EL0 */ + /* EL0 must not touch the timers or counters: the budget timer is the kernel's, whatever firmware left in + * CNTKCTL_EL1. Clear EL0PCTEN/EL0VCTEN (bits 0,1: counter reads), EVNTEN/EVNTDIR (2,3: event stream) and + * EL0VTEN/EL0PTEN (8,9: timer registers); the loader clears only 8 and 9 (artifact_loader.c). */ + ck_wr(cntkctl_el1, cntkctl & ~0x30Full); + swap_ttbr0((uint64_t)(uintptr_t)s->l0); + ck_wr(cntp_cval_el0, ck_rd(cntpct_el0) + (hz ? hz / 100 : 625000)); + ck_wr(cntp_ctl_el0, 1); + ck_isb(); + run.active = 1; + ck_el0_enter(code_va + e->code_offset, stack_top, regs); + run.active = 0; + ck_wr(cntp_ctl_el0, 0); + ck_isb(); + swap_ttbr0(kttbr); + ck_wr(cpacr_el1, cpacr); + ck_wr(cntkctl_el1, cntkctl); + ck_isb(); + ck_lower_sync = old_sync; + ck_tick_switch = old_tick; + if (run.done) { + *res = run.res; + } else { /* the task came back without an event the kernel saw */ + struct osc_event lost = { OSC_EV_LOST, 0, 0, 0, 0 }; + osc_launch_classify(&lost, rt_code_va, res); + } + if (res->cls == OSC_RES_RETURNED && e->ret_kind == 0) + res->value = 0; /* a void function reports 0 (spec 9.3) */ + res->ticks = run.ticks; + + /* teardown: tables, runtime, input, code and stack are cleared; the caller's workspace stays */ + memset(s->l0, 0, sizeof s->l0); + memset(s->l1, 0, sizeof s->l1); + memset(s->l2, 0, sizeof s->l2); + memset(s->l3a, 0, sizeof s->l3a); + memset(s->l3b, 0, sizeof s->l3b); + memset(s->rt_tab, 0, sizeof s->rt_tab); + memset(s->rt_code, 0, sizeof s->rt_code); + memset(s->in, 0, sizeof s->in); + memset(s->code, 0, sizeof s->code); + memset(s->stack, 0, sizeof s->stack); + clean_range(s, sizeof *s, 1); + info->tables_zeroed = count_mapped(s) + (unsigned)(s->l0[idx] != 0) == 0; + s->used = 0; + info->slot_free_after = !s->used; +} + +int ck_osc_result_str(const struct osc_result *r, char *buf, size_t n) +{ + switch (r->cls) { + case OSC_RES_RETURNED: + return ck_snprintf(buf, n, "RETURNED value=%llu", (unsigned long long)r->value); + case OSC_RES_TRAPPED: + return ck_snprintf(buf, n, "TRAPPED trap_code=%u", (unsigned)r->trap_code); + case OSC_RES_UNKNOWN: + return ck_snprintf(buf, n, "OUTCOME_UNKNOWN unknown_reason=%u", (unsigned)r->unknown_reason); + case OSC_RES_REFUSED: + return ck_snprintf(buf, n, "REFUSED_AT_ADMISSION code=%u name=%s", (unsigned)r->refused_code, + osc_code_name(r->refused_code)); + default: + return ck_snprintf(buf, n, "UNCLASSIFIED"); + } +} + +/* Where the launcher keeps its own state, so the selftest can aim a workspace at it. */ +void ck_osc_state_range(uint64_t *addr, uint64_t *len) +{ + *addr = (uint64_t)(uintptr_t)&slot0; + *len = sizeof slot0; +} diff --git a/native/kernel/core/osc_task.h b/native/kernel/core/osc_task.h new file mode 100644 index 00000000..39091f0a --- /dev/null +++ b/native/kernel/core/osc_task.h @@ -0,0 +1,60 @@ +/* osc_task.h -- launch an admitted OSC unit as an EL0 task (OSC_UNIT_ARTIFACT.md section 9), C3-3a. + * Admission (osc_admit.c) never maps anything; this does, for one function call at a time. QEMU only: + * nothing here is physical. See docs/osc-launch.md. */ +#ifndef AIENOS_CK_OSC_TASK_H +#define AIENOS_CK_OSC_TASK_H +#include +#include +#include "osc_launch.h" +#include "osc_unit.h" + +#define CK_OSC_PAGE 4096u +#define CK_OSC_CODE_MAX_BYTES (16u * CK_OSC_PAGE) /* launcher hard maximum (stricter than the spec's 262144) */ +#define CK_OSC_STACK_MAX_BYTES (16u * CK_OSC_PAGE) /* a unit declaring more is refused RESOURCE_UNAVAILABLE */ +#define CK_OSC_IN_MAX_BYTES CK_OSC_PAGE + +/* A caller-owned workspace for `cells` arguments: `pages` 4 KiB pages of page-aligned caller memory starting at + * `mem`, 0 to OSC_WS_MAX_PAGES (0 = no workspace). It is mapped read-write (never executable) into the task for the + * call and is NOT cleared by teardown: state a unit leaves in it is there for the next call that is given the same + * workspace. A workspace over the cap, or with unaligned or null memory, is refused 30 before the first instruction. */ +/* A workspace is mapped read-write (never executable) into EL0 as it is, so it MUST be memory the caller owns + * and nothing else uses: page aligned, not null, not overlapping the launcher's own state or the input buffer + * (refused 30, nothing mapped). The kernel has no region it restricts workspaces to, so beyond those checks it + * trusts the caller. It is not cleared at teardown. */ +struct ck_osc_ws { + uint8_t *mem; + uint32_t pages; +}; + +struct ck_osc_launch_req { + const char *name; /* exact function name (osc_unit_lookup) */ + size_t name_len; + unsigned nargs; + uint64_t args[6]; /* a bytes slice is (ck_osc_va_in() + k, len), a cells slice (ck_osc_va_ws() + k, n) */ + const uint8_t *in; /* read-only input, copied to the task's input window; at most CK_OSC_IN_MAX_BYTES */ + size_t in_len; + struct ck_osc_ws *ws; /* caller-owned workspace, or NULL */ + uint64_t max_ticks; /* caller cap on the budget, 0 = the unit's declared cpu_ticks only */ +}; + +struct ck_osc_launch_info { + uint64_t budget; /* ticks granted */ + unsigned pages_mapped; /* user pages that were mapped while the task existed */ + int tables_zeroed; /* after teardown every page-table entry of the task is zero and its L0 slot is clear (says nothing about frame contents) */ + int slot_free_after; /* the task slot is reusable */ +}; + +/* Unit-space addresses of the input window and the workspace window (the same for every launch). 0 if the + * kernel has no free address-space slot to build them in. */ +uint64_t ck_osc_va_in(void); +uint64_t ck_osc_va_ws(void); + +/* Launch the function rq->name of the accepted unit (bytes `unit`, verdict *a from osc_unit_admit on the + * same bytes) and wait for it. *res is always filled. Refusals (40 unknown name, 41 argument shape or + * range, 30 resources, 16 code hash) mean no unit instruction ran. */ +void ck_osc_launch(const uint8_t *unit, size_t unit_len, const struct osc_accept *a, + const struct ck_osc_launch_req *rq, struct osc_result *res, struct ck_osc_launch_info *info); + +/* "RETURNED value=..", "TRAPPED trap_code=..", "OUTCOME_UNKNOWN reason=..", "REFUSED code=.." */ +int ck_osc_result_str(const struct osc_result *r, char *buf, size_t n); +#endif diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb index 83371f36..b7f92919 100644 --- a/native/kernel/tests/.crumb +++ b/native/kernel/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T11:03:01Z", + "compiled_at": "2026-10-08T12:24:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:1b900c32e47ab5317c6fc9ed443f06496eb9c261857f0c7eec3cd65c97eaddcf", + "digest": "sha256:e2fcb936b8b24ceb35368fafc1065d042999862da4b9938bb0b708bbd327f018", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 92, - "generated_at_commit": "1ab797d6c0c42fee6b5fbebebaa81e1e86a55609", - "source_tree": "sha256:c811e379c067009dd45d383be462e93c29107473dc28b22abb8a62f342d69042" + "files": 99, + "generated_at_commit": "9b759de6e9c8ed316bfe012011bac39831deb10b", + "source_tree": "sha256:dcbdb6b5c7eb121d5d37c0ea1e76be1e5f7ee43adcde63ad71bec6cae037dadf" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tests/fixtures/osc_unit/PROVENANCE.txt b/native/kernel/tests/fixtures/osc_unit/PROVENANCE.txt index 1531bc79..fbd16170 100644 --- a/native/kernel/tests/fixtures/osc_unit/PROVENANCE.txt +++ b/native/kernel/tests/fixtures/osc_unit/PROVENANCE.txt @@ -3,4 +3,19 @@ aien-dev/aien-protocols main at 6661009 (PR #17 merged), specs/osc-unit-artifact (contract OSC_UNIT_ARTIFACT.md, container version 1, frozen v1). Both keys are THROWAWAY TEST keys derived from fixed labels in that spec's tools/make-vectors.sh. They protect nothing and must never enter a real anchor set. -launch.txt (launch code 41) is copied but not run by this admission test: launch is a separate cut. +launch.txt (launch code 41) is vectors/launch.txt, used by tests/test_osc_launch.c (C3-3a). + +launch/ (added by the C3-3a task-launch cut): + osc-launch-check.c copied unchanged from the same spec (tools/osc-launch-check.c): the C reference + for the launch-argument rule (spec 9.2, launch code 41). vectors/launch.txt is the + spec's launch.txt, unchanged. + l01.S, make-l01.sh, l01_launch_fns.unit, l01.code + a TEST-signed unit (the spec's throwaway key test1, built with the spec's own + generator helpers) of hand-assembled functions: trap, spin, peek0, poke_rt, + bare_brk, exec_stack, overflow, counter. NOT compiled by oscc; its IR section is + min.ir, so the IR does not describe the code (attested, never checked: spec 10). + Fixture for the QEMU launch gate only. + (C3-3a review fixes) l01 now also holds peek_kernel, jump_ws, jump_in, dirty, regs_or, touch_past (14 functions, + TEST, hand-assembled, same key and labelling); l02_stack_over.unit is l01 with + max_stack_bytes patched to 65552 (65536 + 16) and re-signed with test1 (TEST, one byte over the + launcher maximum). a06_valid_limits_at_max.unit (vectors/) is launched too: 1 MiB stack. diff --git a/native/kernel/tests/fixtures/osc_unit/launch/l01.S b/native/kernel/tests/fixtures/osc_unit/launch/l01.S new file mode 100644 index 00000000..2f935893 --- /dev/null +++ b/native/kernel/tests/fixtures/osc_unit/launch/l01.S @@ -0,0 +1,143 @@ +// l01.S: hand-assembled TEST functions for the C3-3a task-launch gate. +// Every word is in the OSC-emitted subset (spec 8.4); admission re-checks it. +// x7 = OscRt *, x30 = the runtime return stub, args in x0..x5. + .text + .global _start +_start: +// fn 0 trap(code: u64) -> u64 : the real trap sequence (osc_cg.c trap_seq), code in x0 +trap: + mov x1, x0 + mov x0, x7 + ldr x16, [x0, #16] + blr x16 + brk #1 +// fn 1 spin() -> u64 : never finishes (budget test) +spin: + b spin +// fn 2 peek0() -> u64 : read address 0 (unmapped): a CPU fault +peek0: + movz x0, #0 + ldr x0, [x0] + ret +// fn 3 poke_rt() -> u64 : write the OscRt table (read-only to the unit): a CPU fault +poke_rt: + str x0, [x7] + ret +// fn 4 bare_brk() -> u64 : reaches a brk guard directly (spec 8.4: a fault, never TRAPPED) +bare_brk: + brk #3 +// fn 5 exec_stack() -> u64 : write a `ret` into the stack and call it. W^X: must fault. +exec_stack: + sub sp, sp, #16 + movz x1, #0x03c0 + movk x1, #0xd65f, lsl #16 + str x1, [sp] + add x0, sp, #0 + blr x0 + movz x0, #42 + add sp, sp, #16 + ret +// fn 6 overflow() -> u64 : grow the stack until it leaves the mapped stack +overflow: + sub sp, sp, #16 + str x0, [sp] + b overflow +// fn 7 counter(ws: cells, n: u64) -> u64 : ws[0] += 1, return it (workspace persistence) +counter: + ldr x2, [x0] + add x2, x2, #1 + str x2, [x0] + orr x0, xzr, x2 + ret +// fn 8 peek_kernel(addr: u64) -> u64 : read a kernel virtual address (mapped EL1-only): a CPU fault +peek_kernel: + ldr x0, [x0] + ret +// fn 9 jump_ws(ws: cells, n: u64) -> u64 : call the code at x0 (the caller pre-loads a valid `ret` there); returns 42 +// if that works, so only an execute-never workspace page makes this fault +jump_ws: + sub sp, sp, #16 + str x30, [sp] + blr x0 + ldr x30, [sp] + add sp, sp, #16 + movz x0, #42 + ret +// fn 10 jump_in(in: bytes, n: u64) -> u64 : same, into the input window (caller supplies the `ret` bytes) +jump_in: + sub sp, sp, #16 + str x30, [sp] + blr x0 + ldr x30, [sp] + add sp, sp, #16 + movz x0, #42 + ret +// fn 11 dirty() -> u64 : leave a nonzero value in x1..x29 (for the register-clearing check) +dirty: + movz x1, #0x1111 + movz x2, #0x2222 + movz x3, #0x3333 + movz x4, #0x4444 + movz x5, #0x5555 + movz x6, #0x6666 + movz x8, #0x8888 + movz x9, #0x9999 + movz x10, #0xaaaa + movz x11, #0xbbbb + movz x12, #0xcccc + movz x13, #0xdddd + movz x14, #0xeeee + movz x15, #0xffff + movz x16, #0x1616 + movz x17, #0x1717 + movz x18, #0x1818 + movz x19, #0x1919 + movz x20, #0x2020 + movz x21, #0x2121 + movz x22, #0x2222 + movz x23, #0x2323 + movz x24, #0x2424 + movz x25, #0x2525 + movz x26, #0x2626 + movz x27, #0x2727 + movz x28, #0x2828 + movz x29, #0x2929 + movz x0, #1 + ret +// fn 12 regs_or() -> u64 : OR of x0..x29 as seen at entry, except x7 (the OscRt pointer, set by contract). +// Zero means every other register was cleared by the launcher. +regs_or: + orr x0, x0, x1 + orr x0, x0, x2 + orr x0, x0, x3 + orr x0, x0, x4 + orr x0, x0, x5 + orr x0, x0, x6 + orr x0, x0, x8 + orr x0, x0, x9 + orr x0, x0, x10 + orr x0, x0, x11 + orr x0, x0, x12 + orr x0, x0, x13 + orr x0, x0, x14 + orr x0, x0, x15 + orr x0, x0, x16 + orr x0, x0, x17 + orr x0, x0, x18 + orr x0, x0, x19 + orr x0, x0, x20 + orr x0, x0, x21 + orr x0, x0, x22 + orr x0, x0, x23 + orr x0, x0, x24 + orr x0, x0, x25 + orr x0, x0, x26 + orr x0, x0, x27 + orr x0, x0, x28 + orr x0, x0, x29 + ret +// fn 13 touch_past(ws: cells, n: u64) -> u64 : read the 8 bytes just after x0's cell. With x0 the last cell of +// the workspace this is the first byte past it (unmapped): a CPU fault. +touch_past: + ldr x0, [x0, #8] + ret diff --git a/native/kernel/tests/fixtures/osc_unit/launch/l01.code b/native/kernel/tests/fixtures/osc_unit/launch/l01.code new file mode 100644 index 00000000..3a7abea7 Binary files /dev/null and b/native/kernel/tests/fixtures/osc_unit/launch/l01.code differ diff --git a/native/kernel/tests/fixtures/osc_unit/launch/l01_launch_fns.unit b/native/kernel/tests/fixtures/osc_unit/launch/l01_launch_fns.unit new file mode 100644 index 00000000..bdb3ffef Binary files /dev/null and b/native/kernel/tests/fixtures/osc_unit/launch/l01_launch_fns.unit differ diff --git a/native/kernel/tests/fixtures/osc_unit/launch/l02_stack_over.unit b/native/kernel/tests/fixtures/osc_unit/launch/l02_stack_over.unit new file mode 100644 index 00000000..229efecb Binary files /dev/null and b/native/kernel/tests/fixtures/osc_unit/launch/l02_stack_over.unit differ diff --git a/native/kernel/tests/fixtures/osc_unit/launch/make-l01.sh b/native/kernel/tests/fixtures/osc_unit/launch/make-l01.sh new file mode 100755 index 00000000..4738d063 --- /dev/null +++ b/native/kernel/tests/fixtures/osc_unit/launch/make-l01.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# make-l01.sh: build the C3-3a launch test unit l01_launch_fns.unit with the spec's own generator +# helpers. Usage: make-l01.sh SPEC_DIR OUT_DIR +# SPEC_DIR a checkout of aien-protocols specs/osc-unit-artifact (needs tools/make-vectors.sh, src/min.ir) +# OUT_DIR receives l01_launch_fns.unit and l01.code +# Needs as, objcopy, nm, xxd, sha256sum, openssl (Ed25519), bash. No Python. +# The helper functions (u8, le16, entry, caps_none, build, resign, the throwaway TEST key "test1") are +# taken from SPEC_DIR/tools/make-vectors.sh unchanged: everything before its line `cp "$SRC/min.ir"`. +# HONEST LIMIT: the code is hand-assembled (l01.S), not compiled by oscc. The IR section is min.ir +# (the spec's compiled vector), so the IR does not describe this code. The IR is attested by the +# signer, never checked against the code (spec section 10); the container is valid and the TEST +# signer vouches for a mismatch. program_id therefore equals min.osc's. Test fixture only. +set -eu +export LC_ALL=C +mydir=$(cd "$(dirname "$0")" && pwd) +SPEC=${1:?SPEC_DIR} +OUT=${2:?OUT_DIR} +mkdir -p "$OUT" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +n=$(grep -n '^cp "\$SRC/min.ir"' "$SPEC/tools/make-vectors.sh" | head -1 | cut -d: -f1) +{ echo 'here='"$SPEC/tools"; sed -n "1,$((n - 1))p" "$SPEC/tools/make-vectors.sh" | sed '/^here=/d'; } >"$work/helpers.sh" +OUT_UNIT=$OUT +set -- "$work/keys-out" "$work/keys-out" # helpers read OUT_DIR=$1, KEYS_DIR=$2 +mkdir -p "$work/keys-out" +SRC=$SPEC/src +# shellcheck disable=SC1090 +. "$work/helpers.sh" +OUT=$OUT_UNIT +cmp -s "$KEYS/test1.pub" "$SPEC/keys/test1.pub" || { echo "TEST key mismatch: generator is not the frozen one" >&2; exit 1; } + +as -o "$work/l01.o" "$mydir/l01.S" +objcopy -O binary -j .text "$work/l01.o" "$work/code" +off() { printf '%d' 0x"$(nm "$work/l01.o" | awk -v s="$1" '$3 == s {print $1}')"; } +cp "$SRC/min.ir" "$work/ir" +{ + entry 0 1 5 5 0 0 0 0 0 "$(off trap)" trap + entry 1 0 5 0 0 0 0 0 0 "$(off spin)" spin + entry 2 0 5 0 0 0 0 0 0 "$(off peek0)" peek0 + entry 3 0 5 0 0 0 0 0 0 "$(off poke_rt)" poke_rt + entry 4 0 5 0 0 0 0 0 0 "$(off bare_brk)" bare_brk + entry 5 0 5 0 0 0 0 0 0 "$(off exec_stack)" exec_stack + entry 6 0 5 0 0 0 0 0 0 "$(off overflow)" overflow + entry 7 2 5 12 5 0 0 0 0 "$(off counter)" counter + entry 8 1 5 5 0 0 0 0 0 "$(off peek_kernel)" peek_kernel + entry 9 2 5 12 5 0 0 0 0 "$(off jump_ws)" jump_ws + entry 10 2 5 11 5 0 0 0 0 "$(off jump_in)" jump_in + entry 11 0 5 0 0 0 0 0 0 "$(off dirty)" dirty + entry 12 0 5 0 0 0 0 0 0 "$(off regs_or)" regs_or + entry 13 2 5 12 5 0 0 0 0 "$(off touch_past)" touch_past +} >"$work/ent" +caps_none >"$work/caps0" +build "$OUT/l01_launch_fns.unit" test1 1 5 1 14 "$work/ir" "$work/code" "$work/ent" "$work/caps0" +cp "$work/code" "$OUT/l01.code" +# l02: l01 with max_stack_bytes = 65552 = 65536 + 16 (offset 36; the container requires a multiple of 16, so this is the smallest legal value over the launcher's 65536 maximum), re-signed. +# The launcher must refuse it LIMIT_EXCEEDED (14) before any reservation. +patch "$OUT/l01_launch_fns.unit" 36 10 00 01 00 >"$OUT/l02_stack_over.unit" +resign "$OUT/l02_stack_over.unit" test1 +echo "built $OUT/l01_launch_fns.unit $OUT/l02_stack_over.unit" diff --git a/native/kernel/tests/fixtures/osc_unit/launch/osc-launch-check.c b/native/kernel/tests/fixtures/osc_unit/launch/osc-launch-check.c new file mode 100644 index 00000000..6bfeb95e --- /dev/null +++ b/native/kernel/tests/fixtures/osc_unit/launch/osc-launch-check.c @@ -0,0 +1,56 @@ +/* osc-launch-check.c: reference for the launch-argument rule (spec 9.2). + * Same logic as omega osc_ir_slice_args_ok (osc_ir.c:689-705 at d64ccb3) plus + * the scalar-fits-kind rule. Usage: osc-launch-check KINDS ARGS + * Prints OK | REFUSED LAUNCH_ARG_SHAPE 41. C99, libc only. */ +#include +#include +#include +#include +#define MAXR 6 +static int split(char *s, uint64_t *out) { + int n = 0; + for (char *t = strtok(s, ","); t; t = strtok(NULL, ",")) { + if (n >= 64) return -1; + out[n++] = strtoull(t, NULL, 0); + } + return n; +} +static int is_slice(uint64_t k) { return k == 11 || k == 12; } +static int fits(uint64_t k, uint64_t v) { + switch (k) { + case 1: return v <= 1; + case 2: return v <= 0xff; + case 3: return v <= 0xffff; + case 4: return v <= 0xffffffffull; + case 6: return (int64_t)v == (int8_t)v; + case 7: return (int64_t)v == (int16_t)v; + case 8: return (int64_t)v == (int32_t)v; + default: return 1; /* 5, 9, slice registers */ + } +} +int main(int argc, char **argv) { + if (argc != 3) return 2; + uint64_t kinds[64], args[64]; + char a[512], b[512]; + snprintf(a, sizeof a, "%s", argv[1]); + snprintf(b, sizeof b, "%s", argv[2]); + int nk = split(a, kinds), na = split(b, args); + int bad = (nk < 0 || na != nk || nk > MAXR); + for (int p = 0; !bad && p < nk; p++) { + if (!is_slice(kinds[p]) && !fits(kinds[p], args[p])) bad = 1; + } + for (int p = 0; !bad && p + 1 < nk; p++) { + if (!is_slice(kinds[p])) continue; + uint64_t ptr = args[p], n = args[p + 1], sz = n * (kinds[p] == 12 ? 8 : 1); + if ((kinds[p] == 12 && (n > UINT64_MAX / 8 || (n && (ptr & 7)))) || (n && !ptr) || sz > UINT64_MAX - ptr) bad = 1; + for (int q = 0; !bad && q + 1 < nk; q++) { + if (q == p || !is_slice(kinds[q])) continue; + if (kinds[p] != 12 && kinds[q] != 12) continue; + uint64_t qn = args[q + 1], qsz = qn * (kinds[q] == 12 ? 8 : 1); + if (!sz || !qn || (kinds[q] == 12 && qn > UINT64_MAX / 8) || qsz > UINT64_MAX - args[q]) continue; + if (ptr < args[q] + qsz && args[q] < ptr + sz) bad = 1; + } + } + puts(bad ? "REFUSED LAUNCH_ARG_SHAPE 41" : "OK"); + return 0; +} diff --git a/native/kernel/tests/test_osc_launch.c b/native/kernel/tests/test_osc_launch.c new file mode 100644 index 00000000..352d6b4a --- /dev/null +++ b/native/kernel/tests/test_osc_launch.c @@ -0,0 +1,351 @@ +/* test_osc_launch.c -- host tests for the pure parts of OSC unit launch (artifact/osc_launch.c): + * - the argument rule (spec 9.2) against vectors/launch.txt, and against the spec's own C reference + * tools/osc-launch-check.c (built by the Makefile, path in OSC_LAUNCH_REF) on 3000 pseudo-random + * cases that mix interesting values (alignment, wrap, overlap, range edges); + * - range ownership (9.1.1 item 4), the ticks budget, and the result classification (9.3, 9.1.1): + * RETURNED only from the return stub, TRAPPED only from the trap stub with a code in 1..14, an SVC + * from anywhere else and a brk reached directly are OUTCOME_UNKNOWN(FAULT), never TRAPPED, and no + * exception class and no trap code 0..255 can produce RETURNED; + * - the launch fixture unit l01 admits and its entry table drives the same argument rule. */ +#include +#include +#include +#include +#include +#include "ck_test.h" +#include "osc_launch.h" +#include "osc_unit.h" +#include "osc_unit_test_anchor.h" + +#ifndef OSC_FIXTURE_DIR +#define OSC_FIXTURE_DIR "native/kernel/tests/fixtures/osc_unit" +#endif +#ifndef OSC_LAUNCH_REF +#define OSC_LAUNCH_REF "osc-launch-check" +#endif + +static int split(char *s, uint64_t *out, int max) +{ + int n = 0; + for (char *t = strtok(s, ","); t; t = strtok(NULL, ",")) { + if (n >= max) return -1; + out[n++] = strtoull(t, NULL, 0); + } + return n; +} + +/* ours: 1 OK, 0 refused; -1 unparsable */ +static int ours(const char *kinds, const char *args) +{ + char a[512], b[512]; + uint64_t k[64], v[64]; + snprintf(a, sizeof a, "%s", kinds); + snprintf(b, sizeof b, "%s", args); + int nk = split(a, k, 64), na = split(b, v, 64); + if (nk < 0 || na < 0) return -1; + uint8_t kk[64]; + for (int i = 0; i < nk; i++) kk[i] = (uint8_t)k[i]; + return osc_launch_args_ok(kk, (unsigned)nk, v, (unsigned)na); +} + +/* Runs the reference checker directly (argv, no shell) and reads its first output line. */ +static int reference(const char *kinds, const char *args) +{ + char out[128]; + int fd[2]; + if (pipe(fd) != 0) return -1; + pid_t pid = fork(); + if (pid < 0) { close(fd[0]); close(fd[1]); return -1; } + if (pid == 0) { + close(fd[0]); + if (dup2(fd[1], STDOUT_FILENO) < 0) _exit(127); + close(fd[1]); + execl(OSC_LAUNCH_REF, OSC_LAUNCH_REF, kinds, args, (char *)NULL); + _exit(127); + } + close(fd[1]); + FILE *p = fdopen(fd[0], "r"); + int status = 0, got = p && fgets(out, sizeof out, p) != NULL; + if (p) fclose(p); else close(fd[0]); + if (waitpid(pid, &status, 0) != pid || !got) return -1; + return strncmp(out, "OK", 2) == 0 ? 1 : strncmp(out, "REFUSED LAUNCH_ARG_SHAPE 41", 27) == 0 ? 0 : -1; +} + +static void launch_txt(void) +{ + char path[512], line[512]; + int n = 0; + snprintf(path, sizeof path, "%s/vectors/launch.txt", OSC_FIXTURE_DIR); + FILE *f = fopen(path, "r"); + CHECK(f != NULL); + if (!f) return; + while (fgets(line, sizeof line, f)) { + if (line[0] == '#' || line[0] == '\n') continue; + char kinds[128], args[256], verdict[128]; + if (sscanf(line, "%127s %255s %127[^\n]", kinds, args, verdict) != 3) { CHECK(0); continue; } + int want = strncmp(verdict, "OK", 2) == 0; + if (!want) CHECK(strcmp(verdict, "REFUSED LAUNCH_ARG_SHAPE 41") == 0); + CHECK(ours(kinds, args) == want); + CHECK(reference(kinds, args) == want); + n++; + } + fclose(f); + CHECK(n == 16); + printf(" launch.txt: %d lines\n", n); +} + +static uint64_t rs = 0x9e3779b97f4a7c15ull; +static uint64_t rnd(void) +{ + rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; + return rs; +} + +static void differential(void) +{ + static const char *const shapes[] = { + "5,5", "11,5", "12,5", "11,5,11,5", "12,5,11,5", "11,5,12,5", "12,5,12,5", "2,5", "6,5", "1,4", "7,3", + "8,9", "9", "5", "11,5,5", "12,5,5,5", "11,5,11,5,12,5", "12,5,12,5,12,5", "3,5,11,5", "4,6,12,5", + }; + static const uint64_t vals[] = { + 0, 1, 2, 3, 4, 7, 8, 9, 15, 16, 0x7f, 0x80, 0xff, 0x100, 0xffff, 0x10000, 0xffffffffull, 0x100000000ull, + 0xffffffffffffff80ull, 0xffffffffffff8000ull, 0xffffffff80000000ull, 0x1000, 0x1004, 0x1008, 0x1010, 0x1018, + 0x2000, 0x2000000000000000ull, 0x1fffffffffffffffull, 0x8000000000000000ull, 0xfffffffffffffff0ull, + 0xfffffffffffffff8ull, 0xffffffffffffffffull, 0xfffffffffffffff7ull, + }; + const unsigned nv = sizeof vals / sizeof vals[0]; + int mismatch = 0, ok = 0, ref = 0; + for (int i = 0; i < 3000; i++) { + const char *shape = shapes[rnd() % (sizeof shapes / sizeof shapes[0])]; + int regs = 1; + for (const char *c = shape; *c; c++) regs += *c == ','; + char args[400]; + size_t at = 0; + int cnt = regs; + if (rnd() % 17 == 0) cnt = regs + (rnd() % 2 ? 1 : -1); /* wrong register count now and then */ + if (cnt < 0) cnt = 0; + args[0] = 0; + for (int r = 0; r < cnt; r++) { + int w = snprintf(args + at, sizeof args - at, "%s0x%llx", r ? "," : "", (unsigned long long)vals[rnd() % nv]); + if (w < 0 || (size_t)w >= sizeof args - at) break; /* never step past the buffer */ + at += (size_t)w; + } + if (cnt == 0) strcpy(args, "0"); + int a = ours(shape, args), b = reference(shape, args); + if (a != b) { mismatch++; if (mismatch < 5) printf(" MISMATCH kinds=%s args=%s ours=%d ref=%d\n", shape, args, a, b); } + a == 1 ? ok++ : ref++; + } + CHECK(mismatch == 0); + CHECK(ok > 200 && ref > 200); /* the sample exercises both verdicts */ + printf(" differential vs the spec's C reference: 3000 cases, %d OK, %d refused, %d mismatches\n", ok, ref, mismatch); +} + +static void ownership(void) +{ + const uint8_t kb[2] = { 11, 5 }, kc[2] = { 12, 5 }, kbc[4] = { 11, 5, 12, 5 }; + uint64_t in = 0x200000, ws = 0x210000; + uint64_t a1[2] = { in, 16 }; + CHECK(osc_launch_ranges_owned(kb, 2, a1, in, 16, ws, 4096)); /* exactly the input window */ + uint64_t a2[2] = { in, 17 }; + CHECK(!osc_launch_ranges_owned(kb, 2, a2, in, 16, ws, 4096)); /* one byte past */ + uint64_t a3[2] = { in + 15, 1 }; + CHECK(osc_launch_ranges_owned(kb, 2, a3, in, 16, ws, 4096)); /* last byte */ + uint64_t a4[2] = { in - 1, 1 }; + CHECK(!osc_launch_ranges_owned(kb, 2, a4, in, 16, ws, 4096)); /* one byte before */ + uint64_t a5[2] = { ws, 2 }; + CHECK(!osc_launch_ranges_owned(kb, 2, a5, in, 16, ws, 4096)); /* bytes in the workspace: not RO */ + uint64_t c1[2] = { ws, 512 }; + CHECK(osc_launch_ranges_owned(kc, 2, c1, in, 16, ws, 4096)); /* 512 cells = 4096 bytes */ + uint64_t c2[2] = { ws, 513 }; + CHECK(!osc_launch_ranges_owned(kc, 2, c2, in, 16, ws, 4096)); + uint64_t c3[2] = { in, 1 }; + CHECK(!osc_launch_ranges_owned(kc, 2, c3, in, 16, ws, 4096)); /* cells in the RO input */ + CHECK(!osc_launch_ranges_owned(kc, 2, c1, in, 16, ws, 0)); /* no workspace given */ + uint64_t c4[2] = { 0, 0 }; + CHECK(osc_launch_ranges_owned(kc, 2, c4, in, 16, ws, 0)); /* zero length, null: never dereferenced */ + uint64_t c5[2] = { ws, 0x2000000000000000ull }; + CHECK(!osc_launch_ranges_owned(kc, 2, c5, in, 16, ws, 4096)); /* n*8 would wrap */ + uint64_t m[4] = { in, 8, ws + 8, 2 }; + CHECK(osc_launch_ranges_owned(kbc, 4, m, in, 16, ws, 4096)); + uint64_t m2[4] = { in, 8, ws + 4088, 2 }; + CHECK(!osc_launch_ranges_owned(kbc, 4, m2, in, 16, ws, 4096)); +} + +static void budget(void) +{ + CHECK(osc_launch_budget(1000000, 0) == 1000000); /* no cap: the declared budget */ + CHECK(osc_launch_budget(1000000, 5) == 5); /* a cap lowers it */ + CHECK(osc_launch_budget(3, 5) == 3); /* a cap never raises it */ + CHECK(osc_launch_budget(1, 1) == 1); + CHECK(!osc_launch_budget_expired(0, 5)); + CHECK(!osc_launch_budget_expired(4, 5)); + CHECK(osc_launch_budget_expired(5, 5)); + CHECK(osc_launch_budget_expired(6, 5)); +} + +#define RT 0x7000002000ull +static uint64_t esr_svc(unsigned imm) { return (0x15ull << 26) | (1ull << 25) | imm; } +static uint64_t esr_ec(uint64_t ec) { return (ec << 26) | (1ull << 25); } + +static struct osc_result cls(unsigned kind, uint64_t esr, uint64_t elr, uint64_t x0, uint64_t x1) +{ + struct osc_event e = { kind, esr, elr, x0, x1 }; + struct osc_result r; + memset(&r, 0xaa, sizeof r); + osc_launch_classify(&e, RT, &r); + return r; +} + +static uint64_t stub(unsigned i) { return RT + (uint64_t)i * OSC_RT_STUB_BYTES; } + +static void classify(void) +{ + struct osc_result r; + /* RETURNED: only from the return stub, value is x0 */ + r = cls(OSC_EV_SVC, esr_svc(13), stub(13) + 4, 0xfeedfaceull, 99); + CHECK(r.cls == OSC_RES_RETURNED && r.value == 0xfeedfaceull && r.unknown_reason == 0 && r.trap_code == 0); + r = cls(OSC_EV_SVC, esr_svc(13), stub(13) + 4, 0, 0); + CHECK(r.cls == OSC_RES_RETURNED && r.value == 0); /* a void function reports 0 */ + /* TRAPPED: the trap stub with a code in 1..14 */ + for (unsigned c = 1; c <= 14; c++) { + r = cls(OSC_EV_SVC, esr_svc(OSC_SVC_TRAP), stub(OSC_SVC_TRAP) + 4, 777, c); + CHECK(r.cls == OSC_RES_TRAPPED && r.trap_code == c && r.unknown_reason == 0); + } + /* trap code 0, 15..255 and wide values: OUTCOME_UNKNOWN(TRAP_CODE_UNKNOWN), never TRAPPED */ + for (uint64_t c = 0; c < 256; c++) { + if (c >= 1 && c <= 14) continue; + r = cls(OSC_EV_SVC, esr_svc(OSC_SVC_TRAP), stub(OSC_SVC_TRAP) + 4, 0, c); + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_TRAP_CODE_UNKNOWN); + } + r = cls(OSC_EV_SVC, esr_svc(OSC_SVC_TRAP), stub(OSC_SVC_TRAP) + 4, 0, 0x100000003ull); /* low byte is 3: still not a trap */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_TRAP_CODE_UNKNOWN); + /* runtime services this cut does not provide */ + for (unsigned i = 0; i < OSC_RT_SERVICES; i++) { + if (i == OSC_SVC_TRAP) continue; + r = cls(OSC_EV_SVC, esr_svc(i), stub(i) + 4, 1, 1); + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_OTHER); + } + /* an SVC from unit context (anywhere but a stub with the matching immediate) is refused as a FAULT */ + r = cls(OSC_EV_SVC, esr_svc(0), 0x7000010004ull, 0, 0); /* in the unit's code */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_svc(13), stub(13) + 8, 5, 0); /* return-stub immediate at the wrong place */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_svc(2), stub(13) + 4, 5, 3); /* trap immediate at the return stub */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_svc(13), stub(13) + 5, 5, 0); /* misaligned return address */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_svc(14), stub(14) + 4, 5, 0); /* one stub past the table */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_svc(0), RT - 4, 5, 0); /* just below stub 0 */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_svc(13), 2, 5, 0); /* tiny elr: no wrap into a stub */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + r = cls(OSC_EV_SVC, esr_ec(0x24) | 13, stub(13) + 4, 5, 0); /* not an SVC class at all */ + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT); + /* every other synchronous class: never RETURNED, never TRAPPED; known CPU faults are FAULT */ + for (uint64_t ec = 0; ec < 64; ec++) { + if (ec == 0x15) continue; + r = cls(OSC_EV_SYNC, esr_ec(ec) | 3, stub(13) + 4, 1, 3); + CHECK(r.cls == OSC_RES_UNKNOWN); + int known = ec == 0x00 || ec == 0x07 || ec == 0x0e || ec == 0x18 || ec == 0x20 || ec == 0x22 || + ec == 0x24 || ec == 0x26 || ec == 0x3c; + CHECK(r.unknown_reason == (known ? OSC_UNK_FAULT : OSC_UNK_OTHER)); + } + /* a brk (class 0x3c) with an immediate 1..14 reached directly is a fault, never TRAPPED (spec 8.4) */ + for (unsigned imm = 0; imm < 16; imm++) { + r = cls(OSC_EV_SYNC, esr_ec(0x3c) | imm, 0x7000010000ull, imm, imm); + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_FAULT && r.trap_code == 0); + } + r = cls(OSC_EV_BUDGET, 0, 0x7000010000ull, 0, 0); + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_TICK_OVERRUN); + r = cls(OSC_EV_LOST, 0, 0, 0, 0); + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_LAUNCH_LOST); + r = cls(99, 0, 0, 0, 0); + CHECK(r.cls == OSC_RES_UNKNOWN && r.unknown_reason == OSC_UNK_OTHER); + /* the reason is diagnostic: values are the spec's */ + CHECK(OSC_UNK_FAULT == 1 && OSC_UNK_TICK_OVERRUN == 2 && OSC_UNK_LAUNCH_LOST == 3 && + OSC_UNK_TRAP_CODE_UNKNOWN == 4 && OSC_UNK_OTHER == 255); +} + +static void fixture_unit(void) +{ + char path[512]; + snprintf(path, sizeof path, "%s/launch/l01_launch_fns.unit", OSC_FIXTURE_DIR); + FILE *f = fopen(path, "rb"); + CHECK(f != NULL); + if (!f) return; + static uint8_t buf[8192]; + size_t n = fread(buf, 1, sizeof buf, f); + fclose(f); + struct osc_policy p; + memset(&p, 0, sizeof p); + static const uint8_t (*const ta)[32] = &osc_unit_test1_pk; + p.test_anchors = ta; + p.n_test = 1; + p.unit_formats = OSC_PROFILE_UNIT_FORMATS; + p.abi_versions = OSC_PROFILE_ABI; + static struct osc_accept a; + CHECK(osc_unit_admit(buf, n, &p, &a) == OSC_OK); + CHECK(a.function_count == 14); + int fi = osc_unit_lookup(&a, "counter", 7); + CHECK(fi == 7 && a.entry[fi].nregs == 2 && a.entry[fi].reg_kind[0] == 12 && a.entry[fi].reg_kind[1] == 5); + uint64_t ok[2] = { 0x210000, 1 }, bad[2] = { 0x210004, 1 }; + CHECK(osc_launch_args_ok(a.entry[fi].reg_kind, a.entry[fi].nregs, ok, 2)); + CHECK(!osc_launch_args_ok(a.entry[fi].reg_kind, a.entry[fi].nregs, bad, 2)); + CHECK(!osc_launch_args_ok(a.entry[fi].reg_kind, a.entry[fi].nregs, ok, 1)); + CHECK(osc_unit_lookup(&a, "Counter", 7) == -1 && osc_unit_lookup(&a, "trap", 4) == 0); + /* every word of l01 passed the section 8.4 scan inside admission; the spin loop and the bare brk are in it */ + CHECK(a.code_len == 424); +} + +static void workspace_bounds(void) +{ + const uint8_t kc[2] = { 12, 5 }; + const uint64_t in = 0x200000, ws = 0x210000; + CHECK(OSC_WS_MAX_PAGES == 32u); + /* declared stack vs the launcher maximum: at the max passes, one byte over is LIMIT_EXCEEDED (14) */ + CHECK(osc_launch_stack_ok(0, 65536) && osc_launch_stack_ok(65536, 65536)); + CHECK(!osc_launch_stack_ok(65552, 65536) && !osc_launch_stack_ok(65537, 65536) && !osc_launch_stack_ok(1048576, 65536)); + /* a workspace must not overlap the launcher state (slot0) or the input buffer: disjoint test */ + { + const uint64_t slot = 0x80000, slen = 0x40000; + CHECK(osc_launch_disjoint(0x100000, 4096, slot, slen)); /* clear of it */ + CHECK(!osc_launch_disjoint(slot, 4096, slot, slen)); /* starts inside slot0 */ + CHECK(!osc_launch_disjoint(slot - 4096, 8192, slot, slen)); /* straddles the start */ + CHECK(!osc_launch_disjoint(slot + slen - 4096, 8192, slot, slen)); /* straddles the end */ + CHECK(osc_launch_disjoint(slot - 4096, 4096, slot, slen)); /* ends exactly at its start */ + CHECK(osc_launch_disjoint(slot + slen, 4096, slot, slen)); /* begins exactly at its end */ + CHECK(!osc_launch_disjoint(slot - 8, ~0ull, slot, slen)); /* a wrapping range overlaps */ + CHECK(osc_launch_disjoint(slot, 4096, 0, 0) && osc_launch_disjoint(slot, 0, slot, slen)); /* empty: nothing */ + CHECK(!osc_launch_disjoint(0x100000, 4096, 0x100040, 5)); /* an input buffer inside the workspace */ + } + CHECK(osc_launch_ws_pages_ok(0) && osc_launch_ws_pages_ok(1) && osc_launch_ws_pages_ok(32)); + CHECK(!osc_launch_ws_pages_ok(33) && !osc_launch_ws_pages_ok(0xffffffffull) && !osc_launch_ws_pages_ok(~0ull)); + for (uint64_t pages = 0; pages <= 33; pages++) { + uint64_t len = pages * 4096, cells = len / 8; + uint64_t whole[2] = { ws, cells }, over[2] = { ws, cells + 1 }; + uint64_t last[2] = { ws + len - 8, 1 }, past[2] = { ws + len, 1 }; + uint64_t before[2] = { ws - 8, 1 }; + if (pages == 0) { + CHECK(!osc_launch_ranges_owned(kc, 2, past, in, 16, ws, 0)); /* no workspace: nothing owned */ + continue; + } + CHECK(osc_launch_ranges_owned(kc, 2, whole, in, 16, ws, len)); /* ptr+len ends exactly at the end */ + CHECK(!osc_launch_ranges_owned(kc, 2, over, in, 16, ws, len)); /* one cell too many */ + CHECK(osc_launch_ranges_owned(kc, 2, last, in, 16, ws, len)); /* the last cell */ + CHECK(!osc_launch_ranges_owned(kc, 2, past, in, 16, ws, len)); /* first cell past the end */ + CHECK(!osc_launch_ranges_owned(kc, 2, before, in, 16, ws, len)); + } +} + +int main(void) +{ + launch_txt(); + differential(); + ownership(); + workspace_bounds(); + budget(); + classify(); + fixture_unit(); + return ck_t_verdict("test_osc_launch"); +} diff --git a/scripts/.crumb b/scripts/.crumb index b9eb9d93..5de53809 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T11:48:48Z", + "compiled_at": "2026-10-08T13:03:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:7911dc6ee76b1fbf7fdc8a7593a34cccf8736783af2ae03ad52f57315bad24eb", + "digest": "sha256:6a8bd5f9f008c9388ba829899949836325b9dee35482324ae0ad5159334806e2", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 73, - "generated_at_commit": "f65912aa75332b739f2d408118af9f2de7ee6c57", - "source_tree": "sha256:ea47cf7d1dc97c81b749d0a4ba5ebfdf25b63dc2afcc2315e3c78836708bd78c" + "files": 74, + "generated_at_commit": "4b0e3dbcc3ea6eae9000be3953a5121763f34d8c", + "source_tree": "sha256:69d946b32f1edb43353d8ef660bb29c0f72262ddb5438b684482753fe0de03da" }, "owner_lane": "", "provenance": { diff --git a/scripts/ck_gates.sh b/scripts/ck_gates.sh index bf9f4a85..a63c4694 100755 --- a/scripts/ck_gates.sh +++ b/scripts/ck_gates.sh @@ -11,10 +11,11 @@ # scripts/qemu_ck_keyboard_test.sh, scripts/qemu_ck_fpu_test.sh, # scripts/qemu_ck_infer_test.sh, scripts/qemu_ck_screen_test.sh, # scripts/qemu_ck_console_test.sh, -# scripts/qemu_ck_rollback_test.sh, scripts/qemu_ck_osc_unit_test.sh), and prints +# scripts/qemu_ck_rollback_test.sh, scripts/qemu_ck_osc_unit_test.sh, +# scripts/qemu_ck_osc_launch_test.sh), and prints # one line per gate: # AIENOS_CK_: PASS|FAIL|NOT_RUN [(reason)] -# for M1 M3 SMMU NVME_SHUTDOWN P2_ARTIFACT M0_ROLLBACK OSC_UNIT M4_NVME M4_STORE M4_STORE_CRASH +# for M1 M3 SMMU NVME_SHUTDOWN P2_ARTIFACT M0_ROLLBACK OSC_UNIT OSC_LAUNCH M4_NVME M4_STORE M4_STORE_CRASH # M4_CONTINUITY M4_RECOVERY M4_ALLEN ARGUS1_REVOKE KEYBOARD NET SMP DISK_LAYOUT FPU INFER SCREEN CONSOLE. Gates with no C # implementation print NOT_RUN (MISSING_IMPLEMENTATION: ) and never # run anything. A missing child script, a child that reports NOT_RUN, a child @@ -63,6 +64,7 @@ set -uo pipefail # console -> verdict line from scripts/qemu_ck_console_test.sh (C-only: sustained serial + USB console session in a TEST-ONLY QEMU image; NOT_RUN on gate lock or quiet flag) # rollback -> verdict line from scripts/qemu_ck_rollback_test.sh (C image as the one-time BootNext candidate, AAVMF) # osc -> verdict line from scripts/qemu_ck_osc_unit_test.sh (OSC unit admission, OSC_UNIT_ARTIFACT v1; QEMU, TEST signer, not physical) +# osc_launch -> verdict line from scripts/qemu_ck_osc_launch_test.sh (OSC unit task launch, OSC_UNIT_ARTIFACT v1 section 9; QEMU, TEST signer, not physical) # missing -> NOT_RUN (MISSING_IMPLEMENTATION), never run, never PASS # =========================================================================== CK_GATE_TABLE=' @@ -73,6 +75,7 @@ NVME_SHUTDOWN|store|- P2_ARTIFACT|artifact|- M0_ROLLBACK|rollback|- OSC_UNIT|osc|- +OSC_LAUNCH|osc_launch|- M4_NVME|store|- M4_STORE|store|- M4_STORE_CRASH|crash|- @@ -89,7 +92,7 @@ INFER|infer|- SCREEN|screen|- CONSOLE|console|- ' -CHILDREN=(boot store net artifact smp crash disk cont recov allen kbd fpu infer screen console rollback osc) +CHILDREN=(boot store net artifact smp crash disk cont recov allen kbd fpu infer screen console rollback osc osc_launch) # =========================================================================== repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -144,6 +147,7 @@ set_default_children() { [console]="${repo_root}/scripts/qemu_ck_console_test.sh" [rollback]="${repo_root}/scripts/qemu_ck_rollback_test.sh" [osc]="${repo_root}/scripts/qemu_ck_osc_unit_test.sh" + [osc_launch]="${repo_root}/scripts/qemu_ck_osc_launch_test.sh" ) } @@ -373,11 +377,11 @@ self_test() { } expect_missing_all() { local g - for g in P2_ARTIFACT M0_ROLLBACK OSC_UNIT M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY M4_ALLEN KEYBOARD DISK_LAYOUT FPU INFER SCREEN CONSOLE; do expect "${g}" NOT_RUN; done # P2_ARTIFACT: no artifact child in A..G; M4_STORE_CRASH: no crash child in A..J and R; DISK_LAYOUT: no disk child in A..S + for g in P2_ARTIFACT M0_ROLLBACK OSC_UNIT OSC_LAUNCH M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY M4_ALLEN KEYBOARD DISK_LAYOUT FPU INFER SCREEN CONSOLE; do expect "${g}" NOT_RUN; done # P2_ARTIFACT: no artifact child in A..G; M4_STORE_CRASH: no crash child in A..J and R; DISK_LAYOUT: no disk child in A..S } scenario() { # NAME BOOT_SCRIPT STORE_SCRIPT [NET_SCRIPT] [ARTIFACT_SCRIPT] [SMP_SCRIPT] [CRASH_SCRIPT] [DISK_SCRIPT] (absent: missing) scen="$1" - declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.sh}" [artifact]="${5:-${tmp}/kids/no_artifact_child.sh}" [smp]="${6:-${tmp}/kids/no_smp_child.sh}" [crash]="${7:-${tmp}/kids/no_crash_child.sh}" [disk]="${8:-${tmp}/kids/no_disk_child.sh}" [cont]="${tmp}/kids/no_cont_child.sh" [recov]="${tmp}/kids/no_recov_child.sh" [allen]="${tmp}/kids/no_allen_child.sh" [kbd]="${kbd_kid:-${tmp}/kids/no_kbd_child.sh}" [fpu]="${tmp}/kids/no_fpu_child.sh" [infer]="${tmp}/kids/no_infer_child.sh" [screen]="${tmp}/kids/no_screen_child.sh" [console]="${console_kid:-${tmp}/kids/no_console_child.sh}" [rollback]="${rollback_kid:-${tmp}/kids/no_rollback_child.sh}" [osc]="${osc_kid:-${tmp}/kids/no_osc_child.sh}") + declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.sh}" [artifact]="${5:-${tmp}/kids/no_artifact_child.sh}" [smp]="${6:-${tmp}/kids/no_smp_child.sh}" [crash]="${7:-${tmp}/kids/no_crash_child.sh}" [disk]="${8:-${tmp}/kids/no_disk_child.sh}" [cont]="${tmp}/kids/no_cont_child.sh" [recov]="${tmp}/kids/no_recov_child.sh" [allen]="${tmp}/kids/no_allen_child.sh" [kbd]="${kbd_kid:-${tmp}/kids/no_kbd_child.sh}" [fpu]="${tmp}/kids/no_fpu_child.sh" [infer]="${tmp}/kids/no_infer_child.sh" [screen]="${tmp}/kids/no_screen_child.sh" [console]="${console_kid:-${tmp}/kids/no_console_child.sh}" [rollback]="${rollback_kid:-${tmp}/kids/no_rollback_child.sh}" [osc]="${osc_kid:-${tmp}/kids/no_osc_child.sh}" [osc_launch]="${osc_launch_kid:-${tmp}/kids/no_osc_launch_child.sh}") run_children 2>/dev/null evaluate_table >"${tmp}/${scen}.out" } @@ -393,8 +397,8 @@ self_test() { "$(fake smpA 0 'PASS 3 secondary cores checked in' 'AIENOS_CK_SMP_MUTATION: FAIL' 'AIENOS_CK_SMP: PASS')" expect M1 PASS; expect M3 PASS; expect M4_NVME PASS; expect M4_STORE PASS; expect ARGUS1_REVOKE PASS; expect SMMU PASS; expect NVME_SHUTDOWN PASS; expect NET PASS; expect SMP PASS; expect_missing_all count_rows - [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "9/0/13/22" && ${overall} == NOT_ALL_GATES_PASS ]] \ - && ok "A: counts 9/0/13 of 22, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" + [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "9/0/14/23" && ${overall} == NOT_ALL_GATES_PASS ]] \ + && ok "A: counts 9/0/14 of 23, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" [[ "$(nvme_dma_mode)" == "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately" ]] && ok "A: confined DMA mode recorded from the store PASS lines" || bad "A: dma mode '$(nvme_dma_mode)'" grep -qxF "AIENOS_CK_M4_NVME: PASS (${M4_NVME_PASS_NOTE})" "${tmp}/A.out" \ && ok "A: M4_NVME PASS line carries the confined-mode note" || bad "A: M4_NVME PASS line lacks the note" @@ -406,7 +410,7 @@ self_test() { && ok "a missing-source row is NOT_RUN (MISSING_IMPLEMENTATION: reason)" || bad "missing-source row not NOT_RUN" grep -q '^AIENOS_CK_KEYBOARD: NOT_RUN' "${tmp}/A.out" \ && ok "A: KEYBOARD claimed PASS by the store child stays NOT_RUN without its own child" || bad "A: KEYBOARD line wrong" - [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 22 ]] && ok "A: exactly 22 verdict lines" || bad "A: verdict line count" + [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 23 ]] && ok "A: exactly 23 verdict lines" || bad "A: verdict line count" # B: boot FAIL; store script missing -> its three gates NOT_RUN, never PASS. scenario B "$(fake bootB 1 'FAIL kernel: alive' 'AIENOS_CK_M3: FAIL' 'AIENOS_CK_M1: FAIL')" "${tmp}/kids/does_not_exist.sh" @@ -539,6 +543,14 @@ self_test() { scenario OB "$(fake bootOB 0 'AIENOS_CK_M1: PASS')" "$(fake storeOB 0 'AIENOS_CK_OSC_UNIT: PASS')" expect OSC_UNIT FAIL unset osc_kid + # LA, LB: OSC_LAUNCH comes only from its own child (scripts/qemu_ck_osc_launch_test.sh). + osc_launch_kid="$(fake olA 0 'PASS x' 'AIENOS_CK_OSC_LAUNCH: PASS')" + scenario LA "$(fake bootLA 0 'AIENOS_CK_M1: PASS')" "$(fake storeLA 0 'AIENOS_CK_OSC_LAUNCH: FAIL')" + expect OSC_LAUNCH PASS + osc_launch_kid="$(fake olB 1 'FAIL y' 'AIENOS_CK_OSC_LAUNCH: FAIL')" + scenario LB "$(fake bootLB 0 'AIENOS_CK_M1: PASS')" "$(fake storeLB 0 'AIENOS_CK_OSC_LAUNCH: PASS')" + expect OSC_LAUNCH FAIL + unset osc_launch_kid # Receipt: named by its content hash, valid JSON, physical NOT_RUN, never overwritten. scenario R "$(fake bootR 0 'AIENOS_CK_M1: PASS')" "$(fake storeR 0 'AIENOS_CK_M4_NVME: PASS')" @@ -561,10 +573,10 @@ self_test() { # Restore the clean-tree receipt as the one the checks below look at. write_receipt if command -v jq >/dev/null; then - jq -e '.physical == "NOT_RUN" and (.gates | length) == 22 and .verdict == "NOT_ALL_GATES_PASS" + jq -e '.physical == "NOT_RUN" and (.gates | length) == 23 and .verdict == "NOT_ALL_GATES_PASS" and ([.gates[] | select(.id == "M1")][0].verdict == "PASS") and ([.gates[] | select(.id == "ARGUS1_REVOKE")][0].verdict == "FAIL") - and (.children | length) == 17 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ + and (.children | length) == 18 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ && ok "receipt is valid JSON (jq) with expected fields" || bad "receipt JSON invalid or fields wrong" else echo "NOT_RUN jq not installed; JSON validity not machine-checked"; jq_skipped=1 @@ -577,18 +589,18 @@ self_test() { bad "an existing receipt was overwritten or the clash was not refused" fi - # The gate table parses: 22 rows, known sources, reasons only on missing rows. + # The gate table parses: 23 rows, known sources, reasons only on missing rows. local g s w rows=0 tbad=0 while IFS='|' read -r g s w; do [[ -n "${g}" ]] || continue rows=$((rows + 1)) case "${s}" in - boot|store|net|artifact|smp|crash|disk|cont|recov|allen|kbd|fpu|infer|screen|console|rollback|osc) [[ "${w}" == - ]] || tbad=1 ;; + boot|store|net|artifact|smp|crash|disk|cont|recov|allen|kbd|fpu|infer|screen|console|rollback|osc|osc_launch) [[ "${w}" == - ]] || tbad=1 ;; missing) [[ -n "${w}" && "${w}" != - ]] || tbad=1 ;; *) tbad=1 ;; esac done <<<"${CK_GATE_TABLE}" - [[ ${tbad} == 0 && ${rows} == 22 ]] && ok "gate table: 22 rows well-formed" || bad "gate table malformed (${rows} rows)" + [[ ${tbad} == 0 && ${rows} == 23 ]] && ok "gate table: 23 rows well-formed" || bad "gate table malformed (${rows} rows)" # Dirty-tree refusal, end to end, on a private clone (never this tree). # Both runs stop before any child script (no QEMU). diff --git a/scripts/qemu_ck_osc_launch_test.sh b/scripts/qemu_ck_osc_launch_test.sh new file mode 100755 index 00000000..8f2f5177 --- /dev/null +++ b/scripts/qemu_ck_osc_launch_test.sh @@ -0,0 +1,198 @@ +#!/usr/bin/env bash +# AIENOS_CK_OSC_LAUNCH gate: task launch of an admitted OSC unit (C3-3a) in the C kernel, booted in +# QEMU AArch64 + UEFI (AAVMF). Contract: OSC_UNIT_ARTIFACT.md section 9 (aien-protocols PR #17). +# +# Label: QEMU (aarch64 virt), TEST signer, not physical. Nothing here ran on a Spark or any real machine. +# The only key is the spec's THROWAWAY TEST key. Every launch line the kernel prints carries the label. +# +# Two TEST-signed units are written into the sealed C Store of a GPT boot disk image and read back by the +# kernel's store stage (the path of qemu_ck_osc_unit_test.sh): +# a01_valid_min.unit the spec's vector unit (compiled by oscc): add, first_byte +# l01_launch_fns.unit hand-assembled test functions (tests/fixtures/osc_unit/launch/l01.S, built by +# make-l01.sh with the spec's own generator helpers): trap, spin, peek0, poke_rt, +# bare_brk, exec_stack, overflow, counter +# One boot of the qualification image built with CK_SEED0B_TEST_ANCHOR=1 CK_OSC_LAUNCH_TEST=1. After +# admission the kernel launches a fixed script of calls as EL0 tasks and prints one "osc_launch:" line each. +# This gate checks: +# RETURNED with the exact value; refused bad-argument, unknown-name and out-of-window launches (nothing +# ran); TRAPPED through the runtime trap service; a trap code outside 1..14 and a brk reached directly +# are OUTCOME_UNKNOWN, never TRAPPED; budget exhaustion is OUTCOME_UNKNOWN (TICK_OVERRUN); a null read, +# a write to OscRt, a jump into the stack (W^X) and a stack overflow are contained faults and a launch +# right after each succeeds in the same boot; the task is torn down every time (no page left mapped, +# slot reusable); a caller-owned workspace keeps its state across calls. +# Last line: AIENOS_CK_OSC_LAUNCH: PASS|FAIL|NOT_RUN. +# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +verdict=AIENOS_CK_OSC_LAUNCH + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; echo "${verdict}: NOT_RUN"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "${verdict}: NOT_RUN"; exit 2; } + +# Machine quiet flag (read only) and the QEMU gate lock (one gate at a time): +# scripts/lib_gate_hold.sh (aienos#278). +. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib_gate_hold.sh" +if ! gh_quiet_check || ! gh_lock_take "qemu_ck_osc_launch_test" "${AIENOS_GATE_MINUTES:-60}"; then + echo "NOT_RUN ${gh_why}" + echo "${verdict}: NOT_RUN" + exit 3 +fi +# Release only this run's own gate lock record, at most once. +release_flag() { gh_lock_release; } +work="$(mktemp -d)" +cleanup() { rm -rf "${work}"; release_flag; } +trap cleanup EXIT +failed=0 +pass() { echo "PASS $1"; } +fail() { echo "FAIL $1"; failed=1; } + +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +out_prod="${AIENOS_CK_OUT_PROD:-${repo_root}/target/native-kernel}" +out_launch="${AIENOS_CK_OUT_LAUNCH:-${repo_root}/target/native-kernel-osc-launch-test}" +mk() { make -s -C native/kernel CROSS="${cross}" AIENOS_COMMIT="${commit}" "$@" >/dev/null; } +mk OUT="${out_launch}" CK_SEED0B_TEST_ANCHOR=1 CK_OSC_LAUNCH_TEST=1 full +make -s -C native/kernel OUT="${out_prod}" store-image gpt-image >/dev/null +simg="${out_prod}/host/ck_store_image" + +fix="native/kernel/tests/fixtures/osc_unit" +files=("${fix}/vectors/a01_valid_min.unit" "${fix}/launch/l01_launch_fns.unit" "${fix}/vectors/a06_valid_limits_at_max.unit" "${fix}/launch/l02_stack_over.unit") +a01_line=$(grep -E '^a01_valid_min\.unit ' "${fix}/vectors/expected.txt") +a01_digest=$(sed -E 's/.* unit_digest=([0-9a-f]{64}) .*/\1/' <<<"${a01_line}") +[[ ${#a01_digest} == 64 ]] || fail "expected UnitDigest read from the frozen expected.txt" + +disk="${work}/nvme.img" +"${out_prod}/host/ck_gpt_image" create "${disk}" 512 64 aienos-middle >/dev/null || fail "GPT boot disk image created" +if "${simg}" build "${disk}" 512 "${files[@]}" >"${work}/build.txt" 2>&1; then pass "boot disk built: $(head -1 "${work}/build.txt")" +else fail "boot disk build: $(head -3 "${work}/build.txt" | tr '\n' ' ')"; fi +"${simg}" list "${disk}" 512 >"${work}/list.txt" 2>&1 || fail "host read-back of the boot disk Store" +for f in "${files[@]}"; do + grep -qxF "$(basename "${f}") bytes=$(stat -c %s "${f}") sha256=$(sha256sum "${f}" | cut -d' ' -f1)" "${work}/list.txt" \ + || fail "host read-back of $(basename "${f}")" +done + +boot() { # image, serial text output, disk image + local esp="${work}/esp" log="${work}/serial.log" started status + rm -rf "${esp}" + mkdir -p "${esp}/EFI/BOOT" "${esp}/EFI/AIENOS" + touch "${esp}/EFI/AIENOS/BOOTREPORT.TXT" + cp "$1" "${esp}/EFI/BOOT/BOOTAA64.EFI" + cp "${vars_fd}" "${work}/vars.fd" + started=$(date +%s) + set +e + nice -n 10 timeout "${AIENOS_QEMU_TIMEOUT:-300}" qemu-system-aarch64 \ + -M virt,virtualization=on,gic-version=3,iommu=smmuv3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${esp}" \ + -device virtio-blk-pci,drive=esp \ + -drive if=none,id=nvme0,format=raw,file="$3" \ + -device nvme,drive=nvme0,serial=aienos-nvme-test \ + -device ramfb -display none -nic none \ + -serial file:"${log}" -no-reboot + status=$? + set -e + tr -d '\r' <"${log}" >"$2" + echo "qemu exit ${status} after $(( $(date +%s) - started )) s (commit ${commit:0:12})" + [[ "${status}" == 0 ]] || fail "QEMU exit status ${status} (124 = timeout)" +} +has() { grep -qE -- "$2" "$1"; } +check() { if has "$1" "$3"; then pass "$2"; else fail "$2"; fi; } + +serial="${work}/serial.txt" +cp "${disk}" "${work}/disk-run.img" +boot "${out_launch}/full/BOOTAA64.EFI" "${serial}" "${work}/disk-run.img" +release_flag + +check "${serial}" "left firmware and entered the kernel" "kernel: alive" +check "${serial}" "kernel read all four candidates from the boot disk Store" "^artifact_candidates: 4$" +if has "${serial}" "^report-truncated:"; then fail "kernel report lines were truncated"; else pass "no kernel report line was truncated"; fi +check "${serial}" "final report reached the console" "report_kind: final" +if has "${serial}" "report_kind: (panic|fault)"; then fail "panic or fault reported (a unit fault must stay contained)"; else pass "no kernel panic or fault report: unit faults stayed contained"; fi +check "${serial}" "a01 admitted with the frozen UnitDigest" "^osc_unit: a01_valid_min\\.unit ACCEPT unit_digest=${a01_digest} " +check "${serial}" "l01 admitted (every hand-assembled word is in the OSC subset)" "^osc_unit: l01_launch_fns\\.unit ACCEPT .* funcs=14 caps=0 signer=TEST$" +check "${serial}" "totals: 4 seen, 4 accepted" "^osc_units: seen=4 accepted=4 refused=0 oversize=0 " +check "${serial}" "launch policy line, labelled" "^osc_launch_policy: units=4 code_max=65536 stack_max=65536 in_max=4096 ws_max=32 pages; 1 tick = 10 ms; QEMU \\(aarch64 virt\\), TEST signer, not physical$" + +label='QEMU \(aarch64 virt\), TEST signer, not physical' +tail_run="ticks=[0-9]+ budget=[0-9]+ pages_mapped=[1-9][0-9]* page_tables_zeroed=1 slot_free=1; ${label}\$" +tail_ref="ticks=0 budget=0 pages_mapped=0 page_tables_zeroed=1 slot_free=1; ${label}\$" +# lline NAME UNIT CALL RESULT-REGEX [ref]: one launch line +lline() { + local t="${tail_run}" + [[ "${5:-}" == ref ]] && t="${tail_ref}" + check "${serial}" "$1" "^osc_launch: $2 $3 -> $4 ${t}" +} +a=a01_valid_min.unit +l=l01_launch_fns.unit +lline "RETURNED with the exact value: add(1000000007,998244353) = 1998244360" $a 'add\(1000000007,998244353\)' 'RETURNED value=1998244360' +lline "refused bad argument count: add(5) is LAUNCH_ARG_SHAPE (41), nothing ran" $a 'add\(5\)' 'REFUSED_AT_ADMISSION code=41 name=LAUNCH_ARG_SHAPE' ref +lline "refused unknown name: nosuch is LAUNCH_BAD_ENTRY (40)" $a 'nosuch\(\)' 'REFUSED_AT_ADMISSION code=40 name=LAUNCH_BAD_ENTRY' ref +lline "refused wrong case: ADD is LAUNCH_BAD_ENTRY (40)" $a 'ADD\(1,2\)' 'REFUSED_AT_ADMISSION code=40 name=LAUNCH_BAD_ENTRY' ref +lline "RETURNED: first_byte over the read-only input window = 90 ('Z')" $a 'first_byte\(in\+0,4\)' 'RETURNED value=90' +lline "refused slice outside the caller's input window (ownership), LAUNCH_ARG_SHAPE (41)" $a 'first_byte\(4096,16\)' 'REFUSED_AT_ADMISSION code=41 name=LAUNCH_ARG_SHAPE' ref +lline "TRAPPED code 3 through the runtime trap service" $l 'trap\(3\)' 'TRAPPED trap_code=3' +lline "TRAPPED code 14 (the top of the table)" $l 'trap\(14\)' 'TRAPPED trap_code=14' +lline "trap code 15 is OUTCOME_UNKNOWN (TRAP_CODE_UNKNOWN=4), never TRAPPED" $l 'trap\(15\)' 'OUTCOME_UNKNOWN unknown_reason=4' +lline "a brk reached directly is OUTCOME_UNKNOWN (FAULT=1), never TRAPPED" $l 'bare_brk\(\)' 'OUTCOME_UNKNOWN unknown_reason=1' +check "${serial}" "budget exhaustion: spin() is OUTCOME_UNKNOWN (TICK_OVERRUN=2) after exactly 5 ticks of budget 5" \ + "^osc_launch: ${l} spin\\(\\) -> OUTCOME_UNKNOWN unknown_reason=2 ticks=5 budget=5 pages_mapped=[1-9][0-9]* page_tables_zeroed=1 slot_free=1; ${label}\$" +lline "after the budget kill, the next launch succeeds: add(40,2) = 42" $a 'add\(40,2\)' 'RETURNED value=42' +lline "contained fault: a null read is OUTCOME_UNKNOWN (FAULT=1)" $l 'peek0\(\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "after the fault, the next launch succeeds in the same boot: add(20,22) = 42" $a 'add\(20,22\)' 'RETURNED value=42' +lline "contained fault: a write to OscRt (read-only to the unit) is OUTCOME_UNKNOWN (FAULT=1)" $l 'poke_rt\(\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "W^X: a jump into the stack (written code) is OUTCOME_UNKNOWN (FAULT=1), not RETURNED 42" $l 'exec_stack\(\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "contained fault: a stack overflow is OUTCOME_UNKNOWN (FAULT=1)" $l 'overflow\(\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "after four faults, the next launch succeeds: add(6,36) = 42" $a 'add\(6,36\)' 'RETURNED value=42' +# order: the successful launch comes after the fault it follows +ln() { grep -nE -- "^osc_launch: $1 $2 " "${serial}" | head -1 | cut -d: -f1; } +n_peek=$(ln "${l}" 'peek0\(\)'); n_add=$(ln "${a}" 'add\(20,22\)') +if [[ -n "${n_peek}" && -n "${n_add}" && "${n_add}" -gt "${n_peek}" ]]; then pass "the launch after the contained fault was run after it (line ${n_peek} then ${n_add})" +else fail "the launch after the contained fault was run after it"; fi +# workspace: first workspace counts 1,2,3 across three calls, a fresh one starts at 1 again +vals=$(grep -E -- "^osc_launch: ${l} counter\\(ws\\+0,1\\) -> RETURNED value=" "${serial}" | sed -E 's/.*value=([0-9]+) .*/\1/' | tr '\n' ' ') +if [[ "${vals}" == "1 2 3 1 " ]]; then pass "caller-owned workspace persists across calls: values 1 2 3, a fresh workspace starts again at 1" +else fail "workspace persistence (got: ${vals})"; fi +lline "refused misaligned cells pointer (ws+4): LAUNCH_ARG_SHAPE (41)" $l 'counter\(ws\+4,1\)' 'REFUSED_AT_ADMISSION code=41 name=LAUNCH_ARG_SHAPE' ref +lline "re-entry with a 23-page workspace, last cell (ws+94200) touched: counter 1" $l 'counter\(ws\+94200,1\)' 'RETURNED value=1' +lline "re-entry, same 23-page workspace: counter state preserved, 2" $l 'counter\(ws\+94200,1\)' 'RETURNED value=2' +lline "refused 33-page workspace (over the 32-page cap): RESOURCE_UNAVAILABLE (30), nothing ran" $l 'counter\(ws\+0,1\)' 'REFUSED_AT_ADMISSION code=30 name=RESOURCE_UNAVAILABLE' ref +# review additions: limits, memory protection, register clearing, workspace edges +a6=a06_valid_limits_at_max.unit; l2=l02_stack_over.unit +lline "a06 (declared stack 1 MiB, over the 64 KiB launcher maximum): LIMIT_EXCEEDED (14), before any reservation" $a6 'add\(1,2\)' 'REFUSED_AT_ADMISSION code=14 name=LIMIT_EXCEEDED' ref +lline "stack just over the maximum (65552 = 65536 + 16, the smallest legal value above it): LIMIT_EXCEEDED (14)" $l2 'peek0\(\)' 'REFUSED_AT_ADMISSION code=14 name=LIMIT_EXCEEDED' ref +lline "after the limit refusals, a launch succeeds: add(3,4) = 7" $a 'add\(3,4\)' 'RETURNED value=7' +lline "contained fault: a read of a kernel virtual address (not address 0) is OUTCOME_UNKNOWN (FAULT=1)" $l 'peek_kernel\(kernel\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "after the kernel-address read, a launch succeeds: add(5,6) = 11" $a 'add\(5,6\)' 'RETURNED value=11' +lline "UXN: calling a valid ret pre-loaded in the caller workspace (ws+512) FAULTs (OUTCOME_UNKNOWN FAULT=1) instead of returning 42" $l 'jump_ws\(ws\+512,1\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "after the workspace branch, a launch succeeds: add(7,8) = 15" $a 'add\(7,8\)' 'RETURNED value=15' +lline "UXN: calling valid ret bytes (c0 03 5f d6) placed in the input window FAULTs (OUTCOME_UNKNOWN FAULT=1) instead of returning 42" $l 'jump_in\(in\+0,4\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "after the input-window branch, a launch succeeds: add(9,10) = 19" $a 'add\(9,10\)' 'RETURNED value=19' +lline "a task dirties x1..x29 and returns 1" $l 'dirty\(\)' 'RETURNED value=1' +lline "the next task sees x0..x29 (except x7, the OscRt pointer) all zero: OR of them = 0" $l 'regs_or\(\)' 'RETURNED value=0' +lline "the first byte past the workspace (ws + pages*4096) is OUTCOME_UNKNOWN (FAULT=1), contained" $l 'touch_past\(ws\+16376,1\)' 'OUTCOME_UNKNOWN unknown_reason=1' +lline "after the past-the-end read, a launch succeeds: add(11,12) = 23" $a 'add\(11,12\)' 'RETURNED value=23' +lline "workspace with null memory and pages>0: RESOURCE_UNAVAILABLE (30), nothing mapped" $l 'counter\(ws\+8,1\)' 'REFUSED_AT_ADMISSION code=30 name=RESOURCE_UNAVAILABLE' ref +lline "workspace with unaligned memory: RESOURCE_UNAVAILABLE (30), nothing mapped" $l 'counter\(ws\+16,1\)' 'REFUSED_AT_ADMISSION code=30 name=RESOURCE_UNAVAILABLE' ref +lline "workspace overlapping the launcher's own state: RESOURCE_UNAVAILABLE (30), nothing mapped" $l 'counter\(ws\+24,1\)' 'REFUSED_AT_ADMISSION code=30 name=RESOURCE_UNAVAILABLE' ref +lline "workspace overlapping the input buffer: RESOURCE_UNAVAILABLE (30), nothing mapped" $l 'counter\(ws\+32,1\)' 'REFUSED_AT_ADMISSION code=30 name=RESOURCE_UNAVAILABLE' ref +lline "after the workspace refusals, a launch succeeds: add(13,14) = 27" $a 'add\(13,14\)' 'RETURNED value=27' +check "${serial}" "summary: 19 returned, 2 trapped, 12 refused, 11 unknown" \ + "^osc_launches: returned=19 trapped=2 refused=12 unknown=11; ${label}\$" +# every launch line carries the label; the teardown columns never show a page left behind +nl=$(grep -c '^osc_launch: ' "${serial}" || true) +nlab=$(grep -cE "^osc_launch: .*; ${label}\$" "${serial}" || true) +[[ "${nl}" == 44 && "${nlab}" == 44 ]] && pass "all 44 launch lines carry the label" || fail "launch lines labelled (${nlab} of ${nl})" +if grep -E '^osc_launch: ' "${serial}" | grep -vqE 'page_tables_zeroed=1 slot_free=1;'; then fail "a task left pages mapped or its slot busy"; else pass "every task was torn down: page_tables_zeroed=1, slot_free=1"; fi + +if [[ -n "${AIENOS_LOG_DIR:-}" ]]; then cp "${serial}" "${AIENOS_LOG_DIR}/qemu_ck_osc_launch_serial.log"; fi +if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- serial (osc lines) ----"; grep -E "^(osc_|artifact|kernel|report_kind|panic|fault)" "${serial}" | head -80 || true +fi +echo "label: QEMU (aarch64 virt), TEST signer, not physical" +if [[ "${failed}" == 0 ]]; then echo "${verdict}: PASS"; else echo "${verdict}: FAIL"; exit 1; fi