Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-bridge/patches/0a442a51824c179f # omega-bridge Omega-first language interoperability: checked conversion backends and native language bindings Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-bridge#45 (code only) closed derived `0a442a51824c179f` #45 Imported from GitHub aien-dev/omega-bridge#45 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `7af4d11c3a9c853abc20a99f97d0a4f01524bb66` · Head `72d6dbc9ab4722bbab266fb80c821b3dd3f43e4e` github-advanced-security[bot] commented on `tests/native/v2/fsom2.c` line 80 on 2026-10-30 15:21 UTC ## CodeQL / Call to `memset` may be deleted Call to memset may be deleted by the compiler. Show more details github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-30 15:21 UTC ### Fetch it A git bundle of the pull request's head, 24117 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/omega-bridge/patches/0a442a51824c179f.bundle -o 0a442a51824c179f.bundle git fetch 0a442a51824c179f.bundle refs/pull/45/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-bridge 45 72d6dbc9ab4722bbab266fb80c821b3dd3f43e4e ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-bridge","number":45,"url":"https://github.com/aien-dev/omega-bridge/pull/45","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:00Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/docs/NATIVE-ABI.md b/docs/NATIVE-ABI.md index 892c042..5885611 100644 --- a/docs/NATIVE-ABI.md +++ b/docs/NATIVE-ABI.md @@ -46,7 +46,8 @@ tools/native --target x86linux build/native-x86 \ ``` The x86 target is hosted Linux x86-64 SysV output. With `--freestanding` it emits -the same pure-scalar binding with a SysV adapter that runs on the caller's stack, +the same freestanding binding (pure-scalar OM-1 units, and OM-2 units with output +`fapic`, see below) with a SysV adapter that runs on the caller's stack, keeps the trap anchor in R12 and sets the owned-stack floor R15 to 0 (no bound check, as in the AArch64 freestanding binding). x86 code bytes are packed as little-endian `.quad` words plus a `.byte` tail; the assembled bytes are the @@ -263,8 +264,9 @@ guarded stack, stack-allocation status or hosted reentry restriction. The emitter validates every source token, including unused helpers, against the bounded function-mode integer-scalar subset: integer/bool types, decimal integer literals, scalar locals, functions, arithmetic, comparisons, control flow, contracts and traps. -Arrays (including local arrays), globals, text, host words, floating-point operations -and OM-2 units are refused with exit 110 and no output. Ordinary compiler source +Arrays (including local arrays), globals, text, host words and floating-point operations +are refused with exit 110 and no output, as is an OM-2 frame without its `omega-unit` +trailer. Ordinary compiler source validation still applies. As with hosted transport, framed source and machine bytes must come from the same pinned compiler invocation; this is not an arbitrary-bytecode sandbox. `tools/native` snapshots each input once in private scratch storage; profile @@ -280,6 +282,35 @@ nested trap unwind, independent scalar units, concurrent threads, non-pure sourc refusals, a pthread-emitter mutant, failed inspectors and a deterministic source-swap control whose old-reread mutant admits mismatched source/code and is caught. +**OM-2 freestanding** (the same `--freestanding` flag with an OM-2 unit; output `freest`). +An OM-2 unit without host effects is accepted: its compiler bytes are embedded unchanged +and bound as `omega2_`, with the same argument checks as output `c` (views, layouts, +out, overlaps). Each out parameter is a zero-filled, 16-byte-aligned buffer in the entry's +own frame, rounded up to 16 bytes, passed in its slot and copied back to the caller only +after status 0; a nonzero status (a trap, a refused argument) leaves the caller's buffer as +it was. The runtime table has one entry, the trap, and nothing else: no TLS, no heap, no +stack mapping, no pthread and no stack guard, so the caller must provide a stack large +enough for the compiled functions. The only C library calls are `memset` and `memmove`. + +With an OM-2 unit, `--freestanding` also installs `omega_api_decl.h` and +`omega_api_defs.{c,o}` (output `fapic`): the same prototypes as output `apih`, but each +definition calls `__builtin_trap()` on a nonzero status instead of `abort()`, so the +definition object imports no C library function either. It does not install `omega_api.h`, +whose inline wrappers call `abort()`. The two objects are inspected together: a global +definition in one satisfies a reference in the other (the wrappers calling `omega2_*`), +and every other undefined symbol must be on the GPU_FS_LINK allowlist. +`tests/native/test_freestanding_om2.py` (run by `tests/native/v2/run.sh`, step 10b) runs the +FIPS 180-4 digests of `sha256-om2.om` (empty, abc, the 448-bit message, a million `a` through a +split update), the untouched out buffer after a refused argument and after a trap, four threads +hashing concurrently, and the trap wrapper (exit 133, SIGTRAP); a mutant runtime that drops the +copy-back must leave the caller's 0xa5 pre-call fill in all four digests. +With `--target x86linux --freestanding` the same OM-2 units are bound through the x86 +SysV adapter, with the same out-buffer and import rules. `tests/native/x86/suite.py` +(step `freestanding_om2_x86`) cross-builds `fsom2.c` against that output and runs it under +QEMU: same digests, untouched out buffers and four threads, the trap wrapper (`ud2`, SIGILL), +and the copy-back mutant must leave the pre-call fill in all four digests. That is EMULATED +only; native x86 is NOT_RUN. + ## The declarations for each language (`tools/native`) `OMEGA_NATIVE_OMC= tools/native OUTDIR unit.om...` compiles the units with the selected @@ -537,6 +568,12 @@ the inline ones; it is compiled into the consumer's hosted binding (for the SHA (`-Wmissing-prototypes -Werror`). `omega_api.h` is unchanged, byte for byte. Use one form or the other in a program, not both: each defines the functions under the same names. +**Freestanding API** (output word `fapic`, installed as `omega_api_defs.c` by `--freestanding` +only, in place of the `apic` output). It is the same definitions except that a nonzero status +executes `__builtin_trap()` instead of calling `abort()`, so the object imports no C library +function and can be linked into a freestanding binding. The prototypes stay those of output +`apih`. + **Unsupported (caller precondition, not detected),** as the contract states: that the memory exists for `len` elements, is writable for edit, or stays alive during the call; forged lengths and read-only memory passed as edit. Function-mode stack exhaustion faults as in v1. Loops in the seeded compiler diff --git a/src/native.om b/src/native.om index dc401fd..bd87358 100644 --- a/src/native.om +++ b/src/native.om @@ -43,19 +43,26 @@ text fr "__asm__(\".section .text.omega_bridge,\\\"ax\\\",@progbits\\n.balign 4\ text pre "/* Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n * The Omega machine code below is embedded byte for byte as the seeded compiler wrote it.\n * This file only adapts the C calling convention to it. Regenerate it; do not edit it. */\n#include \n#include \n#include \n#include \n#define OMEGA_OK 0u\n#define OMEGA_BAD_ARG 32u\n#define OMEGA_REENTRY 33u\n#define OMEGA_BAD_RT 34u\n#define OMEGA_NO_STACK 35u\n#define OMBR_STACK (8u << 20)\n#define OMBR_GUARD (8u << 20)\n/* entry[2] is the trap entry (OSC-1 section 7). */\ntypedef struct ombr_rt { const void *entry[32]; } ombr_rt;\ntypedef struct ombr_span { uintptr_t lo, hi; int w; } ombr_span;\nstatic _Thread_local volatile sig_atomic_t ombr_active;\nstatic _Thread_local unsigned char *ombr_stk;\nstatic pthread_key_t ombr_key;\nstatic int ombr_keyok;\nstatic pthread_once_t ombr_once = PTHREAD_ONCE_INIT;\nuint32_t ombr_enter(const void *code, const uint64_t *args, const ombr_rt *rt, uint64_t *out, void *top)\n __attribute__((visibility(\"hidden\")));\nextern const unsigned char ombr_trap[] __attribute__((visibility(\"hidden\")));\nextern const unsigned char ombr_no_entry[] __attribute__((visibility(\"hidden\")));\n/* ombr_enter saves the callee-saved registers on the caller's stack, keeps that stack pointer in x19 and\n * runs the code on the binding's own stack. A normal return stores x0 through out and\n * returns 0. A runtime entry restores the stack pointer from x19 and returns a status; out is not\n * written. The seeded compiler never writes x19..x28. Runtime entries are reached by blr/br, so they\n * start with bti jc. */\n__asm__(\".text\\n.balign 4\\n.local ombr_enter\\n.hidden ombr_enter\\n.type ombr_enter,%function\\nombr_enter:\\n\"\n \"hint #34\\nstp x29,x30,[sp,#-176]!\\nmov x29,sp\\nstp x19,x20,[sp,#16]\\nstp x21,x22,[sp,#32]\\n\"\n \"stp x23,x24,[sp,#48]\\nstp x25,x26,[sp,#64]\\nstp x27,x28,[sp,#80]\\nstp d8,d9,[sp,#96]\\n\"\n \"stp d10,d11,[sp,#112]\\nstp d12,d13,[sp,#128]\\nstp d14,d15,[sp,#144]\\nstr x3,[sp,#160]\\n\"\n \"mov x19,sp\\nmov x16,x0\\nmov x17,x1\\nmov x7,x2\\nmov sp,x4\\n\"\n \"ldp x0,x1,[x17]\\nldp x2,x3,[x17,#16]\\nldp x4,x5,[x17,#32]\\nblr x16\\n\"\n \"mov sp,x19\\nldr x9,[sp,#160]\\nstr x0,[x9]\\nmov w0,#0\\n\"\n \"ombr_leave:\\nldp d14,d15,[sp,#144]\\nldp d12,d13,[sp,#128]\\nldp d10,d11,[sp,#112]\\n\"\n \"ldp d8,d9,[sp,#96]\\nldp x27,x28,[sp,#80]\\nldp x25,x26,[sp,#64]\\nldp x23,x24,[sp,#48]\\n\"\n \"ldp x21,x22,[sp,#32]\\nldp x19,x20,[sp,#16]\\nldp x29,x30,[sp],#176\\nret\\n.size ombr_enter,.-ombr_enter\\n\"\n \".local ombr_trap\\n.hidden ombr_trap\\n.type ombr_trap,%function\\nombr_trap:\\nhint #38\\n\"\n \"mov sp,x19\\nsub x2,x1,#1\\nmov w3,#34\\ncmp x2,#13\\ncsel w0,w1,w3,ls\\nb ombr_leave\\n\"\n \".size ombr_trap,.-ombr_trap\\n\"\n \".local ombr_no_entry\\n.hidden ombr_no_entry\\n.type ombr_no_entry,%function\\nombr_no_entry:\\nhint #38\\n\"\n \"mov sp,x19\\nmov w0,#34\\nb ombr_leave\\n.size ombr_no_entry,.-ombr_no_entry\\n\");\nstatic void ombr_free(void *p)\n{\n munmap(p, OMBR_STACK + OMBR_GUARD);\n}\nstatic void ombr_init(void)\n{\n ombr_keyok = pthread_key_create(&ombr_key, ombr_free) == 0;\n}\n/* The thread's Omega stack: OMBR_STACK usable bytes above an OMBR_GUARD no-access region. A function-mode\n * unit has no call cycles and at most 4 MiB of local arrays per function (OMEGESE, local arrays), so a frame that\n * would pass the bottom starts inside the guard and faults there; nothing below the guard is touched. */\nstatic unsigned char *ombr_stack(void)\n{\n if (ombr_stk)\n return ombr_stk;\n pthread_once(&ombr_once, ombr_init);\n if (!ombr_keyok)\n return 0;\n unsigned char *p = mmap(0, OMBR_STACK + OMBR_GUARD, PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);\n if (p == MAP_FAILED)\n return 0;\n if (mprotect(p, OMBR_GUARD, PROT_NONE) != 0 || pthread_setspecific(ombr_key, p) != 0) {\n munmap(p, OMBR_STACK + OMBR_GUARD);\n return 0;\n }\n ombr_stk = p + OMBR_GUARD + OMBR_STACK;\n return ombr_stk;\n}\nstatic int ombr_span_add(ombr_span *sp, unsigned *ns, const void *p, uint64_t n, uint64_t want, uint64_t es, int w)\n{\n uintptr_t lo = (uintptr_t)p;\n if (!p || n != want || lo % es != 0u || n > (UINTPTR_MAX - lo) / es)\n return 1;\n sp[*ns].lo = lo;\n sp[*ns].hi = lo + n * es;\n sp[*ns].w = w;\n (*ns)++;\n return 0;\n}\nstatic int ombr_overlap(const ombr_span *sp, unsigned ns)\n{\n for (unsigned i = 0; i < ns; i++)\n for (unsigned j = i + 1; j < ns; j++)\n if ((sp[i].w || sp[j].w) && sp[i].lo < sp[j].hi && sp[j].lo < sp[i].hi)\n return 1;\n return 0;\n}\n/* One read-only runtime table for every call and thread: the code only reads it (a write would fault). */\nstatic const ombr_rt ombr_rt_table = {{ ombr_no_entry, ombr_no_entry, ombr_trap, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry }};\nstatic uint32_t ombr_run(const void *code, const uint64_t *args, uint64_t *result, int has_value)\n{\n if (ombr_active)\n return OMEGA_REENTRY;\n ombr_active = 1;\n unsigned char *top = ombr_stack();\n if (!top) {\n ombr_active = 0;\n return OMEGA_NO_STACK;\n }\n uint64_t v = 0;\n uint32_t s = ombr_enter(code, args, &ombr_rt_table, &v, top);\n ombr_active = 0;\n if (s == OMEGA_OK)\n *result = has_value ? v : 0u;\n return s;\n}\n" note mo: the output names; tb: the binding texts, fragments separated by ~ (byte 126): 0-11 h, note 12-21 python, 22-34 rust, 35-46 zig, 47-64 go (its C preamble includes the generated header). -text mo "chpythonrustziggoapihapicfreest" +text mo "chpythonrustziggoapihapicfreestfapic" text tb "/* Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n * C and C++ declarations for libomega_native. Regenerate it; do not edit it.\n * Status: 0 done; 1..14 the Omega trap code; 32 argument refused (null, wrong length, misaligned,\n * overlap); 33 reentry; 34 bad runtime entry; 35 no stack. The result is written only on status 0.\n * A long is its two's-complement bits; an array is its address then its element count.\n * Parameter names carry o_ so no language's reserved words collide. */\n#ifndef OMEGA_NATIVE_H\n#define OMEGA_NATIVE_H\n#include \n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#define OMEGA_OK 0u\n#define OMEGA_BAD_ARG 32u\n#define OMEGA_REENTRY 33u\n#define OMEGA_BAD_RT 34u\n#define OMEGA_NO_STACK 35u\n~/* ~ */\nuint32_t omega_~(uint64_t *result~, uint64_t o_~, void *o_~, const void *o_~, void *o_~, const void *o_~_len~);\n~#ifdef __cplusplus\n}\n#endif\n#endif\n~# Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n# ctypes declarations for libomega_native.so beside this file. Regenerate it; do not edit it.\n# Status: 0 done; 1..14 the Omega trap code; 32 argument refused (None, wrong length, misaligned,\n# overlap); 33 reentry; 34 bad runtime entry; 35 no stack. The result (a ctypes.c_uint64 passed with\n# ctypes.byref) is written only on status 0. A scalar is an int in 0 .. 2**64-1 (a long is passed as its\n# two's-complement bits); anything else raises ctypes.ArgumentError, nothing is truncated. An array is a\n# ctypes array of its element type (bytes for a view uchar, c_float for f32, c_uint16 for ushort) then its element count; an edit array must\n# be writable, so bytes are refused there.\nimport ctypes, os\nOMEGA_OK, OMEGA_BAD_ARG, OMEGA_REENTRY, OMEGA_BAD_RT, OMEGA_NO_STACK = 0, 32, 33, 34, 35\nlib = ctypes.CDLL(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"libomega_native.so\"))\nclass _u64:\n @classmethod\n def from_param(cls, v):\n if type(v) is not int or v < 0 or v > 18446744073709551615:\n raise ValueError(\"omega scalar: an int in 0 .. 2**64-1 expected, got %r\" % (v,))\n return ctypes.c_uint64(v)\n_res = ctypes.POINTER(ctypes.c_uint64)\n_a3 = ctypes.POINTER(ctypes.c_uint64) # edit ulong: a writable ctypes array of c_uint64\n_a4 = ctypes.POINTER(ctypes.c_uint64) # view ulong: a ctypes array of c_uint64\n_a5 = ctypes.POINTER(ctypes.c_ubyte) # edit uchar: a writable ctypes array of c_ubyte\n_a6 = ctypes.c_char_p # view uchar: bytes, or a ctypes array of c_char\n_a7 = ctypes.POINTER(ctypes.c_float) # edit f32: a writable ctypes array of c_float\n_a8 = ctypes.POINTER(ctypes.c_float) # view f32: a ctypes array of c_float\n_a9 = ctypes.POINTER(ctypes.c_uint16) # edit ushort: a writable ctypes array of c_uint16\n_a10 = ctypes.POINTER(ctypes.c_uint16) # view ushort: a ctypes array of c_uint16\n~# ~\nomega_~ = lib.omega_~\nomega_~.argtypes = [_res~, _u64~, _a~]\nomega_~.restype = ctypes.c_uint32\n~// Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n// Declarations for libomega_native (build with -L ; Rust 1.82 or later). Regenerate it; do not edit it.\n// Status: 0 done; 1..14 the Omega trap code; 32 argument refused (null, wrong length, misaligned,\n// overlap); 33 reentry; 34 bad runtime entry; 35 no stack. The result is written only on status 0.\n// A long is its two's-complement bits (an i64 as u64); an array is its pointer then its element count.\n#[allow(dead_code)]\npub const OMEGA_OK: u32 = 0;\n#[allow(dead_code)]\npub const OMEGA_BAD_ARG: u32 = 32;\n#[allow(dead_code)]\npub const OMEGA_REENTRY: u32 = 33;\n#[allow(dead_code)]\npub const OMEGA_BAD_RT: u32 = 34;\n#[allow(dead_code)]\npub const OMEGA_NO_STACK: u32 = 35;\n#[allow(dead_code)]\n#[link(name = \"omega_native\")]\nunsafe extern \"C\" {\n~ // ~\n pub fn omega_~(result: *mut u64~, o_~: u64~: *mut u64~: *const u64~: *mut u8~: *const u8~_len: u64~) -> u32;\n~}\n~// Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n// Declarations for libomega_native (build with -L -lomega_native -lc). Regenerate it; do not edit it.\n// Status: 0 done; 1..14 the Omega trap code; 32 argument refused (null, wrong length, misaligned,\n// overlap); 33 reentry; 34 bad runtime entry; 35 no stack. The result is written only on status 0.\n// A long is its two's-complement bits (@bitCast); an array is its pointer then its element count.\npub const OMEGA_OK: u32 = 0;\npub const OMEGA_BAD_ARG: u32 = 32;\npub const OMEGA_REENTRY: u32 = 33;\npub const OMEGA_BAD_RT: u32 = 34;\npub const OMEGA_NO_STACK: u32 = 35;\n~// ~\npub extern fn omega_~(result: ?*u64~, o_~: u64~: ?[*]u64~: ?[*]const u64~: ?[*]u8~: ?[*]const u8~_len: u64~) u32;\n~// Generated by omega-bridge src/native.om: native call ABI v1 (docs/NATIVE-ABI.md).\n// cgo package omeganative: this file, omega_native.h and libomega_native.so in one folder. Regenerate it;\n// do not edit it. No run-time path is baked in: the program's build names the folder (CGO_LDFLAGS set to\n// -Wl,-rpath,), or LD_LIBRARY_PATH does.\n// Status: 0 done; 1..14 the Omega trap code; 32 argument refused (nil, wrong length, misaligned,\n// overlap); 33 reentry; 34 bad runtime entry; 35 no stack. The result is written only on status 0.\n// A long is its two's-complement bits (an int64 as uint64); an array is an unsafe.Pointer to memory\n// holding no Go pointers, then its element count.\npackage omeganative\n\n/*\n#cgo CFLAGS: -I${SRCDIR}\n#cgo LDFLAGS: -L${SRCDIR} -lomega_native\n#include \"omega_native.h\"\n*/\nimport \"C\"\n\nimport \"unsafe\"\n\nconst (\n\tOmegaOK uint32 = 0\n\tOmegaBadArg uint32 = 32\n\tOmegaReentry uint32 = 33\n\tOmegaBadRt uint32 = 34\n\tOmegaNoStack uint32 = 35\n)\n~\n// ~\nfunc Omega_~(result *uint64~, o_~ uint64~ unsafe.Pointer~ unsafe.Pointer~ unsafe.Pointer~ unsafe.Pointer~_len uint64~) uint32 {\n\treturn uint32(C.omega_~((*C.uint64_t)(unsafe.Pointer(result))~, C.uint64_t(o_~)~, o_~_len)~))\n}\n" -note Freestanding output accepts integer scalars only: no arrays, storage, host words or OM-2. +note Freestanding output (freest) accepts pure units only: no storage (global, text), host words, floats +note or input; an OM-1 unit integer scalars only (no arrays). fw lists the words a pure unit may use; the +note words after # are the OM-2 ones, allowed only in an OM-2 unit (fo2 1): views, layouts, out +note parameters, local arrays, part, unroll, inline and rotations. global fns ulong 1024 global fne ulong 1024 global fnc ulong 1 -text fw "|note|fn|to|ret|if|else|end|for|while|bound|break|continue|trap|requires|ensures|invariant|result|const|bool|uchar|ushort|uint|ulong|byte|short|int|long|true|false|add|sub|mul|div|rem|and|or|xor|shl|shr|neg|not|eq|ne|lt|le|gt|ge|bitcast|(|)|=|void|" +global fo2 ulong 1 +text fw "|note|fn|to|ret|if|else|end|for|while|bound|break|continue|trap|requires|ensures|invariant|result|const|bool|uchar|ushort|uint|ulong|byte|short|int|long|true|false|add|sub|mul|div|rem|and|or|xor|shl|shr|neg|not|eq|ne|lt|le|gt|ge|bitcast|(|)|=|void|#|om2|export|layout|field|out|at|little|big|edit|view|fresh|get|put|len|new|part|unroll|inline|rotr|rotl|*|" text fp "/* Generated pure integer-scalar freestanding native ABI v1 binding. */\n#include \n#define OMEGA_OK 0u\n#define OMEGA_BAD_ARG 32u\n#define OMEGA_BAD_RT 34u\ntypedef struct ombr_rt { const void *entry[32]; } ombr_rt;\nuint32_t ombr_enter(const void *code, const uint64_t *args, const ombr_rt *rt, uint64_t *out, void *top)\n __attribute__((visibility(\"hidden\")));\nextern const unsigned char ombr_trap[] __attribute__((visibility(\"hidden\")));\nextern const unsigned char ombr_no_entry[] __attribute__((visibility(\"hidden\")));\n/* ombr_enter saves the callee-saved registers on the caller's stack, keeps that stack pointer in x19 and\n * runs the pure scalar code on the caller's stack. A normal return stores x0 through out and\n * returns 0. A runtime entry restores the stack pointer from x19 and returns a status; out is not\n * written. The seeded compiler never writes x19..x28. Runtime entries are reached by blr/br, so they\n * start with bti jc. */\n__asm__(\".text\\n.balign 4\\n.local ombr_enter\\n.hidden ombr_enter\\n.type ombr_enter,%function\\nombr_enter:\\n\"\n \"hint #34\\nstp x29,x30,[sp,#-176]!\\nmov x29,sp\\nstp x19,x20,[sp,#16]\\nstp x21,x22,[sp,#32]\\n\"\n \"stp x23,x24,[sp,#48]\\nstp x25,x26,[sp,#64]\\nstp x27,x28,[sp,#80]\\nstp d8,d9,[sp,#96]\\n\"\n \"stp d10,d11,[sp,#112]\\nstp d12,d13,[sp,#128]\\nstp d14,d15,[sp,#144]\\nstr x3,[sp,#160]\\n\"\n \"mov x19,sp\\nmov x16,x0\\nmov x17,x1\\nmov x7,x2\\n\"\n \"ldp x0,x1,[x17]\\nldp x2,x3,[x17,#16]\\nldp x4,x5,[x17,#32]\\nblr x16\\n\"\n \"mov sp,x19\\nldr x9,[sp,#160]\\nstr x0,[x9]\\nmov w0,#0\\n\"\n \"ombr_leave:\\nldp d14,d15,[sp,#144]\\nldp d12,d13,[sp,#128]\\nldp d10,d11,[sp,#112]\\n\"\n \"ldp d8,d9,[sp,#96]\\nldp x27,x28,[sp,#80]\\nldp x25,x26,[sp,#64]\\nldp x23,x24,[sp,#48]\\n\"\n \"ldp x21,x22,[sp,#32]\\nldp x19,x20,[sp,#16]\\nldp x29,x30,[sp],#176\\nret\\n.size ombr_enter,.-ombr_enter\\n\"\n \".local ombr_trap\\n.hidden ombr_trap\\n.type ombr_trap,%function\\nombr_trap:\\nhint #38\\n\"\n \"mov sp,x19\\nsub x2,x1,#1\\nmov w3,#34\\ncmp x2,#13\\ncsel w0,w1,w3,ls\\nb ombr_leave\\n\"\n \".size ombr_trap,.-ombr_trap\\n\"\n \".local ombr_no_entry\\n.hidden ombr_no_entry\\n.type ombr_no_entry,%function\\nombr_no_entry:\\nhint #38\\n\"\n \"mov sp,x19\\nmov w0,#34\\nb ombr_leave\\n.size ombr_no_entry,.-ombr_no_entry\\n\");\nstatic const ombr_rt ombr_rt_table = {{ ombr_no_entry, ombr_no_entry, ombr_trap, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry, ombr_no_entry }};\nstatic uint32_t ombr_run(const void *code, const uint64_t *args, uint64_t *result, int has_value)\n{\n uint64_t v = 0;\n uint32_t status = ombr_enter(code, args, &ombr_rt_table, &v, 0);\n if (status == OMEGA_OK)\n *result = has_value ? v : 0u;\n return status;\n}\n" text fb ")\n{\n uint64_t a[6] = {0};\n if (!result || (uintptr_t)result % 8u != 0u || (uintptr_t)result > UINTPTR_MAX - 8u)\n return OMEGA_BAD_ARG;\n~ return ombr_run(ombr_entry_" fn fword k ulong to ulong i = ulong 0 while lt add i 1 len fw if eq get fw i 124 +if and eq get fw add i 1 35 eq get fo2 0 0 +ret 0 +end j = add i 1 while and lt j len fw ne get fw j 124 j = add j 1 @@ -103,6 +110,18 @@ ret 0 end if eq get inb s 45 s = add s 1 +else +if and eq get fo2 0 1 gt sub e s 2 +if and eq get inb s 48 eq get inb add s 1 120 +for j ulong sub e add s 2 +b = get inb add add s 2 j +if and or lt b 48 gt b 57 or lt b 97 gt b 102 +ret 0 +end +end +ret 1 +end +end end if eq s e ret 0 @@ -130,6 +149,25 @@ end end ret 0 end +note fdecl2: pass 0 of fcheck on a line of an OM-2 unit: on a `fn` or `export fn` line every token that is +note not a word or a number is a declared name (the function, its parameters); a `layout` or `field` line +note declares its second token. fw offsets: export 254, layout 261, field 268. +fn fdecl2 nt ulong to void +b = ulong 0 +if eq fis 0 254 6 1 +b = 1 +end +if and gt nt b eq fis b 6 2 1 +for k ulong nt +if and gt k b eq fknown k 0 +fadd k +end +end +end +if and ge nt 2 or eq fis 0 261 6 1 eq fis 0 268 5 1 +fadd 1 +end +end fn fcheck p ulong q ulong to void put fnc 0 0 for pass ulong 2 @@ -140,6 +178,9 @@ next = add get st 7 1 if gt nt 0 if eq fis 0 1 4 0 if eq pass 0 +if eq get fo2 0 1 +fdecl2 nt +else if eq fis 0 6 2 1 if lt nt 4 trap 10 @@ -154,6 +195,7 @@ fadd k k = add k 2 end end +end if ge nt 2 if or eq fis 0 28 3 1 eq fis 0 98 5 1 fadd 1 @@ -447,6 +489,9 @@ end if eq mdis 25 6 1 m = 10 end +if eq mdis 31 5 1 +m = 11 +end if eq m 0 trap 10 end @@ -1125,6 +1170,23 @@ end end end end +note fq: the freestanding v2 fragments (outputs freest and fapic), separated by ~: 0 the runtime, 1-2 the +note out buffer in an entry's frame, 3-4 the end of an entry, 5 the trap of a refused call, 6 the fapic +note file's start. +text fq "/* ABI v2, freestanding (docs/NATIVE-ABI.md, ABI v2, output freest): OM-2 units on the caller's stack. The\n * argument checks are those of output c. Each out parameter is written to a buffer in the calling\n * function's frame (16-byte aligned, zero-filled) and copied to the caller only after status 0. No\n * thread-local state, heap or stack mapping; the only C library calls are memset and memmove. */\ntypedef struct ombr_span { uintptr_t lo, hi; int w; } ombr_span;\ntypedef struct ombr2_out { unsigned slot; uint64_t n; void *dst; } ombr2_out;\n/* A binding of OM-2 units alone does not call the ABI v1 helper. */\n__attribute__((unused)) static void ombr2_keep(void)\n{\n (void)ombr_run;\n}\nstatic int ombr_span_add(ombr_span *sp, unsigned *ns, const void *p, uint64_t n, uint64_t want, uint64_t es, int w)\n{\n uintptr_t lo = (uintptr_t)p;\n if (!p || n != want || lo % es != 0u || n > (UINTPTR_MAX - lo) / es)\n return 1;\n sp[*ns].lo = lo;\n sp[*ns].hi = lo + n * es;\n sp[*ns].w = w;\n (*ns)++;\n return 0;\n}\n/* An unsized view of n elements of es bytes, as in output c. */\n__attribute__((unused)) static int ombr2_view(ombr_span *sp, unsigned *ns, const void *p, uint64_t n, uint64_t es, int w)\n{\n uintptr_t lo = (uintptr_t)p;\n if (n == 0u)\n return 0;\n if (!p || lo % es != 0u || n > UINT64_MAX / es || n * es > UINTPTR_MAX - lo)\n return 1;\n sp[*ns].lo = lo;\n sp[*ns].hi = lo + n * es;\n sp[*ns].w = w;\n (*ns)++;\n return 0;\n}\n/* A fixed range of nb > 0 bytes (a layout or an out parameter) aligned to es. */\n__attribute__((unused)) static int ombr2_fixed(ombr_span *sp, unsigned *ns, const void *p, uint64_t nb, uint64_t es,\n int w)\n{\n uintptr_t lo = (uintptr_t)p;\n if (!p || lo % es != 0u || nb > UINTPTR_MAX - lo)\n return 1;\n sp[*ns].lo = lo;\n sp[*ns].hi = lo + nb;\n sp[*ns].w = w;\n (*ns)++;\n return 0;\n}\n/* w: 0 view, 1 edit or the result, 2 out; refused overlaps as in output c. */\nstatic int ombr2_overlap(const ombr_span *sp, unsigned ns)\n{\n for (unsigned i = 0; i < ns; i++)\n for (unsigned j = i + 1; j < ns; j++)\n if ((sp[i].w == 1 || sp[j].w == 1 || (sp[i].w == 2 && sp[j].w == 2))\n && sp[i].lo < sp[j].hi && sp[j].lo < sp[i].hi)\n return 1;\n return 0;\n}\n/* As ombr_run; each out buffer is carved from ob (the entry's frame, 16-byte aligned, each buffer rounded\n * up to 16 bytes), zero-filled, passed in its slot and copied to the caller only after status 0. */\nstatic uint32_t ombr2_run(const void *code, uint64_t *args, uint64_t *result, int has_value, const ombr2_out *o,\n unsigned no, unsigned char *ob)\n{\n unsigned char *buf[6] = {0};\n for (unsigned i = 0; i < no; i++) {\n __builtin_memset(ob, 0, o[i].n);\n buf[i] = ob;\n args[o[i].slot] = (uint64_t)(uintptr_t)ob;\n ob += (o[i].n + 15u) / 16u * 16u;\n }\n uint64_t v = 0;\n uint32_t s = ombr_enter(code, args, &ombr_rt_table, &v, 0);\n if (s == OMEGA_OK) {\n for (unsigned i = 0; i < no; i++)\n __builtin_memmove(o[i].dst, buf[i], o[i].n);\n *result = has_value ? v : 0u;\n }\n return s;\n}\n~ _Alignas(16) unsigned char ob[~];\n~, ou, no, ob);\n}\n~, ou, no, 0);\n}\n~) != OMEGA_OK)\n __builtin_trap();\n~/* Generated by omega-bridge src/native.om: the freestanding definitions of the C API declared in\n * omega_api_decl.h (output fapic), for the freestanding binding (output freest). Each calls\n * omega2_ and executes a trap instruction (__builtin_trap) on a nonzero status; it calls no C\n * library function. Regenerate it; do not edit it. */\n#include \"omega_api_decl.h\"\n" +fn ofq k ulong to void +c = ulong 0 +for i ulong len fq +b = get fq i +if eq b 126 +c = add c 1 +else +if eq c k +ob b +end +end +end +end note ofv / otn: fragment k of fv / tn. fn ofv k ulong to void if and eq get xt 0 1 eq k 17 @@ -1893,6 +1955,30 @@ ofv 9 oun ofv 10 end +note cfsend: the end of an entry in output freest: its out buffers in the entry's own frame (each rounded up +note to 16 bytes, as ombr2_run carves them), then the call of ombr2_run with that buffer. +fn cfsend to void +nb = ulong 0 +for j ulong get st 2 +if eq get qk j 5 +nb = add nb mul div add mul get qn j tsize get qt j 15 16 16 +end +end +if gt nb 0 +ofq 1 +odec nb +ofq 2 +end +ofv 48 +oen +ofv 49 +odec get s2 8 +if gt nb 0 +ofq 3 +else +ofq 4 +end +end note cone: one entry in C: its stub (bti c, a branch to word k of the code) and its function. fn cone to void ofv 14 @@ -1920,12 +2006,16 @@ ofv 23 cpar ofv 24 cbody +if eq get st 5 10 +cfsend +else ofv 48 oen ofv 49 odec get s2 8 ofv 50 end +end fn hone to void ofv 21 osig @@ -2438,7 +2528,11 @@ ofv 32 opn j end end +if eq get st 5 11 +ofq 5 +else ofv 143 +end if eq get s2 8 0 ofv 144 else @@ -2452,7 +2546,7 @@ end note eone2: the bound entry just parsed, in the output st 5. fn eone2 to void m = get st 5 -if eq m 1 +if or eq m 1 eq m 10 cone end if eq m 2 @@ -2470,7 +2564,7 @@ end if eq m 6 goone end -if ge m 7 +if and ge m 7 ne m 10 apone end end @@ -2494,9 +2588,13 @@ if gt mul nex stride cl trap 10 end m = get st 5 -if eq m 1 +if or eq m 1 eq m 10 if eq get s2 0 0 +if eq m 10 +ofq 0 +else ofv 0 +end put s2 0 1 end ecode2 @@ -2539,6 +2637,7 @@ note unit: accept the unit at p, emit it, return where the next unit starts. fn unit p ulong to ulong q = sepat p if eq get st 5 10 +put fo2 0 prof p q fcheck p q end if eq prof p q 1 @@ -2607,6 +2706,9 @@ end if eq m 9 ofa 3 end +if eq m 11 +ofq 6 +end end p = ulong 0 nu = ulong 0 diff --git a/tests/native/test_freestanding.py b/tests/native/test_freestanding.py index cbdf35f..2fca567 100755 --- a/tests/native/test_freestanding.py +++ b/tests/native/test_freestanding.py @@ -79,13 +79,15 @@ def main(): 'host': 'fn epoch n ulong to ulong\nr = getpid\nret n\nend\n', 'exit': 'fn epoch n ulong to ulong\nexit 0\nret n\nend\n', 'hidden-host-helper': 'fn hidden to ulong\nret monons\nend\nfn epoch n ulong to ulong\nret n\nend\n', - 'om2': 'om2\nfn epoch n ulong to ulong\nret n\nend\n', + # OM-2 itself is accepted (tests/native/test_freestanding_om2.py); a frame without the + # omega-unit trailer is not. + 'om2-no-trailer': 'om2\nfn epoch n ulong to ulong\nret n\nend\n', } for name, source in refusals.items(): frame = source.encode() + b'\0' + f'{len(code):08d}'.encode() + code p = subprocess.run([gen, 'freest'], input=frame, capture_output=True) assert p.returncode == 110 and not p.stdout, (name, p.returncode, p.stdout) - print('PASS freestanding refuses arrays, storage, text, host effects including unused helper and OM-2 before any output') + print('PASS freestanding refuses arrays, storage, text, host effects including unused helper and an OM-2 frame without its trailer before any output') # Mutate the .om emitter, not a production C implementation. The normal tools/native gate # must refuse an actual pthread import and leave an already installed library untouched. mutant = t / 'mutant' diff --git a/tests/native/test_freestanding_om2.py b/tests/native/test_freestanding_om2.py new file mode 100755 index 0000000..d10a894 --- /dev/null +++ b/tests/native/test_freestanding_om2.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""OM-2 freestanding binding: FIPS 180-4 digests of sha256-om2.om through outputs freest + fapic, +the out-buffer rules, and a mutant runtime that drops the copy-back.""" +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +ALLOWED = {'_GLOBAL_OFFSET_TABLE_', 'memcpy', 'memmove', 'memset', 'memcmp', 'strlen', 'strcmp'} +# FIPS 180-2/180-4 examples: empty, "abc", the 448-bit message, and 1,000,000 'a'. +WANT = { + 'empty': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', + 'abc': 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', + '448': '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1', + 'million': 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0', +} +# What the caller prints with the copy-back dropped: its 0xa5 pre-call fill, unchanged. +MUTANT = {name: 'a5' * 32 for name in WANT} + + +def run(args, **kw): + p = subprocess.run([str(a) for a in args], capture_output=True, **kw) + if p.returncode: + raise AssertionError(f'{args}: exit {p.returncode}\n{p.stdout!r}\n{p.stderr!r}') + return p.stdout + + +def drop_copyback(source): + """src/native.om text with the freestanding OM-2 runtime's out-buffer copy-back removed.""" + lines = source.splitlines() + for i, line in enumerate(lines): + if line.startswith('text fq '): + parts = json.loads(line[len('text fq '):]).split('~') + assert parts[0].count('__builtin_memmove') == 1 + parts[0] = parts[0].replace('__builtin_memmove(o[i].dst, buf[i], o[i].n);', '(void)buf[i];') + lines[i] = 'text fq ' + json.dumps('~'.join(parts)) + return '\n'.join(lines) + '\n' + raise AssertionError('freestanding OM-2 runtime template missing') + + +def main(): + with tempfile.TemporaryDirectory(prefix='bridge-freestanding-om2-') as td: + t = Path(td) + out = t / 'lib' + run([ROOT / 'tools/native', '--freestanding', out, + ROOT / 'tests/native/v2/sha256-om2.om', ROOT / 'tests/native/v2/fsout.om']) + assert not (out / 'libomega_native.so').exists() + defined = set() + imports = {} + for obj in ('omega_native.o', 'omega_api_defs.o'): + imports[obj] = {line.split()[-1] + for line in run(['nm', '-u', out / obj]).decode().splitlines() if line.split()} + defined |= {line.split()[-1] + for line in run(['nm', '--defined-only', '-g', out / obj]).decode().splitlines() + if line.split()} + sections = run(['readelf', '-SW', out / obj]).decode() + assert '.tbss' not in sections and '.tdata' not in sections + for obj, names in imports.items(): + assert not names - ALLOWED - defined, (obj, names - ALLOWED - defined) + assert not (out / 'omega_api.h').exists() + # The freestanding object compiled as the consumer would, with the required flags. + run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-Wmissing-prototypes', + '-ffreestanding', '-fno-builtin', '-fno-stack-protector', + '-include', out / 'omega_native.h', '-c', out / 'omega_native.c', '-o', t / 'again.o']) + caller = t / 'fsom2' + run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', '-I', out, + ROOT / 'tests/native/v2/fsom2.c', out / 'omega_native.o', out / 'omega_api_defs.o', + '-o', caller]) + lines = run([caller]).decode().splitlines() + got = dict(line.split() for line in lines if line.split()[0] in WANT) + assert got == WANT, got + assert 'badarg 32 1' in lines and 'outok 0 2 7 1' in lines and 'outtrap 5 1' in lines + assert 'threads 1' in lines + print('PASS OM-2 freestanding: FIPS 180-4 digests, bad-arg and trap leave out untouched, four threads') + # A trap instruction: 133 when the shell reports it, -5 (SIGTRAP) when Python does. + p = subprocess.run([caller, 'trap'], capture_output=True) + assert p.returncode in (133, -5) and not p.stdout, (p.returncode, p.stdout) + print('PASS fapic wrapper traps on a nonzero status (exit 133)') + + # Negative control: drop the copy-back from the runtime. The digest checks must then fail, + # because the caller's buffer keeps its pre-call fill. + mutant = t / 'mutant' + (mutant / 'tools').mkdir(parents=True) + (mutant / 'src').mkdir() + shutil.copy2(ROOT / 'tools/native', mutant / 'tools/native') + (mutant / 'src/native.om').write_text(drop_copyback((ROOT / 'src/native.om').read_text())) + mout = t / 'mutlib' + run([mutant / 'tools/native', '--freestanding', mout, + ROOT / 'tests/native/v2/sha256-om2.om', ROOT / 'tests/native/v2/fsout.om']) + mcaller = t / 'mfsom2' + run(['cc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', '-pthread', '-I', mout, + ROOT / 'tests/native/v2/fsom2.c', mout / 'omega_native.o', mout / 'omega_api_defs.o', + '-o', mcaller]) + mp = subprocess.run([mcaller], capture_output=True) + mlines = mp.stdout.decode().splitlines() + mgot = dict(line.split() for line in mlines if line.split() and line.split()[0] in WANT) + # Every digest is the untouched pre-call fill: a crash or partial run is not a detection. + assert mp.returncode == 0 and mgot == MUTANT, (mp.returncode, mgot) + print('PASS mutant runtime (copy-back dropped) leaves the pre-call fill in every digest') + + +if __name__ == '__main__': + main() diff --git a/tests/native/v2/fsom2.c b/tests/native/v2/fsom2.c new file mode 100644 index 0000000..13bc74c --- /dev/null +++ b/tests/native/v2/fsom2.c @@ -0,0 +1,96 @@ +/* A hosted caller of the freestanding ABI v2 binding (outputs freest + fapic) of sha256-om2.om and + * fsout.om; tests/native/test_freestanding_om2.py builds it and checks what it prints. `fsom2` prints + * one line per check; `fsom2 trap` calls a C API wrapper on a trapping input and must not return. */ +#include "omega_api_decl.h" +#include +#include +#include +#include + +/* Four threads hash "abc" concurrently, each on its own stack (no shared runtime state). */ +static void *spin(void *arg) +{ + static const uint8_t want[4] = {0xba, 0x78, 0x16, 0xbf}; + uint8_t o[32]; + (void)arg; + for (int i = 0; i < 2000; i++) { + memset(o, 0, sizeof o); + sha256_hash((const uint8_t *)"abc", 3, o); + if (memcmp(o, want, 4) != 0) + return (void *)1; + } + return 0; +} + +static void hex(const char *name, const uint8_t *d) +{ + printf("%s ", name); + for (int i = 0; i < 32; i++) + printf("%02x", d[i]); + printf("\n"); +} + +static void once(const char *name, const char *m) +{ + uint8_t o[32]; + memset(o, 0xa5, sizeof o); + sha256_hash((const uint8_t *)m, strlen(m), o); + hex(name, o); +} + +static uint8_t million[1000000]; + +int main(int argc, char **argv) +{ + if (argc > 1 && strcmp(argv[1], "trap") == 0) { + uint8_t o[16]; + fsout(0, o); + printf("RETURNED\n"); + return 0; + } + once("empty", ""); + once("abc", "abc"); + once("448", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); + sha256_ctx c; + uint8_t o[32]; + memset(million, 'a', sizeof million); + memset(o, 0xa5, sizeof o); + sha256_init(&c); + sha256_update(&c, million, 123); + sha256_update(&c, million + 123, sizeof million - 123); + sha256_final(&c, o); + hex("million", o); + /* A refused argument (a null view of 5 bytes): status 32, the out buffer untouched. */ + uint64_t r = 99; + memset(o, 0xa5, sizeof o); + uint32_t s = omega2_sha256_hash(&r, NULL, 5, o); + int same = 1; + for (int i = 0; i < 32; i++) + same &= o[i] == 0xa5; + printf("badarg %u %d\n", s, same); + /* Success: the whole out buffer comes back (written byte 7, the rest zero-filled). */ + uint8_t b[16]; + memset(b, 0xaa, sizeof b); + s = omega2_fsout(&r, 1, b); + int zero = 1; + for (int i = 1; i < 16; i++) + zero &= b[i] == 0; + printf("outok %u %llu %u %d\n", s, (unsigned long long)r, b[0], zero); + /* A trap after the out write: nonzero status, the caller's buffer as it was. */ + memset(b, 0xaa, sizeof b); + s = omega2_fsout(&r, 0, b); + same = 1; + for (int i = 0; i < 16; i++) + same &= b[i] == 0xaa; + printf("outtrap %u %d\n", s, same); + pthread_t t[4]; + int bad = 0; + for (int i = 0; i < 4; i++) + bad |= pthread_create(&t[i], 0, spin, 0) != 0; + for (int i = 0; i < 4; i++) { + void *v = (void *)1; + bad |= pthread_join(t[i], &v) != 0 || v != 0; + } + printf("threads %d\n", !bad); + return 0; +} diff --git a/tests/native/v2/fsout.om b/tests/native/v2/fsout.om new file mode 100644 index 0000000..9e5977a --- /dev/null +++ b/tests/native/v2/fsout.om @@ -0,0 +1,10 @@ +note fsout.om: an out parameter written before a trap. Freestanding ABI v2 copies the out buffer back +note only on status 0, so after the trap the caller's buffer must hold what it held before the call. +om2 +export fn fsout x ulong o out uchar 16 to ulong +put o 0 7 +if eq x 0 +trap 5 +end +ret add x 1 +end diff --git a/tests/native/v2/run.sh b/tests/native/v2/run.sh index db27b9c..644d201 100755 --- a/tests/native/v2/run.sh +++ b/tests/native/v2/run.sh @@ -28,17 +28,18 @@ W=$O/work; GEN=$W/native-gen # basegen REV NAME: the historical generator, with the current C runtime prelude and only # private assembly-linkage directives normalized. Public wrappers, signatures, compiler bytes -# and declarations remain byte-compared. REVs are reachable on this branch: 5458684 has the blob -# of pre-rebase 3f05908, 3d79d77 that of 3bb8b8a. +# and declarations remain byte-compared. The REV is reachable on main: f637021 is #26 (f32 and +# ushort kinds), the last intended change of the existing outputs. #26 changed the python output of +# every unit and admitted fsum and halve, so the earlier baselines (5458684, 3d79d77) no longer apply. basegen() { PRE=$(grep '^text pre ' "$ROOT/src/native.om"); export PRE git -C "$ROOT" show "$1:src/native.om" | awk '/^text pre /{print ENVIRON["PRE"]; next} /^text fr |^text fv /{gsub(/[.]globl ombr_code_/, ".local ombr_code_"); gsub(/[.]globl ombr_entry_/, ".local ombr_entry_"); gsub(/[.]globl ombr2_code_/, ".local ombr2_code_"); gsub(/[.]globl ombr2_entry_/, ".local ombr2_entry_")} {print}' > "$O/native-$2.om" "$OMC" < "$O/native-$2.om" > "$O/gen-$2"; chmod +x "$O/gen-$2" } -# 1. ABI v1 output unchanged: the generator of 5458684 (plus #17's prelude) and this one, on every +# 1. ABI v1 output unchanged: the generator of f637021 (plus the current prelude) and this one, on every # existing unit alone and on the v1 suite's set, for all six outputs. -basegen 5458684 v1 +basegen f637021 v1 same=0; diff=0; : > "$O/v1set.in" for u in "$ROOT"/tests/native/*.om "$ROOT"/tests/native/g1/*.om; do "$OMC" < "$u" > "$O/one.bin" 2> /dev/null || continue @@ -54,7 +55,7 @@ for w in c h python rust zig go; do "$O/gen-v1" $w < "$O/v1set.in" > "$O/a.out"; "$GEN" $w < "$O/v1set.in" > "$O/b.out" if cmp -s "$O/a.out" "$O/b.out"; then same=$((same + 1)); else diff=$((diff + 1)); echo "DIFF set $w"; fi done -if [ $diff = 0 ]; then pass "ABI v1 bindings byte-identical to 5458684's generator (runtime/private linkage normalized): $same unit x output cases (every tests/native and g1 unit, and the set)" +if [ $diff = 0 ]; then pass "ABI v1 bindings byte-identical to f637021's generator (runtime/private linkage normalized): $same unit x output cases (every tests/native and g1 unit, and the set)" else fail "ABI v1 bindings changed in $diff cases"; fi # 2. Identity: each v2 unit's embedded source digest equals sha256sum of its file (oracle), the omc digest @@ -269,16 +270,15 @@ mut overlap '/^text fv /s/if ((sp\[i\].w == 1 || sp\[j\].w == 1 ||/if ((/' 'vcop mut outcopy '/^text fv /s/memmove(o\[i\].dst, buf\[i\], o\[i\].n);/;/' 'digest: tag' # 10a. The C API out of line (outputs apih, apic) for freestanding consumers. The inline header -# (output api) stays byte for byte what 3d79d77's generator (with #17's prelude) wrote, as does every -# other output. -basegen 3d79d77 3bb +# (output api) and the out-of-line pair stay byte for byte what f637021's generator (with the current +# prelude) wrote, as does every other output. ok=1 -for w in c h python rust zig go api; do - "$O/gen-3bb" $w < "$W/units.in" > "$O/a.out"; "$GEN" $w < "$W/units.in" > "$O/b.out" +for w in c h python rust zig go api apih apic; do + "$O/gen-v1" $w < "$W/units.in" > "$O/a.out"; "$GEN" $w < "$W/units.in" > "$O/b.out" cmp -s "$O/a.out" "$O/b.out" || { ok=0; echo "DIFF $w"; } done -if [ $ok = 1 ]; then pass "outputs c h python rust zig go api byte-identical to 3d79d77's generator (runtime/private linkage normalized) on the v2 set" -else fail "an existing output changed against 3d79d77"; fi +if [ $ok = 1 ]; then pass "outputs c h python rust zig go api apih apic byte-identical to f637021's generator (runtime/private linkage normalized) on the v2 set" +else fail "an existing output changed against f637021"; fi FS=$O/fs; mkdir -p "$FS" FSCF="-std=gnu11 -ffreestanding -fno-builtin -O2 -Wall -Wextra -Werror -c" # fsobj DIR: the freestanding object from DIR's omega_api_decl.h; prints its undefined symbols. @@ -324,6 +324,11 @@ if amut api '/^if eq get st 5 7$/s/7$/97/'; then else fail "mutant api changed something else"; fi fi +# 10b. Freestanding OM-2 (tools/native --freestanding, outputs freest + fapic): FIPS 180-4 digests, +# out-buffer rules, threads, the trap wrapper and the copy-back-dropped mutant. +if python3 "$T/../test_freestanding_om2.py" > "$O/fsom2.log" 2>&1; then pass "freestanding OM-2: $(grep -c '^PASS' "$O/fsom2.log") checks incl. copy-back mutant" +else fail "freestanding OM-2"; cat "$O/fsom2.log"; fi + # 10. Cost (HOST): call overhead, stack switch, copies, small and large views. if [ "${1:-}" = measure ]; then cc -std=gnu11 -O2 -Wall -Wextra -Werror -pthread -I "$O" "$T/measure.c" -L"$O" -lomega_native -Wl,-rpath,"$O" -o "$O/measure" \ diff --git a/tests/native/v2/sha256-om2.om b/tests/native/v2/sha256-om2.om new file mode 100644 index 0000000..748c871 --- /dev/null +++ b/tests/native/v2/sha256-om2.om @@ -0,0 +1,344 @@ +note SPDX-License-Identifier: Apache-2.0 +note sha256-om2.om: FIPS 180-4 SHA-256 in OM-2 (spec/omegese-om2.md, #747/#748, ledger L838). +note The four entries are the API of src/sha256.h, exported through omega-bridge ABI v2 as +note omega2_sha256_init/update/final/hash; the bridge's generated omega_api.h maps the C names. +note +note Invariants: +note - All hashing state is the caller's 104-byte context (layout shactx below, equal to sha256_ctx +note on LP64 AArch64). Nothing else persists between calls, so a byte copy of a live context is an +note equivalent context (erratum E3). +note - count is the number of bytes absorbed since init, modulo 2^64. buf[0 .. count mod 64) holds the +note pending bytes of the current block; the rest of buf is unspecified. state is the chaining value +note after the count div 64 whole blocks. +note - final reads the context and writes only the digest, so the context is unchanged by it. The +note contract promises less (after final the context is unspecified, memory safety only). +note - Every branch and every loop count depends only on lengths, never on message bytes (section 8). +note - Indices into the unsized input view are checked at run time (trap 3); indices into sized +note arrays inside unrolled bodies are constants and checked when compiled. +note bridge c-type shactx sha256_ctx +note bridge c-define SHA256_DIGEST_SIZE 32 +note bridge c-define SHA256_BLOCK_SIZE 64 +om2 + +layout shactx 104 +field state uint 8 at 0 little +field count ulong at 32 little +field buf uchar 64 at 40 little +end + +note K[0..63]: the first 32 bits of the fractional parts of the cube roots of the first 64 primes. +note Copied mechanically from seed/qualification/om2/fixtures/sha256-k.dec (tool-computed, never typed). +fn kinit k edit uint 64 to void +put k 0 0x428a2f98 +put k 1 0x71374491 +put k 2 0xb5c0fbcf +put k 3 0xe9b5dba5 +put k 4 0x3956c25b +put k 5 0x59f111f1 +put k 6 0x923f82a4 +put k 7 0xab1c5ed5 +put k 8 0xd807aa98 +put k 9 0x12835b01 +put k 10 0x243185be +put k 11 0x550c7dc3 +put k 12 0x72be5d74 +put k 13 0x80deb1fe +put k 14 0x9bdc06a7 +put k 15 0xc19bf174 +put k 16 0xe49b69c1 +put k 17 0xefbe4786 +put k 18 0x0fc19dc6 +put k 19 0x240ca1cc +put k 20 0x2de92c6f +put k 21 0x4a7484aa +put k 22 0x5cb0a9dc +put k 23 0x76f988da +put k 24 0x983e5152 +put k 25 0xa831c66d +put k 26 0xb00327c8 +put k 27 0xbf597fc7 +put k 28 0xc6e00bf3 +put k 29 0xd5a79147 +put k 30 0x06ca6351 +put k 31 0x14292967 +put k 32 0x27b70a85 +put k 33 0x2e1b2138 +put k 34 0x4d2c6dfc +put k 35 0x53380d13 +put k 36 0x650a7354 +put k 37 0x766a0abb +put k 38 0x81c2c92e +put k 39 0x92722c85 +put k 40 0xa2bfe8a1 +put k 41 0xa81a664b +put k 42 0xc24b8b70 +put k 43 0xc76c51a3 +put k 44 0xd192e819 +put k 45 0xd6990624 +put k 46 0xf40e3585 +put k 47 0x106aa070 +put k 48 0x19a4c116 +put k 49 0x1e376c08 +put k 50 0x2748774c +put k 51 0x34b0bcb5 +put k 52 0x391c0cb3 +put k 53 0x4ed8aa4a +put k 54 0x5b9cca4f +put k 55 0x682e6ff3 +put k 56 0x748f82ee +put k 57 0x78a5636f +put k 58 0x84c87814 +put k 59 0x8cc70208 +put k 60 0x90befffa +put k 61 0xa4506ceb +put k 62 0xbef9a3f7 +put k 63 0xc67178f2 +end + +note H(0): the first 32 bits of the fractional parts of the square roots of the first 8 primes +note (fixtures/sha256-iv.dec). +fn iv s edit uint 8 to void +put s 0 0x6a09e667 +put s 1 0xbb67ae85 +put s 2 0x3c6ef372 +put s 3 0xa54ff53a +put s 4 0x510e527f +put s 5 0x9b05688c +put s 6 0x1f83d9ab +put s 7 0x5be0cd19 +end + +note Message schedule of the block m[o .. o+64). w is fresh: its incoming contents are never read. +note The compiler proves that every get of w reads an element written earlier in this function +note (error 27 otherwise): w[0..16) are the block's big-endian words, w[16..64) the FIPS recurrence. +fn sched w edit uint 64 fresh m view uchar * o ulong to void +q = ulong 0 +x = uint 0 +y = uint 0 +for i ulong 16 unroll +q = add o mul i 4 +x = uint get m q +x = or shl x 8 uint get m add q 1 +x = or shl x 8 uint get m add q 2 +put w i or shl x 8 uint get m add q 3 +end +for i ulong 48 unroll +x = get w add i 1 +y = get w add i 14 +x = add add get w i get w add i 9 xor xor rotr x 7 rotr x 18 shr x 3 +put w add i 16 add x xor xor rotr y 17 rotr y 19 shr y 10 +end +end + +note The 64 rounds on the chaining value s. One round body, emitted 64 times by unroll; i is a constant +note in each copy, so get kt i and get w i need no run-time check. uint arithmetic wraps mod 2^32. +note Ch(e,f,g) = (e and f) xor (not e and g) is written g xor (e and (f xor g)); Maj(a,b,c) = +note (a and b) xor (a and c) xor (b and c) is written (a and b) or (c and (a or b)). Both are bitwise +note identities. h first becomes T1, then T1 + T2, which is the next a; the names then shift by one. +note The sums are built a term per line and each Sigma in two lines through t: 12 names are live, and +note omc hands out 16 registers with no spilling (error 12 under compiler-s1/s2 for longer lines). +fn rounds s edit uint 8 w view uint 64 kt view uint 64 to void +a = get s 0 +b = get s 1 +c = get s 2 +d = get s 3 +e = get s 4 +f = get s 5 +g = get s 6 +h = get s 7 +t = uint 0 +for i ulong 64 unroll +h = add h get kt i +h = add h get w i +t = xor rotr e 6 rotr e 11 +t = xor t rotr e 25 +h = add h t +h = add h xor g and e xor f g +d = add d h +t = xor rotr a 2 rotr a 13 +t = xor t rotr a 22 +h = add h t +t = and c or a b +h = add h or and a b t +t = h +h = g +g = f +f = e +e = d +d = c +c = b +b = a +a = t +end +put s 0 add get s 0 a +put s 1 add get s 1 b +put s 2 add get s 2 c +put s 3 add get s 3 d +put s 4 add get s 4 e +put s 5 add get s 5 f +put s 6 add get s 6 g +put s 7 add get s 7 h +end + +note One block m[o .. o+64) into s. sched and rounds stay calls: inlined, their names would share +note one 16-register frame with this function's parameters (no spilling, error 12). +fn compress s edit uint 8 w edit uint 64 kt view uint 64 m view uchar * o ulong to void +sched w m o +rounds s w kt +end + +note The whole blocks of m (len m is a multiple of 64 and at most 2^25, so under 2^19 passes). +fn run s edit uint 8 w edit uint 64 kt view uint 64 m view uchar * to void +for j ulong shr len m 6 +compress s w kt m shl j 6 +end +end + +note The whole blocks of m (len m a multiple of 64). A rolled loop traps 4 after 1000000 passes +note (OMEGESE.md section 2; omc s_for), so m is cut into runs of 2^25 bytes (2^19 blocks): +note len m = top * 2^44 + mid * 2^25 + rest, and no loop passes 2^20 times. top reaches 1000000 +note only above 1.7e19 bytes, which no AArch64 address space holds. +fn blocks s edit uint 8 w edit uint 64 kt view uint 64 m view uchar * to void +q = ulong 0 +for a ulong shr len m 44 +for b ulong 0x80000 +run s w kt part m q 0x2000000 +q = add q 0x2000000 +end +end +for b ulong and shr len m 25 0x7ffff +run s w kt part m q 0x2000000 +q = add q 0x2000000 +end +run s w kt part m q sub len m q +end + +note Pad the k pending bytes already in p (k < 64; p was all zero past them): 0x80, zeros, and the +note 64-bit big-endian bit length of the n-byte message in the last 8 bytes of one or two blocks. +fn finish s edit uint 8 w edit uint 64 kt view uint 64 p edit uchar 128 k ulong n ulong to void +put p k 0x80 +e = ulong 64 +if ge k 56 +e = 128 +end +bits = shl n 3 +for i ulong 8 unroll +put p sub e add i 1 uchar and shr bits mul i 8 0xff +end +compress s w kt view p 0 +if eq e 128 +compress s w kt view p 64 +end +end + +export fn sha256_init c edit shactx to void +s = new uint 8 0 +iv s +for i ulong 8 unroll +put c state i get s i +end +put c count 0 +end + +note k bytes of d from o into the context's buffer at bi (bi + k <= 64). A function of its own: inside +note absorb the copy loop needs more than the 16 registers (error 12 under compiler-s4). +fn tobuf c edit shactx bi ulong d view uchar * o ulong k ulong to void +for i ulong k +put c buf add bi i get d add o i +end +end + +note Whole blocks are hashed straight from d; the bytes that complete a pending block go through blk. +fn absorb c edit shactx d view uchar * bi ulong to void +n = len d +s = new uint 8 0 +w = new uint 64 0 +kt = new uint 64 0 +blk = new uchar 64 0 +kinit kt +for i ulong 8 unroll +put s i get c state i +end +off = ulong 0 +if gt bi 0 +off = sub 64 bi +for i ulong bi +put blk i get c buf i +end +for i ulong off +put blk add bi i get d i +end +compress s w kt view blk 0 +end +nb = shr sub n off 6 +blocks s w kt part d off shl nb 6 +off = add off shl nb 6 +tobuf c 0 d off sub n off +for i ulong 8 unroll +put c state i get s i +end +end + +note Any length, including 0 and >= 2^32. lt n sub 64 bi cannot wrap (bi < 64); add bi n could. +export fn sha256_update c edit shactx d view uchar * to void +n = len d +cnt = get c count +bi = and cnt 63 +put c count add cnt n +if lt n sub 64 bi +tobuf c bi d 0 n +ret +end +absorb c d bi +end + +export fn sha256_final c edit shactx o out uchar 32 to void +s = new uint 8 0 +w = new uint 64 0 +kt = new uint 64 0 +p = new uchar 128 0 +v = ulong 0 +kinit kt +for i ulong 8 unroll +put s i get c state i +end +cnt = get c count +k = and cnt 63 +for i ulong k +put p i get c buf i +end +finish s w kt p k cnt +for i ulong 8 unroll +v = ulong get s i +for j ulong 4 unroll +put o add mul i 4 j uchar and shr v sub 24 mul j 8 0xff +end +end +end + +note Equal to init, update(d), final on a fresh context (section 7), with the state in locals. o may +note overlap d: the binding copies o out only after the call returns status 0. +export fn sha256_hash d view uchar * o out uchar 32 to void +s = new uint 8 0 +w = new uint 64 0 +kt = new uint 64 0 +p = new uchar 128 0 +v = ulong 0 +kinit kt +iv s +n = len d +nb = shr n 6 +blocks s w kt part d 0 shl nb 6 +off = shl nb 6 +k = sub n off +for i ulong k +put p i get d add off i +end +finish s w kt p k n +for i ulong 8 unroll +v = ulong get s i +for j ulong 4 unroll +put o add mul i 4 j uchar and shr v sub 24 mul j 8 0xff +end +end +end diff --git a/tests/native/x86/suite.py b/tests/native/x86/suite.py index 6fb6e2c..472d596 100755 --- a/tests/native/x86/suite.py +++ b/tests/native/x86/suite.py @@ -343,12 +343,21 @@ class Suite: after = {str(p.relative_to(keep)): p.read_bytes() for p in keep.rglob("*") if p.is_file()} self.check("tools/native refusal preserves previous outputs and removes scratch", result.returncode == 110 and str(bad).encode() in result.stderr and before == after) - def mutant_generator(self, name, old, new, count=1): + def mutant_generator(self, name, old, new, count=1, within=None): + # within: mutate only the one src/native.om line starting with these bytes. folder = self.out / ("mut-" + name) folder.mkdir() source = (ROOT / "src/native.om").read_bytes() - assert source.count(old) == count, (name, source.count(old), count) - changed = source.replace(old, new) + if within is None: + assert source.count(old) == count, (name, source.count(old), count) + changed = source.replace(old, new) + else: + lines = source.split(b"\n") + hit = [i for i, line in enumerate(lines) if line.startswith(within)] + assert len(hit) == 1, (name, within, len(hit)) + assert lines[hit[0]].count(old) == count, (name, lines[hit[0]].count(old), count) + lines[hit[0]] = lines[hit[0]].replace(old, new) + changed = b"\n".join(lines) binary = self.must([self.omc], data=changed) gen = folder / "gen" gen.write_bytes(binary) @@ -360,7 +369,9 @@ class Suite: ("wrap", b" || n * es > UINTPTR_MAX - lo)", b")", b"#748 golden: vpart len 2^64-1"), ("overlap", b"if ((sp[i].w == 1 || sp[j].w == 1 ||", b"if ((", b"vcopy edit == view"), ("outcopy", b"memmove(o[i].dst, buf[i], o[i].n);", b"(void)buf[i];", b"digest: tag")): - folder, gen = self.mutant_generator(name, old, new) + # The hosted ABI v2 runtime (text fv) only: the freestanding OM-2 runtime (text fq) + # carries some of the same guards, and these callers link output c. + folder, gen = self.mutant_generator(name, old, new, within=b"text fv ") for word, ext in (("c", "c"), ("h", "h")): result = self.generate(word, self.frame_set, gen) self.check(name + " mutant generated " + word, result.returncode == 0) @@ -455,20 +466,25 @@ class Suite: baseline.write_bytes(self.must([self.omc], data=source)) baseline.chmod(0o755) frames = {} + om2_frames = {"v2-set"} for path in sorted(N.rglob("*.om")): if Path(__file__).parent in path.parents: continue text = path.read_bytes() - significant = [line for line in text.splitlines() if not line.startswith(b"note ") and line.strip()] + # A note line is one whose first word is note (a bare `note` too), as src/native.om reads it. + significant = [line for line in text.splitlines() if line.split()[:1] not in ([], [b"note"])] om2 = bool(significant and significant[0] == b"om2") compiler = self.xomc if om2 else self.omc result = self.call([compiler], data=text) if result.returncode: self.check("AArch64 parity fixture compiles " + str(path.relative_to(N)), False) continue - trailer = ("omega-unit " + path.stem + " " + digest(Path(compiler).read_bytes()) + "\n").encode() if om2 else b"" + # The unit name as tools/native writes it (tr -c 'A-Za-z0-9_' '_'). + trailer = ("omega-unit " + re.sub(r"[^A-Za-z0-9_]", "_", path.stem) + " " + digest(Path(compiler).read_bytes()) + "\n").encode() if om2 else b"" frame = text + b"\0" + f"{len(result.stdout):08d}".encode() + result.stdout + trailer frames[path] = frame + if om2: + om2_frames.add(str(path.relative_to(N))) sets = {"v1-set": b"".join(frame for path, frame in frames.items() if path.parent == N), "v2-set": frames.get(N / "madd.om", b"") + b"".join(frames.get(T / (name + ".om"), b"") for name in ("vec", "lay", "one"))} comparisons = [(str(path.relative_to(N)), frame) for path, frame in frames.items()] + list(sets.items()) @@ -476,6 +492,12 @@ class Suite: for word in (*OUTPUTS, "freest"): old = self.generate(word, frame, baseline, target=False) new = self.generate(word, frame, target=False) + if word == "freest" and name in om2_frames: + # Deliberate change: the baseline refuses OM-2 units in output freest (exit 110); + # they are now bound on the caller's stack (docs/NATIVE-ABI.md, ABI v2, freestanding). + self.check("AArch64 freest " + name + ": " + BASELINE + " refused OM-2, now accepted", + old.returncode == 110 and not old.stdout and new.returncode == 0 and new.stdout) + continue self.check("AArch64 byte parity " + BASELINE + " " + name + " " + word, old.returncode == new.returncode and old.stdout == new.stdout and old.stderr == new.stderr) @@ -561,6 +583,50 @@ class Suite: self.check("freestanding x86 result-store mutant caught by caller EMULATED", result.returncode == 1) + def freestanding_om2_x86(self): + # tests/native/test_freestanding_om2.py's caller (FIPS 180-4 digests, out-buffer rules, four + # threads) against `tools/native --target x86linux --freestanding` with OM-2 units, i.e. + # outputs freest + fapic through the SysV adapter, and the copy-back-dropped mutant. + sys.path.insert(0, str(N)) + import test_freestanding_om2 as om2 + good = (ROOT / "src/native.om").read_text() + units = [N / "v2/sha256-om2.om", N / "v2/fsout.om"] + for name, source in (("freestanding-om2-x86", good), ("freestanding-om2-x86-mutant", om2.drop_copyback(good))): + tree = self.out / name + (tree / "tools").mkdir(parents=True) + (tree / "src").mkdir() + shutil.copy2(ROOT / "tools/native", tree / "tools/native") + (tree / "src/native.om").write_text(source) + lib = tree / "lib" + self.must([tree / "tools/native", "--target", "x86linux", "--freestanding", lib, *units]) + objs = [lib / "omega_native.o", lib / "omega_api_defs.o"] + defined, imports = set(), set() + for obj in objs: + elf = obj.read_bytes() + self.check(name + " " + obj.name + " is x86-64 ELF", elf[:6] == b"\x7fELF\x02\x01" and elf[18:20] == b"\x3e\x00") + imports |= {l.split()[-1] for l in self.must(self.nm + ["-u", str(obj)]).decode().splitlines() if l.split()} + defined |= {l.split()[-1] for l in self.must(self.nm + ["--defined-only", "-g", str(obj)]).decode().splitlines() if l.split()} + self.check(name + " objects import only GPU_FS_LINK names", not imports - om2.ALLOWED - defined) + self.must_build(self.call(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-pthread", + "-I", str(lib), str(N / "v2/fsom2.c"), *map(str, objs), + "-o", str(tree / "fsom2")])) + result = self.call(self.guest(tree / "fsom2")) + lines = result.stdout.decode().splitlines() + got = dict(l.split() for l in lines if l.split() and l.split()[0] in om2.WANT) + if source is good: + self.check("freestanding x86 OM-2 FIPS 180-4 digests, bad-arg and trap leave out untouched, four threads EMULATED", + result.returncode == 0 and got == om2.WANT and "badarg 32 1" in lines + and "outok 0 2 7 1" in lines and "outtrap 5 1" in lines and "threads 1" in lines) + # The fapic wrapper's __builtin_trap() is ud2 on x86-64: SIGILL, and the call never returns. + result = self.call(self.guest(tree / "fsom2", "trap")) + self.check("freestanding x86 OM-2 fapic wrapper traps (SIGILL) on a nonzero status EMULATED", + result.returncode == -4 and not result.stdout) + else: + # Every digest must be the caller's untouched 0xa5 pre-call fill, so a crash or a + # partial run cannot pass as the mutant being caught. + self.check("freestanding x86 OM-2 copy-back-dropped mutant leaves the pre-call fill in every digest EMULATED", + result.returncode == 0 and got == om2.MUTANT) + def floor_controls(self): # This is a byte-level foreign ABI oracle, not compiler behavior: # mov %r15,%rax; ret; nop; nop occupies one six-byte export slot. @@ -619,7 +685,7 @@ def main(): for step in (suite.initial_library, suite.identity_and_code, suite.aarch64_parity, suite.callers, suite.stale_and_v1, suite.refusals, suite.runtime_mutants, suite.private_symbols, suite.freestanding_api, suite.trap_controls, - suite.freestanding_x86, suite.floor_controls): + suite.freestanding_x86, suite.freestanding_om2_x86, suite.floor_controls): try: step() except (RuntimeError, AssertionError, OSError, StopIteration) as error: diff --git a/tools/native b/tools/native index d4c2da0..dd4e32c 100755 --- a/tools/native +++ b/tools/native @@ -31,9 +31,13 @@ # refusal (a unit outside the subset, or a name the binding cannot carry) names the unit, exits 110 # and installs nothing; a previous run's outputs are replaced only on success. Extra C flags: # OMEGA_NATIVE_CFLAGS. -# --freestanding accepts only pure integer-scalar OM-1 units and installs omega_native.{c,h,o} -# plus work/. The object has no undefined symbols except the GPU_FS_LINK libc-string allowlist. -# Calls use the caller's stack; traps return status without TLS, heap or a hosted runtime. +# --freestanding accepts pure integer-scalar OM-1 units and OM-2 units without host effects, and +# installs omega_native.{c,h,o} plus work/; with an OM-2 unit also omega_api_decl.h and +# omega_api_defs.{c,o}, whose wrappers call __builtin_trap() on a nonzero status (output fapic) +# instead of abort(). No omega_api.h (its inline wrappers call abort()). The objects have no +# undefined symbols except the GPU_FS_LINK libc-string allowlist. Calls use the caller's stack, an +# OM-2 out parameter is a zero-filled buffer in the entry's frame copied back only on status 0, and +# traps return status without TLS, heap or a hosted runtime. # Freestanding x86 output uses the same contract with a SysV adapter (owned-stack floor 0, as on AArch64). set -eu PIN=734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61 @@ -120,7 +124,7 @@ for u in "$@"; do echo "omega-ident 1 unit=$name abi=$abi profile=$prof src=$(sha256sum < "$src" | cut -d' ' -f1) omc=$pin path=$u" >> "$W/work/ident.txt" done words="c h python rust zig go"; [ $v2 = 0 ] || words="$words api apih apic" -[ "$CMODE" != freest ] || words="freest h" +[ "$CMODE" != freest ] || { words="freest h"; [ $v2 = 0 ] || words="$words apih fapic"; } for w in $words; do if ! generate "$w" < "$W/work/units.in" > "$W/$w.out" 2> /dev/null; then echo "tools/native: refused the set of units (a bound or unit name repeats); nothing installed" >&2 @@ -132,16 +136,32 @@ if [ "$CMODE" = c ]; then mv "$W/python.out" "$W/omega_native.py"; mv "$W/rust.out" "$W/omega_native.rs" mv "$W/zig.out" "$W/omega_native.zig"; mv "$W/go.out" "$W/omega_native.go" fi -[ $v2 = 0 ] || { mv "$W/api.out" "$W/omega_api.h"; mv "$W/apih.out" "$W/omega_api_decl.h"; mv "$W/apic.out" "$W/omega_api_defs.c"; } +if [ "$CMODE" = freest ]; then + [ $v2 = 0 ] || { mv "$W/apih.out" "$W/omega_api_decl.h"; mv "$W/fapic.out" "$W/omega_api_defs.c"; } +elif [ $v2 = 1 ]; then + mv "$W/api.out" "$W/omega_api.h"; mv "$W/apih.out" "$W/omega_api_decl.h"; mv "$W/apic.out" "$W/omega_api_defs.c" +fi # The library names itself (soname), so every caller records libomega_native.so and finds it via rpath. if [ "$CMODE" = freest ]; then + objs=omega_native.o ${CC:-cc} -std=gnu11 -O2 -Wall -Wextra -Werror -Wmissing-prototypes -ffreestanding -fno-builtin \ -include "$W/omega_native.h" ${OMEGA_NATIVE_CFLAGS:-} -c -o "$W/omega_native.o" "$W/omega_native.c" - if ! nm -u "$W/omega_native.o" > "$W/undefined.txt"; then - echo "tools/native: freestanding symbol inspection failed; nothing installed" >&2 - exit 1 + if [ $v2 = 1 ]; then + objs="$objs omega_api_defs.o" + ${CC:-cc} -std=gnu11 -O2 -Wall -Wextra -Werror -Wmissing-prototypes -ffreestanding -fno-builtin \ + -I "$W" ${OMEGA_NATIVE_CFLAGS:-} -c -o "$W/omega_api_defs.o" "$W/omega_api_defs.c" fi - if ! awk 'NF && $NF !~ /^(_GLOBAL_OFFSET_TABLE_|memcpy|memmove|memset|memcmp|strlen|strcmp)$/ {print $NF; bad=1} END {exit bad}' \ + # The objects are linked together, so one's reference to another's global definition (the + # fapic wrappers calling omega2_*) is not an import; everything else must be on the allowlist. + : > "$W/undefined.txt"; : > "$W/defined.txt" + for o in $objs; do + if ! nm -u "$W/$o" >> "$W/undefined.txt" || ! nm --defined-only -g "$W/$o" >> "$W/defined.txt"; then + echo "tools/native: freestanding symbol inspection failed; nothing installed" >&2 + exit 1 + fi + done + if ! awk -v defs="$W/defined.txt" 'BEGIN {while ((getline l < defs) > 0) {n = split(l, f); if (n) def[f[n]] = 1}} + NF && !($NF in def) && $NF !~ /^(_GLOBAL_OFFSET_TABLE_|memcpy|memmove|memset|memcmp|strlen|strcmp)$/ {print $NF; bad=1} END {exit bad}' \ "$W/undefined.txt" > "$W/refused-imports.txt"; then echo "tools/native: freestanding imports refused by inspection; nothing installed" >&2 cat "$W/refused-imports.txt" >&2 @@ -154,16 +174,16 @@ fi # The API headers must compile on their own: their layout size and offset checks are C static # assertions. The definitions are compiled against their prototypes (a disagreement fails here). if [ $v2 = 1 ]; then - ${CC:-cc} -std=gnu11 -fsyntax-only -Wall -Wextra -Werror -I "$W" -x c "$W/omega_api.h" + [ "$CMODE" = freest ] || ${CC:-cc} -std=gnu11 -fsyntax-only -Wall -Wextra -Werror -I "$W" -x c "$W/omega_api.h" ${CC:-cc} -std=gnu11 -fsyntax-only -Wall -Wextra -Werror -I "$W" -x c "$W/omega_api_decl.h" ${CC:-cc} -std=gnu11 -fsyntax-only -Wall -Wextra -Werror -Wmissing-prototypes -I "$W" "$W/omega_api_defs.c" fi # Install together: the previous run's outputs go, the new set comes in. -for f in omega_native.c omega_native.h omega_native.o omega_native.py omega_native.rs omega_native.zig omega_native.go omega_api.h omega_api_decl.h omega_api_defs.c libomega_native.so work; do +for f in omega_native.c omega_native.h omega_native.o omega_native.py omega_native.rs omega_native.zig omega_native.go omega_api.h omega_api_decl.h omega_api_defs.c omega_api_defs.o libomega_native.so work; do rm -rf "$OUT/$f"; [ ! -e "$W/$f" ] || mv "$W/$f" "$OUT/$f" done if [ "$CMODE" = freest ]; then - echo "tools/native: $# pure scalar unit(s) -> $OUT/omega_native.{c,h,o} (+ work/)" + echo "tools/native: $# unit(s) -> $OUT/omega_native.{c,h,o}$([ $v2 = 0 ] || echo ' + omega_api_decl.h, omega_api_defs.{c,o}') (+ work/)" else echo "tools/native: $# unit(s) -> $OUT/libomega_native.so + omega_native.{c,h,py,rs,zig,go}$([ $v2 = 0 ] || echo ' + omega_api.h, omega_api_decl.h, omega_api_defs.c') (+ work/)" fi ```