code wiki / (root) / nx_craft_lit_fit_expanded_t181.nx

nx_craft_lit_fit_expanded_t181.nx source

↩ module page · 5411 lines · 262144 B

1// nx_game_page_emit.nx -- the SOVEREIGN game-page emitter. Until now the browser page for a wasm 2// game was assembled by printf blocks in _ops/nx_emit_game.sh -- real emission logic living in 3// SHELL, against the doctrine (shell only LAUNCHES sovereign ELFs). This organ owns it: reads the 4// .wasm, base64-encodes it (composes nx_base64 -- one encoder, not a coreutils dependency), and 5// emits the complete self-contained page (marker, shim, input forwarding, persistence bytes-mover). 6// usage: nx_game_page_emit <wasm> <out.html> <title> <native-client-name> <controls-html> 7// 8// RECOVERED 2026-08-02 from buildroot/_build/nx_craft_emit.s (the 14:07 build's data section) 9// after a failed in-place rewrite TRUNCATED this file to 0 bytes and the damage was copied to 10// both trees. Every emitted chunk below is the exact byte sequence that build shipped, so the 11// recovered emitter is byte-equivalent to the last one that passed both gates. 12// license_tier: ORIGINAL 13// syscalls.nx -- thin __syscall wrappers used across modules. 14// 15// Sovereign path: no libc. Every memory allocation, file op, and 16// clock read in the rest of the runtime routes through one of these 17// helpers. Numbers match Linux RV64; NishiOS uses the same set. 18// 19// Extracted from runtime.nx and ir.nx's copy-pasted helpers so the 20// module-import build doesn't produce duplicate symbols. 21 22// Tier aliases (nx_size / nx_idx / nx_fd / ...) ride along with the 23// syscall shelf: 141 runtime files use `as nx_size` etc. and only 24// compiled historically because the old parser silently void-cast 25// unknown type names (T#nx-int-alias-size-0 closed that hole LOUDLY, 26// which exposed the missing import). nx_tier.nx is pure type 27// aliases (0 funcs); prepass_register_aliases skips duplicates, so 28// modules that also import it directly stay fine. 29// nx_tier.nx -- substrate-wide tier configuration. 30// 31// Single point of edit for scale-agnostic substrate. Per user 32// directive 2026-05-13: "with the i64 it looks hardcoded everywhere 33// if we really want this dynamic dont we want that to be a changeable 34// value everywhere so it can switch to i128 and i256 etc." 35// 36// Per cardinals: 37// - feedback-numeric-tier-ladder.md (N0..N9 swap) 38// - feedback-scale-agnostic-substrate.md (MCU..HPC swap) 39// - feedback-substrate-additive-not-restrictive.md (declare cost) 40// 41// SEMANTIC ALIASES (not all should swap simultaneously): 42// 43// nx_int -- DEFAULT ARITHMETIC integer. Swappable across the 44// numeric tier ladder. Swap this to i128 to make the 45// entire substrate compute in 128-bit integers. 46// 47// nx_size -- MEMORY-SIZE integer. Always platform-pointer-width. 48// Used for buffer sizes, mmap byte counts, struct 49// sizes. Does NOT swap with nx_int -- changing this 50// would break pointer arithmetic. Stays i64 on RV64. 51// 52// nx_idx -- ARRAY-INDEX integer. Same width as nx_size on 53// flat-memory targets. Distinct alias so future 54// GPU/distributed targets can change indexing without 55// touching arithmetic. 56// 57// nx_byte -- The byte type. Stays u8. Distinct alias so MCU 58// targets that emulate u16-byte memory could rebind. 59// 60// HARDWARE-TIER BUFFER SIZES (declare cost, don't restrict): 61// 62// NX_BUF_TINY -- 64 B (MCU-friendly; stack-safe) 63// NX_BUF_SMALL -- 256 B (MCU heap-friendly) 64// NX_BUF_MEDIUM -- 4096 B (page-size; workstation default) 65// NX_BUF_LARGE -- 64 KiB (server-friendly) 66// NX_BUF_HUGE -- 1 MiB (HPC; assumes virtual memory) 67// 68// Use these instead of `sys_mmap(4096)` etc. so the substrate 69// announces its memory footprint and tier-incompatible code can 70// be flagged by audit. 71// 72// HARDWARE TIER (informational; downstream code may branch): 73// 74// NX_TIER_MCU = 0 -- microcontroller, kilobytes RAM 75// NX_TIER_SOVEREIGN_CHIP = 1 -- custom silicon, ~MB RAM 76// NX_TIER_FAMILY_DEVICE = 2 -- phone/router, ~GB RAM 77// NX_TIER_WORKSTATION = 3 -- laptop/desktop, ~10-100 GB RAM 78// NX_TIER_SERVER = 4 -- server-class, ~TB RAM 79// NX_TIER_HPC = 5 -- cluster, distributed 80// 81// COMPILE-TIME SWAP for nx_int (uncomment exactly one line): 82 83// THIS FILE IS THE SINGLE DEFINITION SITE for substrate-wide types. 84// Per user directive 2026-05-13: only this file (and platform-ABI 85// definition files like nx_syscalls.nx) should declare bare i64. 86// Every other substrate module uses the aliases below. 87 88// ===== arithmetic-tier aliases (swappable per nx_int tier ladder) ===== 89 90type nx_int = i64 // N1 -- default; 9 quintillion, fits all physical scales 91// type nx_int = i32 // N0 -- MCU / embedded 92// type nx_int = i128 // N2 -- queued; needs nx_i128 backend ops 93// type nx_int = i256 // N3 -- shipped (nx_i256.nx); cosmology / crypto 94 95// ===== platform-width aliases (stay at pointer width) ================= 96 97type nx_size = i64 // memory-size / byte-count 98type nx_idx = i64 // array-index 99type nx_byte = u8 // single-byte unit 100 101// ===== POSIX/Linux platform-ABI aliases (mandated 64-bit on RV64) ==== 102// 103// Each is a 64-bit integer by Linux RV64 ABI. Renamed here so substrate 104// code never writes bare `i64` for these semantic types. 105 106type nx_fd = i64 // file descriptor (kernel-mandated width) 107type nx_exit = i64 // exit / status code (main() return) 108type nx_pid = i64 // process id 109type nx_uid = i64 // user id 110type nx_gid = i64 // group id 111type nx_syscall_num = i64 // Linux syscall number 112type nx_off = i64 // file offset (off_t) 113type nx_errno = i64 // errno (negative on syscall failure) 114 115// ===== SEMANTIC TYPE GENEALOGY (added 2026-05-20) ====================== 116// 117// Per cardinal [[feedback-type-genealogy-math-cardinal-not-script]] 118// AND its immediate refinement (same session): every alias collapsing 119// to i64 is "y2k incestuous" -- relabeling, not genealogy. Real 120// semantic types pick the APPROPRIATE underlying width based on 121// the physics of the values they represent: 122// 123// - Small sealed enums (15 outcomes, 18 probe kinds) -> u8 124// - Display pixel coords (~32M max realistic) -> i32 125// - Q10 / Q14 fixed-point (values * 1024 / 16384) -> i32 126// - 32-bit color packs (RGBA8888) -> u32 127// - Q20 fixed-point (values * 1048576) -> i64 128// - Wide color packs (RGBA16161616, PRESERVE_ALL) -> u64 129// - Timestamps (ns / us / ms / cycles) -> i64 (2038 Y2K38) 130// - 64-bit hash digests -> u64 131// - Cryptographic hashes (SHA-256, SHA-512) -> STRUCT (multi-word; queued) 132// - Virtual addresses on 64-bit ISA -> u64 133// 134// Each type is a child of its PHYSICALLY-APPROPRIATE parent 135// (i8/u8/i32/u32/i64/u64), not blanket-i64. This breaks the 136// y2k-incestuous trap where renaming i64 N ways pretends to be 137// type discipline while every value silently shares one width. 138 139// ----- TIME family (all i64; ns/us/ms/cycles legitimately need it) ----- 140// 2038 Y2K38 lurks for 32-bit time_t; i64 is the substrate-honest 141// choice. ms/us/ns + cycles all i64. s_q14 needs only i32 range 142// (val*16384 fits comfortably in i32 for typical second scales) but 143// we stay at i64 to compose cleanly with the i64 time arithmetic 144// across the substrate. 145type nx_ns = i64 // nanoseconds (since boot, monotonic) 146type nx_us = i64 // microseconds (since boot, monotonic) 147type nx_ms = i64 // milliseconds (since epoch, wall) 148type nx_s_q14 = i64 // seconds in Q14 fixed-point 149type nx_cycles = i64 // CPU cycle count 150 151// ----- HASH family (non-cryptographic 64-bit; crypto = STRUCT) ----- 152// FNV-1a / xxhash digest is u64 by spec. SHA-256 / SHA-512 / BLAKE 153// hashes are MULTI-WORD; they're declared as structs in 154// nx_sha256.nx / nx_sha512.nx / nx_blake2b.nx (each carries its own 155// fixed-size byte array; NOT i64). 156type nx_hash64 = u64 // FNV-1a / xxhash / truncated SHA -- 64-bit digest 157 158// ----- ETG family (sealed enums; small value space -> u8) ----- 159// nx_outcome_id sealed enum has 11 values; u8 fits 256 160// nx_probe_kind sealed enum has 18 values; u8 fits 256 161// nx_claim_source sealed enum has 13 values; u8 fits 256 162// nx_silicon_serial is a content-addressed identity HASH; u64. 163type nx_outcome_id = u8 // NX_ETG_OUTCOME_* (11 values; u8 fits) 164type nx_probe_kind = u8 // NX_ETG_PROBE_* (18 values; u8 fits) 165type nx_claim_source = u8 // NX_ETG_CLAIM_* (13 values; u8 fits) 166type nx_silicon_serial = u64 // per-die identity hash (cryptographic-strength width) 167 168// ----- PERF family (sealed enums) ----- 169type nx_pathology_id = u8 // NX_PERF_PATH_* (15 values; u8 fits) 170type nx_flow_state_id = u8 // NX_FLOW_STATE_* (6 values; u8 fits) 171 172// ----- FIXED-POINT family (width chosen by precision*range) ----- 173// Q10: value * 1024. Typical seed values are 0..255 so q10 max is 174// ~261K; i32 holds up to ~2.1B -> plenty of headroom. 175// Q14: value * 16384. Typical max around 16K of seed -> q14 ~ 2.6e8; 176// i32 holds up to 2.1e9 -> headroom for a few decimal seconds. 177// Q20: value * 1048576. Wider precision; needs i64 to avoid wrap. 178type nx_q10 = i32 // val * 1024; ~0.001 precision 179type nx_q14 = i32 // val * 16384; ~6e-5 precision 180type nx_q20 = i64 // val * 1048576; ~1e-6 precision 181 182// ----- GRAPHICS family (display coords + color packs at real widths) ----- 183// Modern displays are well within 32-bit pixel addressing. 184// 8K display = 7680x4320 pixels. i32 holds 2.1B -> plenty. 185// nx_color_rgba8 = 32-bit packed RGBA (the common case) 186// nx_color_rgba16 = 64-bit packed RGBA16161616 (HDR / wide gamut) 187type nx_pixel_x = i32 // screen X in pixels 188type nx_pixel_y = i32 // screen Y in pixels 189type nx_color_rgba8 = u32 // RGBA8888 packed 190type nx_color_rgba16 = u64 // RGBA16161616 packed (HDR / preserve-all) 191 192// ----- PERCEPTUAL family (sealed enum; small value space) ----- 193// nx_perceptual_profile has ~40 declared values up through 194// NX_PERCEPT_PRESERVE_ALL = 9999. Sentinel value 9999 needs i16, 195// not u8. i16 fits -32768..32767 with room for sentinels. 196type nx_perceptual_profile = i16 // NX_PERCEPT_* (~40 values + 9999 sentinel) 197 198// ----- ADDRESS family (virtual addresses on 64-bit ISA) ----- 199// Pointer-width is u64 on all our supported 64-bit targets 200// (RV64 / x86_64 / AArch64 / ppc64le / loongarch64 / mips64 / 201// s390x / RV32 uses u32 -- TODO: tier-conditional). 202type nx_addr = u64 // raw virtual address (caller casts to *u8) 203 204// nx_capability_manifest: 205// variant_class: tier_config 206// variant_id: tier_config_v1_global 207// requires_isa: [rv32i, rv32imac, rv64imac, rv64imacv, x86_64, aarch64, armv7a, cortex_m, avr, xtensa, wasm32] 208// requires_syscalls: [] 209// requires_ram_min_b: 0 // pure-const + typedef module, no runtime cost 210// tier_floor: NX_TIER_MCU 211// tier_ceiling: NX_TIER_HPC 212// cost_model: 213// flops_per_n: 0.0 214// bytes_per_n: 0.0 215// syscalls_per_n: 0.0 216// adversary_class: THREAT_OPPORTUNISTIC 217// 218// Note: This file is the substrate's TIER ENUM SOURCE OF TRUTH. It 219// has no variants by design (it IS the variant_class taxonomy that 220// other primitives' tier_floor / tier_ceiling reference). Manifest 221// declared for hygiene completeness; selector will skip it. 222 223// ---- buffer-size constants (use instead of bare numbers) ------- 224 225const NX_BUF_TINY: nx_size = 64 226const NX_BUF_SMALL: nx_size = 256 227const NX_BUF_MEDIUM: nx_size = 4096 228const NX_BUF_LARGE: nx_size = 65536 229const NX_BUF_HUGE: nx_size = 1048576 230 231// ---- hardware tier sentinels ----------------------------------- 232 233const NX_TIER_MCU: nx_int = 0 234const NX_TIER_SOVEREIGN_CHIP: nx_int = 1 235const NX_TIER_FAMILY_DEVICE: nx_int = 2 236const NX_TIER_WORKSTATION: nx_int = 3 237const NX_TIER_SERVER: nx_int = 4 238const NX_TIER_HPC: nx_int = 5 239 240// ---- numeric tier sentinels (informational) -------------------- 241 242const NX_NUM_N0_I32: nx_int = 0 243const NX_NUM_N1_I64: nx_int = 1 244const NX_NUM_N2_I128: nx_int = 2 245const NX_NUM_N3_I256: nx_int = 3 246const NX_NUM_N4_I512: nx_int = 4 247const NX_NUM_N5_BIGINT: nx_int = 5 248 249// ---- byte-width of substrate types (replace bare `8` / `4`) ---- 250// 251// Use these wherever you need the byte count of a substrate type -- 252// e.g., sys_mmap(N * NX_SIZEOF_NX_SIZE) to allocate N nx_size slots. 253// Swap nx_int's underlying type and ONLY this constant changes. 254 255const NX_SIZEOF_NX_INT: nx_size = 8 // nx_int currently i64 -> 8 bytes 256const NX_SIZEOF_NX_SIZE: nx_size = 8 // nx_size always pointer-width 257const NX_SIZEOF_NX_IDX: nx_size = 8 // nx_idx alias of nx_size 258 259// ---- POSIX stdio file descriptors (replace bare 0/1/2) --------- 260 261const NX_FD_STDIN: nx_fd = 0 262const NX_FD_STDOUT: nx_fd = 1 263const NX_FD_STDERR: nx_fd = 2 264 265const SYS_MAGIC_1024: i64 = 1024 266const SYS_MAGIC_1000000: i64 = 1000000 267const SYS_MAGIC_4294967296: i64 = 4294967296 268// first read window for a size-UNKNOWABLE file (lseek END <= 0); doubles while it fills -- see sys_read_file 269const SYS_READ_GROW_INIT: i64 = 65536 270const SYS_MAGIC_100000: i64 = 100000 271 272// ---- syscall numbers (per-target) ---- 273// 274// Cross-target via the macro processor (cardinal landed 2026-05-20: 275// feedback-hardware-agnostic-is-robustness -- the substrate must 276// compile + run on every silicon we point it at). Default path 277// (TARGET_X86_64 not defined) carries Linux RV64 numbers used by 278// qemu-RV64 + NishiOS. When nxc2 is invoked with --target x86_64 279// main.c pre-defines @macro TARGET_X86_64 1 so this file resolves 280// to x86_64 Linux ABI numbers. 281// 282// nx_syscalls_x86_64.nx remains the dedicated x86_64-only mirror 283// for files that want explicit single-target imports (e.g., bench 284// smokes built only for x86_64). This block makes nx_syscalls.nx 285// itself dual-target so substrate primitives compile portably. 286 287@ifdef TARGET_X86_64 288const SYS_READ: i64 = 0 289const SYS_WRITE: i64 = 1 290const SYS_CLOSE: i64 = 3 291const SYS_LSEEK: i64 = 8 292const SYS_OPENAT: i64 = 257 293const SYS_EXIT: i64 = 60 294const SYS_MMAP: i64 = 9 295const SYS_CLOCK_GETTIME: i64 = 228 296const SYS_IOCTL: i64 = 16 297const SYS_CLOCK_NANOSLEEP: i64 = 230 298// Namespace/container family, x86 branch (debt 1785528831). Moved here from 299// nx_syscalls_x86_64.nx so ONE module owns the wrapper set -- a TU reaching both 300// modules used to hold every wrapper TWICE, resolved silently by definition ORDER. 301const SYS_CHROOT: i64 = 161 302const SYS_MOUNT: i64 = 165 303const SYS_UNSHARE: i64 = 272 304const SYS_GETUID: i64 = 102 305const SYS_GETGID: i64 = 104 306const SYS_POLL: i64 = 7 307@endif 308 309@ifndef TARGET_X86_64 310const SYS_READ: i64 = 63 311const SYS_WRITE: i64 = 64 312const SYS_CLOSE: i64 = 57 313const SYS_LSEEK: i64 = 62 314const SYS_OPENAT: i64 = 56 315const SYS_EXIT: i64 = 93 316const SYS_MMAP: i64 = 222 317const SYS_CLOCK_GETTIME: i64 = 113 318const SYS_IOCTL: i64 = 29 319const SYS_CLOCK_NANOSLEEP: i64 = 115 320// Namespace/container family, RV64 branch (debt 1785528831). This is the branch actually 321// KEPT (TARGET_X86_64 is hard-pinned undefined), so these are the numbers the x86 backend 322// translates at emit: 51->161 chroot, 40->165 mount, 97->272 unshare, 174->102 getuid, 323// 176->104 getgid. The 40 and 51 rows were added to x86ctx_rv64_to_x86_64_syscall and 324// shipped FIRST -- without them both would pass through to the WRONG x86 syscall 325// (sendfile / getsockname), silently, because that translator's default is `return num`. 326const SYS_CHROOT: i64 = 51 327const SYS_MOUNT: i64 = 40 328const SYS_UNSHARE: i64 = 97 329const SYS_GETUID: i64 = 174 330const SYS_GETGID: i64 = 176 331const SYS_POLL: i64 = 73 332@endif 333 334func sys_ioctl(fd: i64, request: i64, arg: i64) -> i64 { 335 return __syscall(SYS_IOCTL, fd, request, arg, 0, 0, 0) 336} 337 338// poll(2): wait for events on fds. fds points to an array of `nfds` 339// struct pollfd { i32 fd; i16 events; i16 revents } (8 bytes each). 340// timeout_ms < 0 = block forever, 0 = return immediately. Returns the 341// count of ready fds (>0), 0 on timeout, or -errno. Used by the 342// substrate's own network diagnostics (bounded non-blocking connect) 343// instead of reaching for external tools. (rv64 const = ppoll; this 344// wrapper only runs on the x86_64 target.) 345func sys_poll(fds: *u8, nfds: i64, timeout_ms: i64) -> i64 { 346 return __syscall(SYS_POLL, fds, nfds, timeout_ms, 0, 0, 0) 347} 348 349// ---- core wrappers ---- 350 351func sys_write(fd: i64, buf: *u8, count: i64) -> i64 { 352 return __syscall(SYS_WRITE, fd, buf, count, 0, 0, 0) 353} 354 355func sys_read(fd: i64, buf: *u8, count: i64) -> i64 { 356 return __syscall(SYS_READ, fd, buf, count, 0, 0, 0) 357} 358 359func sys_close(fd: i64) -> i64 { 360 return __syscall(SYS_CLOSE, fd, 0, 0, 0, 0, 0) 361} 362 363// chdir. The compiler only rv64->x86 translates CONSTANT syscall numbers (x86ctx_emit_syscall: 364// VK_CONST_INT); chdir is absent from that table, so a constant 49 falls through to x86_64 bind and a 365// constant 80 is mapped to fstat -- BOTH gave EBADF (PROBE-PROVEN by test_chdir). The documented escape 366// (nx_x86_64_ctx.nx:1004 "Runtime-computed syscall number -- load as-is") is to make op0 RUNTIME: a memory 367// load can't be folded to VK_CONST_INT, so the raw x86_64 number 80 passes through untranslated = real 368// chdir. Used by the supervisor to set a spawned daemon's CWD before execve. 0 on success, -errno on fail. 369func sys_chdir(path: *u8) -> i64 { 370 let nbox: *i64 = sys_mmap(16) as *i64 371 nbox[0] = 80 // x86_64 chdir, forced runtime so the rv64->x86 xlate is skipped 372 return __syscall(nbox[0], path as i64, 0, 0, 0, 0, 0) 373} 374 375// getcwd -- SAME runtime-number escape as sys_chdir directly above, for the same documented reason: the 376// rv64->x86 translator only rewrites CONSTANT syscall numbers, and getcwd is absent from that table, so a 377// constant would be mangled exactly as chdir's was. A memory load cannot be folded to VK_CONST_INT, so the 378// raw x86_64 number passes through untranslated. 379// WHY THIS EXISTS (2026-08-14): the shim had sys_chdir but NOTHING to ask where we are. Every organ that 380// resolves a path against the CWD could therefore only print a RELATIVE path -- a claim whose truth depends 381// on invisible state. Three separate working-directory faults in one session stayed invisible until they 382// bit, and in each the reader could not tell "the file is missing" from "I am standing somewhere else". 383// ★★★AN ORGAN THAT CANNOT REPORT WHERE IT IS CANNOT WRITE AN HONEST PATH. 384// Returns the byte length written INCLUDING the terminator, or -errno (notably -ERANGE if cap is short). 385// SYS_PATH_MAX is exported so a caller never hand-writes the size: the FIRST consumer of sys_getcwd (this 386// author, minutes after adding it) wrote `sys_mmap(4096)` and `sys_getcwd(buf, 4096)` on consecutive 387// lines -- a bare literal AND a duplicate-authored pair, the exact shape being removed elsewhere the same 388// day. ★★A NEW PRIMITIVE THAT DOES NOT EXPORT ITS OWN SIZE INVITES EVERY CALLER TO INVENT ONE. 389const SYS_PATH_MAX: i64 = 4096 // Linux PATH_MAX; getcwd returns -ERANGE below it 390// The DIRECTORY sibling of MODE_0644, added on the same evidence: `0x1ed` appears at 569 sites in 391// buildroot/runtime (nx_shelltool, corpus_complete=1), i.e. the estate scatters TWO file-mode constants, 392// not one. Named here so the pair lives together and a reader meets both at the same place. 393const MODE_0755: i64 = 0x1ed // rwxr-xr-x : default mode for a created directory 394func sys_getcwd(buf: *u8, cap: i64) -> i64 { 395 let nbox: *i64 = sys_mmap(16) as *i64 396 nbox[0] = 79 // x86_64 getcwd, forced runtime so the rv64->x86 xlate is skipped 397 return __syscall(nbox[0], buf as i64, cap, 0, 0, 0, 0) 398} 399 400// ⚠AT_FDCWD MOVED UP 2026-07-20 -- IT WAS A LIVE MISCOMPILE. This const was declared ~60 lines BELOW 401// (in the openat block) while sys_unlinkat and sys_fchmodat immediately below REFERENCE it. A module 402// const referenced ABOVE its declaration does not resolve, and nx_cc silently substituted CONSTANT 0 403// -- so both wrappers passed dirfd=0 (stdin) instead of -100. Absolute paths survive that (openat 404// ignores dirfd when the path is absolute), RELATIVE paths do not, which is exactly why unlinkat was 405// long recorded as flaky and "passing only by luck". Surfaced by the new unknown-identifier 406// diagnostic, which turned a silent 0 into a compile error. LAW (already banked, now enforced): 407// module-wide consts/statics go ABOVE every possible reader. 408const AT_FDCWD: i64 = -100 409 410// unlinkat(AT_FDCWD, path, 0) -- delete a file. x86_64 263 is a PROVEN pass-through (not an rv64 key), 411// but this is THE canonical home: 5+ organs hand-rolled `__syscall(263,...)` before this landed (DRY, 412// 2026-07-20). 0 on success, -errno on fail. 413func sys_unlinkat(path: *u8) -> i64 { 414 return __syscall(263, AT_FDCWD, path as i64, 0, 0, 0, 0) 415} 416 417// fchmodat(AT_FDCWD, path, mode) -- chmod by path. ⚠a CONSTANT 268 gets rv64->x86 TRANSLATED to the 418// wrong syscall (silent no-op chmod -- cost a vacuous-permission-test debug cycle, 2026-07-20), so the 419// number is forced RUNTIME via the sys_chdir nbox pattern. 0 on success, -errno on fail. 420func sys_fchmodat(path: *u8, mode: i64) -> i64 { 421 let nbox: *i64 = sys_mmap(16) as *i64 422 nbox[0] = 268 // x86_64 fchmodat, forced runtime so the xlate is skipped 423 return __syscall(nbox[0], AT_FDCWD, path as i64, mode, 0, 0, 0) 424} 425 426// exit_group(2) -- terminate ALL tasks in the thread group. Raw x86_64 231 427// (231 is NOT an rv64 key in the compiler's swap table, so it passes through 428// untranslated -- the munmap-11 precedent). THE explicit program-exit call 429// once a process holds live nx_thread_pool workers: CLONE_VM tasks are 430// separate PIDs, so plain sys_exit (93 -> x86 60, single task) leaves them 431// running, holding stdout open and wedging any pipeline that waits for EOF 432// (found 2026-07-07: the shared-pool matmul dispatcher hung the build lane 433// this way). Return-from-main already exit_groups via the _start trampoline; 434// use THIS for explicit early program exit. Per-THREAD exit stays sys_exit 435// (see nx_thread_exit). 436func sys_exit_group(code: i64) -> i64 { 437 return __syscall(231, code, 0, 0, 0, 0, 0) 438} 439 440// setpriority(PRIO_PROCESS=0, who=0 -> SELF, prio) -- x86_64 syscall 141. 441// Lower priority = larger nice value; 19 is the maximum yield. 442// WHY A WRAPPER AND NOT AN OPERATOR STEP (measured 2026-07-30): a bulk media 443// migration walk saturated the NAS; every forked organ queued behind its I/O so 444// EVERY agent MCP call 503'd for minutes -- the control plane went blind while a 445// background job did exactly what it was told. `renice 19` on the running pid 446// restored interactive service at once. 447// LAW: a long-running BULK job must yield to the interactive control plane BY 448// CONSTRUCTION at its own launch, not when an operator notices. Bind it to the 449// one act every bulk job performs (its startup) and nothing has to remember it. 450// WARN: `ionice` does NOT exist on the Synology busybox, so the I/O-class lever 451// is unavailable; CPU nice sufficed because the walk is SHA-256-bound over 452// cached reads (state R, not D, once niced). 453func sys_setpriority(prio: i64) -> i64 { 454 return __syscall(141, 0, 0, prio, 0, 0, 0) 455} 456 457// ADDITIVE TWIN 2026-08-04 (nx_resgov): re-nice ANOTHER process by pid. The incumbent above pins 458// who=0 = "me", so it cannot deprioritise a runaway -- and a governor that can only slow ITSELF has 459// no graceful rung between "observe" and "kill". PRIO_PROCESS=0, who=pid. Existing callers untouched 460// (rule 19: add the new entry point, never re-shape the one in service). 461func sys_setpriority_of(pid: i64, prio: i64) -> i64 { 462 return __syscall(141, 0, pid, prio, 0, 0, 0) 463} 464 465// munmap -- free a region from sys_mmap. x86_64 munmap = 11; 11 is NOT an rv64 number in the compiler's 466// swap table, so the literal passes through untranslated = real munmap (unlike chdir, where rv64 80=fstat 467// intercepted it). CRITICAL for long-running loops: the supervisor's per-poll proc_* scans mmap 64KB+ each; 468// unfreed, the leak hits DSM's RLIMIT_AS -> mmap returns -12 -> the code writes through it -> SEGFAULT 469// (dmesg-proven: nx_hostctl segfault at 0xfffffffffffffff4). Free scan buffers to keep the supervisor alive. 470// ===== SMALL-ALLOCATION BUMP ARENA (2026-08-06, debt 1785516350 / 1786055008) ===================== 471// MEASURED FIRST, THEN BUILT. nx_arena_probe: 20,000 x sys_mmap(32) -> VmSize 80,172 kB, 472// VmRSS 80,024 kB. 640 KB of requested data cost 78 MB of RESIDENT memory -- 4096 bytes per 32-byte 473// request, exactly one page and one kernel VMA each. Across the corpus nx_mmapbal deep counts 17,157 474// functions / 43,498 sites that allocate and never return, so this multiplier is the actual shape of 475// the leak: the call sites are not individually wrong so much as individually EXPENSIVE. 476// 477// One VMA per call is also a HARD CORRECTNESS CEILING, not just a memory cost: vm.max_map_count 478// defaults to 65530, after which mmap returns -ENOMEM and callers write through the failed pointer. 479// That is precisely the dmesg-proven nx_hostctl SEGFAULT at 0xfffffffffffffff4 described below. 480// 481// SO: requests <= NXA_SMALL_MAX are bump-allocated out of a 256 KiB chunk (one VMA per ~5,400 small 482// allocations instead of one per allocation). Larger requests take the ORIGINAL path untouched -- 483// they are the ones plausibly relying on page alignment, and they are not where the leak lives. 484// 485// THE ZEROING CONTRACT IS LOAD-BEARING AND IS PRESERVED BY NEVER RECYCLING. Callers rely on mmap 486// returning zeroed memory (nx_mmapbal: "mmap zeroes, so an untouched slot reads empty with no init 487// loop"). Bytes handed out here come from a freshly mmapped chunk and are NEVER handed out twice, so 488// every region is zero-filled exactly as before. LIFO give-back on munmap was deliberately REJECTED: 489// it would recover memory but hand back dirty bytes, silently breaking every caller that trusts the 490// zero -- a correctness regression traded for a memory win, which is the wrong trade. 491// 492// KNOWN TRADE-OFF, stated rather than hidden: small allocations are now ADJACENT within a chunk 493// instead of isolated in their own pages. An overrun that today walks off the end of a page and 494// SIGSEGVs loudly may instead corrupt a neighbouring allocation quietly. NXA_GAP puts slack between 495// allocations and NXA_SMALL_MAX is kept deliberately low to bound the exposure, but the risk is real 496// and is the reason this starts at 256 rather than a page. 497// ---- MEMORY ORDERING, THE ONE DEFINITION ------------------------------------------------------- 498// Moved here from nx_atom.nx on 2026-08-25 and DELETED from its two other copies 499// (nx_atomic_intrinsic_test, nx_simd_i32x8_test). Measured before the move, corpus_complete=1: 500// THREE files each declared NX_MO_SEQ_CST = 5 independently. A constant written in three places is 501// three rulers that agree until one of them does not. 502// 503// They live at THIS layer because the arena allocator below needs an ordering value for its own 504// lock, and this file cannot import nx_atom.nx -- nx_atom imports THIS file, so that direction is a 505// cycle. Everything that had these constants still has them: nx_atom.nx imports this file, and so 506// does every consumer of nx_atom. 507// 508// The __atomic_* forms these feed are COMPILER INTRINSICS, not library calls, so this file can use 509// them with no import at all. Verified in nx_x86_64_ctx rather than assumed: __atomic_cas_i64 emits 510// `lock cmpxchgq`, __atomic_faa_i64 emits `lock xaddq`, __atomic_fence emits `mfence`. On x86-64 the 511// ordering operand is not consulted by the emitter because those instructions are full barriers 512// regardless; it is carried for the RV64A backend, where it selects the aq/rl bits. 513const NX_MO_RELAXED: i64 = 0 514const NX_MO_CONSUME: i64 = 1 515const NX_MO_ACQUIRE: i64 = 2 516const NX_MO_RELEASE: i64 = 3 517const NX_MO_ACQ_REL: i64 = 4 518const NX_MO_SEQ_CST: i64 = 5 519 520const NXA_SMALL_MAX: i64 = 256 521const NXA_CHUNK: i64 = 262144 522const NXA_ALIGN: i64 = 16 523const NXA_GAP: i64 = 16 524const NXA_STATE: i64 = 4096 525// RING CANARY (temporary diagnostic): the single-slot canary checked only the immediately 526// previous allocation and reported ZERO overruns -- but the bisection proved the write is 527// DELAYED, landing after later allocations have been served. Track the last NXA_RING 528// allocations and re-verify every one of them on each call. Lives at i64 slot NXA_RBASE in 529// the state page; the reporter borrows bytes 64/128, so 512 is clear of it. 530const NXA_RING: i64 = 128 531const NXA_RBASE: i64 = 64 532// ---- ARENA MARK/RESET (2026-08-12, additive; the durable fix for bump-without-reset). The arena 533// abandons a full chunk on rollover, so a long-running accept loop accumulates chunks into one giant 534// coalesced VMA (hub_gw MEASURED 3.4GB over 64k requests). A daemon marks the arena AFTER startup and 535// resets at its accept-loop's quiescent point; reset munmaps every chunk allocated since the mark and 536// zeroes the marked chunk's reclaimed tail, so per-request small allocations reuse a bounded slab. 537// State slots (state page is 512 i64): [3]=chunk_count [4]=mark_valid [5]=mark_bump [6]=mark_chunk_end 538// [7]=mark_chunk_count; the chunk-base list lives at slots NXA_CHUNKBASE..+NXA_CHUNKMAX (clear of the 539// ring at 64..320 and the reporter scratch below 64). CONTRACT: the caller guarantees NO arena 540// allocation made after the mark is still referenced at reset (the accept-loop top, where the previous 541// request's frames have all returned -- the same quiescent point ss_cache_reap already uses). LARGE 542// (>NXA_SMALL_MAX) allocations take their own VMA and are NOT tracked here; a per-request large mmap 543// still needs its own munmap. Untracked-overflow (>NXA_CHUNKMAX chunks between resets) degrades to the 544// old leak for the excess, never corrupts. 545// ---- ARENA MUTUAL EXCLUSION (2026-08-25) ------------------------------------------------------- 546// THE DEFECT: the bump-pointer advance below was a plain read-modify-write -- 547// let p: i64 = nxa_st[0] 548// nxa_st[0] = p + need 549// -- so two threads that read nxa_st[0] before either wrote it BOTH RECEIVE THE SAME POINTER and 550// then write over each other. The chunk refill, the ring-canary scan and the nxa_st[2] counter have 551// the same shape. MEASURED while shipping structured concurrency: eight pool workers calling a 552// helper that allocates a 16-byte timespec raced this cursor and produced ARENA-OVERRUN 553// prev_alloc_size=16 followed by SIGSEGV. It generalises to EVERY small allocation from more than 554// one thread, which is why the scoped-spawn child body was written to allocate nothing at all. 555// 556// WHY A LOCK AND NOT A LOCK-FREE BUMP. A fetch-and-add on the cursor fixes only the fast path; two 557// threads can still both observe the chunk exhausted and both refill, and the canary ring and the 558// counter would still race. One lock over the whole mutable region is correct by inspection, which 559// on the allocator that every organ in the estate calls is worth more than a clever fast path. 560// THE COST IS NOT THE DOMINANT COST HERE: this function ALREADY walks all NXA_RING canary slots on 561// every allocation, so one uncontended `lock cmpxchgq` is far below the noise of work already done. 562// 563// SLOT 4 IS FREE BY THE LAYOUT ABOVE: [0] cursor, [1] limit, [2] ring counter, [3] chunk count, and 564// the ring starts at NXA_RBASE=64. It is also clear of the byte-64 and byte-128 scratch that 565// nxa_report_overrun formats digits into (slots 8 and 16), which slot 4 (bytes 32-39) does not touch. 566const NXA_LOCK: i64 = 4 567// A BOUND ON AN UNKNOWABLE WAIT, DERIVED RATHER THAN PICKED, AND ITS EXHAUSTION ANNOUNCES. The 568// longest thing the critical section can do is the NXA_RING canary scan plus one mmap, so a spin far 569// beyond that is not contention -- it is a holder that is never coming back. Eight times the ring 570// gives an order of magnitude of headroom over the longest legitimate hold; on reaching it the 571// allocator SAYS SO on stderr once and keeps waiting, because hanging visibly is recoverable and 572// corrupting silently is not, and dying inside the allocator would take down a process that may be 573// merely slow. 574const NXA_LOCK_WARN: i64 = NXA_RING * 8 575// Slot 5: "the contention hint has already been printed by this process". Also free by the layout 576// above and clear of every scratch region. It is a FLAG, not a counter, and it is set through a CAS 577// so the once-ness is itself race-free rather than depending on the lock it reports about. 578const NXA_LOCK_WARNED: i64 = 5 579 580const NXA_CHUNKBASE: i64 = 320 581const NXA_CHUNKMAX: i64 = 192 582 583// [0] = next free byte, [1] = one past the end of the current chunk. A static POINTER to a real 584// mmapped page rather than scalar statics, matching the idiom the corpus already proves; the state 585// page is taken through __syscall directly so this can never recurse into itself. 586static nxa_st: *i64 587 588// munmap -- free a region from sys_mmap. x86_64 munmap = 11; 11 is NOT an rv64 number in the compiler's 589// swap table, so the literal passes through untranslated = real munmap (unlike chdir, where rv64 80=fstat 590// intercepted it). CRITICAL for long-running loops: the supervisor's per-poll proc_* scans mmap 64KB+ each; 591// unfreed, the leak hits DSM's RLIMIT_AS -> mmap returns -12 -> the code writes through it -> SEGFAULT 592// (dmesg-proven: nx_hostctl segfault at 0xfffffffffffffff4). Free scan buffers to keep the supervisor alive. 593// 594// A small len means the region came from the bump arena above, because sys_mmap routes by the SAME 595// threshold. Unmapping an interior pointer would tear a hole in a chunk still holding other callers' 596// live allocations, so it is a no-op here. Balanced small callers therefore no longer return memory -- 597// but they now cost ~48 bytes instead of 4096, so the arena wins by two orders of magnitude even 598// against code that was already correct. 599// Matching release for sys_mmap_try and other whole kernel mappings. 600// Never pass an arena allocation from sys_mmap: its small pointers may be interior. 601// Preserve the requested mapping length; the kernel applies its page rounding. 602const NXA_MAP_INVALID:i64=0-22 // Linux EINVAL, a protocol value rather than a resource budget. 603func sys_munmap_direct(addr:*u8,len:i64)->i64{ 604 if (addr as i64)<=0||len<=0{return NXA_MAP_INVALID} 605 return __syscall(11,addr as i64,len,0,0,0,0) 606} 607 608func sys_munmap(addr: *u8, len: i64) -> i64 { 609 if len <= NXA_SMALL_MAX { return 0 } 610 return __syscall(11, addr as i64, len, 0, 0, 0, 0) 611} 612 613// Seek within a file. whence: 0=SEEK_SET, 1=SEEK_CUR, 2=SEEK_END. 614// Returns new file offset on success, -errno on failure. 615func sys_lseek(fd: i64, offset: i64, whence: i64) -> i64 { 616 return __syscall(SYS_LSEEK, fd, offset, whence, 0, 0, 0) 617} 618 619// ---- FILESYSTEM SPACE: THE AXIS THE ESTATE DID NOT HAVE (2026-08-28) ----------------------------- 620// WHY THIS IS HERE AND NOT LEFT WHERE IT WAS. On 2026-08-28 a 100%-FULL DISK truncated a sibling seat's 621// MEMORY.md to 0 bytes -- open(path,"w") truncates before it writes, so a full volume does not refuse a 622// write, it DESTROYS the file. Nothing in the estate saw it coming: nx_resmon is "the resource axis 623// nx_health lacks" for MEMORY and SWAP, and a search for the disk primitive returned matches=0 for BOTH 624// sys_statfs and statvfs with corpus_complete=1. nx_res_census records the same absence in its own header. 625// The capability was not missing, it was DARK: nx_system_triage.tr_free_gb has read filesystem space since 626// 2026-06-10, in an _hdl_build organ that is NOT REGISTERED (nx_job_run refuses it as "not an unpinned 627// GREEN tool"), so the one instrument that could have warned was unreachable by any caller. 628// A CAPABILITY THAT EXISTS IN ONE UNREACHABLE ORGAN IS INDISTINGUISHABLE FROM ONE NOBODY BUILT. 629// 630// WHY THE RAW 137 AND NOT A SYS_ CONST. This file's dual-arch blocks are gated on TARGET_X86_64, which is 631// HARD-PINNED UNDEFINED, so the RV64 branch is what compiles and the x86 backend translates each number at 632// emit through x86ctx_rv64_to_x86_64_syscall -- whose default is `return num`. There is NO row for RV64 43 633// (statfs), so a SYS_STATFS=43 const would pass through unmapped to x86_64 43 = ACCEPT: a different 634// syscall, silently, on a path pointer. That is not a hypothesis -- nx_system_triage PROBE-PROVED it on 635// 2026-06-10: "rv64 43 returns -9 through the translation table; 137 raw matches df exactly." So 137 is 636// the MEASURED-CORRECT number for the target we actually emit, and it is named here ONCE instead of 637// sitting as a bare literal at each call site. 638// ⚠NAMED FOLLOW-UP, conflict-checked and deliberately NOT taken here: adding `if num == 43 { return 137 }` 639// to x86ctx_rv64_to_x86_64_syscall would make the arch-correct const work too. Nothing passes 43 as an x86 640// number (43 appears only as a translation TARGET, from RV64 202 accept), so the row is safe -- but it is a 641// COMPILER change that activates only on the next nx_cc self-host rebuild, and the working path needs none. 642// 643// struct statfs (x86_64) as i64 slots: 0 f_type, 1 f_bsize, 2 f_blocks, 3 f_bfree, 4 f_bavail, 5 f_files. 644// f_bavail (not f_bfree) is the honest number for "will my write succeed": it excludes the root reserve, so 645// it reports FULLER than root would see. Wrong in the safe direction, and said out loud rather than implied. 646// ⚠THE IMPRECISION, MEASURED AND NAMED SO NOBODY LATER "FIXES" IT INTO AGREEING WITH df: this permil is 647// NOT df's Use%. df computes Used/(Used+Available), which EXCLUDES the root-reserved blocks from its 648// denominator; this computes (blocks-bavail)/blocks, which counts the reserve as used. VERIFIED against df 649// on 2026-08-28: avail_bytes came back 958449582080, which is EXACTLY df's Available of 935985920 KiB, while 650// the same volume read 113 permil here and 7% there -- both correct, measuring different things. Both reach 651// their maximum at the SAME event (bavail = 0), so a threshold calibrated against THIS metric alarms at the 652// same moment a writer actually hits the wall; it simply sits higher below that. Calibrate thresholds to 653// this definition, and do not import a df-derived number as if it were the same quantity. 654const SYS_STATFS_X86_MEASURED: i64 = 137 655const STATFS_BUF_BYTES: i64 = 144 656const STATFS_I_BSIZE: i64 = 1 657const STATFS_I_BLOCKS: i64 = 2 658const STATFS_I_BAVAIL: i64 = 4 659const STATFS_PERMIL: i64 = 1000 660const STATFS_ERR: i64 = 0 - 1 661 662// raw statfs into a caller-supplied 144-byte buffer. 0 = ok, non-zero = the kernel's negative errno. 663func sys_statfs(path: *u8, buf: *i64) -> i64 { 664 return __syscall(SYS_STATFS_X86_MEASURED, path, buf, 0, 0, 0, 0) 665} 666 667// bytes available to a non-root writer on the filesystem holding `path`; STATFS_ERR if statfs failed. 668func sys_fs_avail_bytes(path: *u8) -> i64 { 669 let buf: *i64 = sys_mmap(STATFS_BUF_BYTES) as *i64 670 if sys_statfs(path, buf) != 0 { return STATFS_ERR } 671 return buf[STATFS_I_BSIZE] * buf[STATFS_I_BAVAIL] 672} 673 674// USED per-mille of the filesystem holding `path`, counted against what a non-root writer can reach: 675// (blocks - bavail) * 1000 / blocks. STATFS_ERR if statfs failed or the volume reports zero blocks -- 676// an UNMEASURABLE volume must never read as 0 permil used, which is the most flattering possible lie. 677func sys_fs_used_permil(path: *u8) -> i64 { 678 let buf: *i64 = sys_mmap(STATFS_BUF_BYTES) as *i64 679 if sys_statfs(path, buf) != 0 { return STATFS_ERR } 680 let blocks: i64 = buf[STATFS_I_BLOCKS] 681 if blocks <= 0 { return STATFS_ERR } 682 let avail: i64 = buf[STATFS_I_BAVAIL] 683 return ((blocks - avail) * STATFS_PERMIL) / blocks 684} 685 686func sys_exit(code: i64) -> i64 { 687 return __syscall(SYS_EXIT, code, 0, 0, 0, 0, 0) 688} 689 690// mmap anonymous R/W memory; returns raw bytes. Fixed flags: 691// PROT_READ|PROT_WRITE = 3, MAP_PRIVATE|MAP_ANONYMOUS = 0x22, fd=-1. 692// FAIL-CLOSED ON A REFUSED MAPPING (2026-08-07). MEASURED: the corpus has 90,817 sys_mmap call sites 693// and SIX of them check the result -- all six in test probes whose response is sys_exit anyway. So 694// 90,811 sites take whatever this returns and write through it. When the kernel refuses, that value is 695// -errno, and the write lands at 0xfffffffffffffff4 (-12, ENOMEM). That is not a hypothetical: dmesg 696// on this host recorded it hourly in nx_web_shard_compact, and 18 times in nx_web_crawl_step. 697// Returning a poisoned pointer to 90,811 unguarded callers is the defect. Dying here is strictly safer 698// than dying there: the process ends either way, but this way there is no memory corruption first and 699// the failure is NAMED instead of arriving as a bare segfault address an operator has to decode. 700// This is the never-brick shape -- fail-safe BY CONSTRUCTION, not by every caller remembering. 701// KNOWN COST, stated: nx_mmap_probe / test_munmap deliberately provoke a refusal to observe it. They 702// now exit here with code 12 rather than printing their own verdict. Six probes lose a diagnostic; 703// 90,811 sites stop corrupting memory. 704// ===== TEMPORARY DIAGNOSTIC -- ARENA OVERRUN CANARY (2026-08-07) ===================================== 705// ⛔DO NOT BLESS A COMPILER BUILT WITH THIS. The canary writes 0xC7 into the NXA_GAP slack that a 706// caller could otherwise legitimately read as zeros, so it changes observable behaviour for any code 707// that reads past its declared size -- which is precisely the code being hunted. 708// PURPOSE: at NXA_SMALL_MAX=256 the compiler produces 14 SPURIOUS type diagnostics (it reports 709// `arg 2 is an INTEGER but the parameter is a POINTER` against a parameter DECLARED `j: *u8`), i.e. 710// something writes past its allocation and corrupts the parser's type table. At threshold 64 the same 711// requests each get a 4096-byte page whose slack absorbs it. Reading the source found nothing: the 712// two obvious suspects (nx_ir.nx:70 sys_mmap(104), nx_parse.nx:868 sys_mmap(256)) are both correctly 713// sized and bounded. So stop reading and MEASURE: stamp each small allocation's gap, verify the 714// PREVIOUS one on the next call, and print the size of whichever allocation was overrun. 715// Writes to fd 2 without allocating -- it borrows scratch inside the arena state page, because a 716// reporter that called sys_mmap would recurse into the thing it is instrumenting. 717// Dump n bytes at src to fd 2, unprintables as '.', using scratch at state+256 (the ring starts at 718// state+512 and the decimal scratch sits at +64/+128, so this cannot collide with either). n is 719// capped by callers at 48 so the buffer stays clear of the ring. 720func nxa_dump_printable(src: i64, n: i64) -> i64 { 721 let o: *u8 = ((nxa_st as i64) + 256) as *u8 722 var i: i64 = 0 723 while i < n { 724 let sp: *u8 = (src + i) as *u8 725 var c: i64 = sp[0] as i64 726 if c < 32 { c = 46 } 727 if c > 126 { c = 46 } 728 o[i] = c as u8 729 i = i + 1 730 } 731 o[n] = 10 as u8 732 sys_write(2, o, n + 1) 733 return 0 734} 735 736// FINGERPRINT (2026-08-12): the size alone + all-zeros byte dump never named the site. The ring already 737// records each allocation's REQUESTED size in counter order, so the recent size SEQUENCE fingerprints the 738// code path that was running when the overrun landed (a distinctive run of sizes is near-unique to a 739// function). Writes to fd 2 borrowing state-page scratch at bytes 320/340 (clear of the ring at byte 512, 740// the reporter decimals at 64/128, and the byte-dump at 256). No allocation -- must not recurse into sys_mmap. 741func nxa_dump_sizes() -> i64 { 742 sys_write(2, " ring_sizes(old->recent): " as *u8, 27) 743 let scr: *u8 = ((nxa_st as i64) + 320) as *u8 744 let out2: *u8 = ((nxa_st as i64) + 340) as *u8 745 let cnt: i64 = nxa_st[2] 746 var start: i64 = cnt - 32 747 if start < 0 { start = 0 } 748 var idx: i64 = start 749 while idx < cnt { 750 let slot: i64 = idx % NXA_RING 751 let szv: i64 = nxa_st[NXA_RBASE + slot * 2 + 1] 752 var m: i64 = szv 753 var k: i64 = 0 754 if m == 0 { scr[0] = 48 as u8; k = 1 } 755 while m > 0 { scr[k] = (48 + (m % 10)) as u8; m = m / 10; k = k + 1 } 756 var j: i64 = 0 757 while j < k { out2[j] = scr[k - 1 - j]; j = j + 1 } 758 out2[k] = 44 as u8 759 sys_write(2, out2, k + 1) 760 idx = idx + 1 761 } 762 sys_write(2, "\n" as *u8, 1) 763 return 0 764} 765 766func nxa_report_overrun(sz: i64, gs: i64) -> i64 { 767 let msg: *u8 = "ARENA-OVERRUN prev_alloc_size=" as *u8 768 var n: i64 = 0 769 while msg[n] != (0 as u8) { n = n + 1 } 770 sys_write(2, msg, n) 771 let b: *u8 = ((nxa_st as i64) + 64) as *u8 772 let o: *u8 = ((nxa_st as i64) + 128) as *u8 773 var m: i64 = sz 774 var k: i64 = 0 775 if m == 0 { b[0] = 48 as u8; k = 1 } 776 while m > 0 { b[k] = (48 + (m % 10)) as u8; m = m / 10; k = k + 1 } 777 var i: i64 = 0 778 while i < k { o[i] = b[k - 1 - i]; i = i + 1 } 779 o[k] = 10 as u8 780 sys_write(2, o, k + 1) 781 // The SIZE alone did not name the site (four 80-byte victims, and the two unbounded 80-byte 782 // buffers in nx_parse.nx were sized from their inputs with no effect). So show the DATA: the 783 // victim's own bytes identify the buffer, and the bytes written past its end identify the WRITER. 784 let algn: i64 = (sz + NXA_ALIGN - 1) / NXA_ALIGN * NXA_ALIGN 785 let base: i64 = gs - algn 786 var dn: i64 = sz 787 if dn > 48 { dn = 48 } 788 sys_write(2, " own : " as *u8, 8) 789 nxa_dump_printable(base, dn) 790 sys_write(2, " over: " as *u8, 8) 791 nxa_dump_printable(gs, 16) 792 nxa_dump_sizes() 793 return 0 794} 795 796func nxa_die(msg: *u8) -> i64 { 797 var n: i64 = 0 798 while msg[n] != (0 as u8) { n = n + 1 } 799 sys_write(2, msg, n) 800 sys_exit(12) 801 return 0 802} 803 804// Address of the arena lock word. Valid only once nxa_st exists; every caller below has already 805// ensured that, and the state-page creation itself is discussed at the take site. 806func nxa_lock_addr() -> *i64 { 807 return ((nxa_st as i64) + NXA_LOCK * 8) as *i64 808} 809 810// __atomic_cas_i64 returns 1 when it wrote and 0 when it did not, so the spin condition is == 0. 811// It is a COMPILER INTRINSIC, not a call into nx_atom -- that module imports THIS file, so importing 812// it back would be a cycle. Verified in nx_x86_64_ctx rather than assumed: it lowers to a genuine 813// `lock cmpxchgq` followed by sete, which is a full barrier on x86-64 whatever ordering is passed. 814func nxa_lock_take() -> i64 { 815 var spins: i64 = 0 816 while __atomic_cas_i64(nxa_lock_addr(), 0, 1, NX_MO_ACQUIRE) == 0 { 817 spins = spins + 1 818 // Fires EXACTLY ONCE, on equality rather than on exceeding, so a genuinely long wait reports 819 // itself without turning the allocator into a log generator. 820 if spins == NXA_LOCK_WARN { 821 // ONCE PER PROCESS, not once per acquisition. MEASURED 2026-08-25 and this is a 822 // correction to the first cut of this very function: it fired on equality per CALL, and 823 // eight workers contending LEGITIMATELY produced hundreds of identical lines in a single 824 // gate run. A DIAGNOSTIC THAT FIRES CONSTANTLY IS ONE EVERY READER LEARNS TO IGNORE, and 825 // this one writes to the stderr of every organ in the estate. 826 // The threshold was derived from the longest the critical section can run, which bounds 827 // ONE hold and says nothing about QUEUE DEPTH: with N threads waiting, a legitimate wait 828 // is N holds and can exceed any per-section derivation. So this is a NOISE FLOOR for a 829 // hint, never a correctness bound -- it never fails, never delays, and never repeats. 830 // The flag is set through a CAS so the once-ness cannot itself race. 831 let wflag: *i64 = ((nxa_st as i64) + NXA_LOCK_WARNED * 8) as *i64 832 if __atomic_cas_i64(wflag, 0, 1, NX_MO_ACQ_REL) == 1 { 833 let m: *u8 = "ARENA-LOCK: sustained allocator contention seen (reported once per process; a hint, not an error -- allocation proceeds normally).\n" as *u8 834 var mn: i64 = 0 835 while m[mn] != (0 as u8) { mn = mn + 1 } 836 sys_write(2, m, mn) 837 } 838 } 839 } 840 return 0 841} 842 843func nxa_lock_give() -> i64 { 844 // nx_cc refuses a bare intrinsic statement ("computes a value and never uses it") and an atomic 845 // store has no result worth using, so it is bound and discarded -- the same shape nx_atom uses 846 // for exactly this reason. The contract is unchanged: this returns 0 either way. 847 let discarded: i64 = __atomic_store_i64(nxa_lock_addr(), 0, NX_MO_RELEASE) 848 if discarded != 0 { return 0 } 849 return 0 850} 851 852// Optional mapping for request boundaries that must report allocation refusal. 853// Unlike sys_mmap, this never aborts the process and never consumes arena storage. 854// Release successful mappings with sys_munmap_direct, not the arena-aware sys_munmap. 855// A successful reservation can still fail on later physical-memory pressure; callers 856// must not describe virtual address admission as guaranteed resident RAM. 857func sys_mmap_try(size:i64)->*u8 { 858 if size<=0 { return 0 as *u8 } 859 let mapped:i64=__syscall(SYS_MMAP,0,size,3,0x22,-1,0) 860 if mapped<=0 { return 0 as *u8 } 861 return mapped as *u8 862} 863 864func sys_mmap(size: i64) -> *u8 { 865 // Large requests keep the EXACT original behaviour, byte for byte: page-aligned, own VMA. Any 866 // caller that depends on page alignment is allocating at least a page, so the arena cannot reach 867 // it. Every failure path below also falls back to this same call, so an exhausted arena degrades 868 // to the old allocator rather than returning a bad pointer. 869 if size > NXA_SMALL_MAX { 870 let big: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x22, -1, 0) 871 if big <= 0 { nxa_die("FATAL sys_mmap: kernel refused a large mapping (ENOMEM). Refusing to return a poisoned pointer -- a write through it would corrupt memory.\n" as *u8) } 872 return big as *u8 873 } 874 if (nxa_st as i64) == 0 { 875 let s: i64 = __syscall(SYS_MMAP, 0, NXA_STATE, 3, 0x22, -1, 0) 876 if s <= 0 { 877 // arena state page refused -- degrade to the plain allocator, and only die if THAT fails too 878 let f1: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x22, -1, 0) 879 if f1 <= 0 { nxa_die("FATAL sys_mmap: kernel refused the arena state page AND the fallback mapping (ENOMEM).\n" as *u8) } 880 return f1 as *u8 881 } 882 nxa_st = s as *i64 883 } 884 // EVERYTHING FROM HERE TO THE RETURN TOUCHES SHARED STATE: the cursor, the limit, the chunk 885 // table, the canary ring and the ring counter. It is ONE critical section because the refill 886 // decision and the bump that depends on it cannot be separated without reintroducing the race. 887 // The state page itself is created ABOVE this point, unlocked: two threads arriving there 888 // together would each map a page and one would win the static, leaking the other's 4 KiB but 889 // corrupting nothing, and in practice the arena is warm long before any thread is spawned 890 // because spawning one allocates. That residual is NAMED here rather than papered over. 891 nxa_lock_take() 892 var need: i64 = size 893 if need <= 0 { need = 1 } 894 need = (need + NXA_ALIGN - 1) / NXA_ALIGN * NXA_ALIGN + NXA_GAP 895 if nxa_st[0] + need > nxa_st[1] { 896 let c: i64 = __syscall(SYS_MMAP, 0, NXA_CHUNK, 3, 0x22, -1, 0) 897 if c <= 0 { 898 // chunk refused -- degrade to the plain allocator, and only die if THAT fails too. 899 // RELEASE FIRST: this is the one path that leaves the critical section early, and a lock 900 // held across a degraded return would wedge every other allocator in the process. 901 nxa_lock_give() 902 let f2: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x22, -1, 0) 903 if f2 <= 0 { nxa_die("FATAL sys_mmap: kernel refused an arena chunk AND the fallback mapping (ENOMEM).\n" as *u8) } 904 return f2 as *u8 905 } 906 nxa_st[0] = c 907 nxa_st[1] = c + NXA_CHUNK 908 // track the chunk base so arena_reset can munmap post-mark chunks (additive; guarded at cap). 909 if nxa_st[3] < NXA_CHUNKMAX { nxa_st[NXA_CHUNKBASE + nxa_st[3]] = c; nxa_st[3] = nxa_st[3] + 1 } 910 } 911 // ---- RING CANARY (temporary diagnostic) ---- 912 var rk: i64 = 0 913 while rk < NXA_RING { 914 let gs0: i64 = nxa_st[NXA_RBASE + rk * 2] 915 if gs0 != 0 { 916 var bi: i64 = 0 917 var bad: i64 = 0 918 while bi < 8 { 919 let bp: *u8 = (gs0 + bi) as *u8 920 if bp[0] != (199 as u8) { bad = 1; bi = 8 } else { bi = bi + 1 } 921 } 922 if bad == 1 { 923 nxa_report_overrun(nxa_st[NXA_RBASE + rk * 2 + 1], gs0) 924 nxa_st[NXA_RBASE + rk * 2] = 0 925 } 926 } 927 rk = rk + 1 928 } 929 let p: i64 = nxa_st[0] 930 nxa_st[0] = p + need 931 let gs: i64 = p + need - NXA_GAP 932 var gj: i64 = 0 933 while gj < NXA_GAP { let q: *u8 = (gs + gj) as *u8; q[0] = 199 as u8; gj = gj + 1 } 934 let slot: i64 = nxa_st[2] % NXA_RING 935 nxa_st[NXA_RBASE + slot * 2] = gs 936 nxa_st[NXA_RBASE + slot * 2 + 1] = size 937 nxa_st[2] = nxa_st[2] + 1 938 // The ONLY other exit from the critical section is the degraded chunk-refill path above, which 939 // releases before it returns. Every shared write is now behind this pair. 940 nxa_lock_give() 941 return p as *u8 942} 943 944// arena_mark: force the arena warm (so a first chunk + state page exist), then record the current 945// position as the reset barrier. Returns 1. A daemon calls this ONCE after startup, before its loop. 946func sys_arena_mark() -> i64 { 947 let warm: *u8 = sys_mmap(1) // ensures nxa_st + chunk[0] exist; the 1 byte is itself arena scratch 948 if (warm as i64) == 0 { return 0 } 949 nxa_st[4] = 1 950 nxa_st[5] = nxa_st[0] 951 nxa_st[6] = nxa_st[1] 952 nxa_st[7] = nxa_st[3] 953 return 1 954} 955 956// arena_reset: reclaim everything allocated since the mark. munmap post-mark chunks, restore the bump 957// to the mark, ZERO the marked chunk's reclaimed tail (preserves the mmap-returns-zeroed contract for 958// recycled bytes), and CLEAR the ring canary (its stamps may point into a just-munmap'd chunk, and a 959// stale deref on the next alloc would SEGV). Returns 1 on reset, 0 if no mark was set. 960func sys_arena_reset() -> i64 { 961 if (nxa_st as i64) == 0 { return 0 } 962 if nxa_st[4] != 1 { return 0 } 963 var i: i64 = nxa_st[7] 964 while i < nxa_st[3] { 965 let cb: i64 = nxa_st[NXA_CHUNKBASE + i] 966 if cb != 0 { __syscall(11, cb, NXA_CHUNK, 0, 0, 0, 0); nxa_st[NXA_CHUNKBASE + i] = 0 } 967 i = i + 1 968 } 969 nxa_st[3] = nxa_st[7] 970 nxa_st[0] = nxa_st[5] 971 nxa_st[1] = nxa_st[6] 972 var z: i64 = nxa_st[0] 973 while z < nxa_st[1] { let q: *u8 = z as *u8; q[0] = 0 as u8; z = z + 1 } 974 var r: i64 = 0 975 while r < NXA_RING * 2 { nxa_st[NXA_RBASE + r] = 0; r = r + 1 } 976 nxa_st[2] = 0 977 return 1 978} 979 980// mmap anonymous SHARED R/W memory -- ONE region that survives fork() so all 981// children see each other's writes (MAP_SHARED|MAP_ANONYMOUS = 0x21). Allocate 982// in the PARENT before fork. Foundation for the fork-per-connection video relay 983// (peers in separate children share the per-room frame table). 984func sys_mmap_shared(size: i64) -> *u8 { 985 let r: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x21, -1, 0) 986 return r as *u8 987} 988 989// madvise(2) -- prefetch/advice hints for mapped ranges. MADV_WILLNEED=3 batches page-ins so a 990// serial fault loop over a cold file-backed mmap becomes parallel disk readahead (the dp-web-pub 991// stage-2 p95 fix, 2026-08-12). RAW x86_64 NUMBER 28 ON PURPOSE (sys_exit_group's raw-231 pattern): 992// the portable rv64/asm-generic number is 233 and x86ctx_rv64_to_x86_64_syscall has no 233 row in 993// the DEPLOYED compiler, so a portable const would emit x86_64 233 = epoll_ctl (the wrong-syscall- 994// not-an-error class; see the setpgid/flock rows). The 233->28 row is staged in nx_x86_64_ctx.nx and 995// activates on the next nx_cc self-host rebuild; flip this to the portable const AFTER that lands. 996// Signature bite-proven by nx_madvise_probe (0 / -12 ENOMEM / -22 EINVAL). Advisory contract: callers 997// may ignore the return value -- a failed hint costs nothing but the cold-read behaviour it hints away. 998func sys_madvise(addr: *u8, len: i64, advice: i64) -> i64 { 999 return __syscall(28, addr, len, advice, 0, 0, 0) 1000} 1001 1002// openat flavors used by the compiler driver. AT_FDCWD = -100 (declared ABOVE, next to its first 1003// reader -- see the miscompile note there; do NOT move it back down). 1004// O_RDONLY = 0; O_CREAT|O_WRONLY|O_TRUNC = 0x241 on Linux RV64. 1005const O_RDONLY: i64 = 0 1006const O_WRONLY_CT: i64 = 0x241 // O_CREAT | O_WRONLY | O_TRUNC 1007const O_WRONLY_CA: i64 = 0x441 // O_CREAT | O_WRONLY | O_APPEND 1008 1009func sys_openat_rd(path: *u8) -> i64 { 1010 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_RDONLY, 0, 0, 0) 1011} 1012 1013// O_RDWR|O_CREAT (NO truncate) -- for offset-addressed persistent files like the metrics ring TSDB 1014// (create if missing, then lseek+read/write records in place, never truncating existing history). 1015const O_RDWR_CREATE: i64 = 0x42 1016func sys_openat_rdwr(path: *u8, mode: i64) -> i64 { 1017 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_RDWR_CREATE, mode, 0, 0) 1018} 1019 1020// ★★★THE FILE MODE IS THE HALF OF THIS INTERFACE THAT WAS NEVER NAMED. The O_ flags above are named 1021// consts in hex WITH a decoding comment; the mode passed beside them is a bare literal at every call 1022// site. MEASURED 2026-08-14 (coverage_complete=1 corpus_complete=1 over 23,053 files): 1023// - 29 organs passed the mode as a bare DECIMAL literal, which no reader decodes as rw-r--r-- 1024// without stopping to convert it. ⚠THE FIRST COUNT PUBLISHED HERE WAS 26: the scan was scoped to 1025// runtime/_hdl_build/ and the SUBDIRECTORY's count was published as the estate figure -- three 1026// more (nx_forge_rag, nx_gpu_export, nx_bvhfk) sat one level up in runtime/. 1027// ★A COUNT INHERITS THE SCOPE OF ITS SCAN, AND THE SCOPE IS THE PART NOBODY PRINTS BESIDE IT. 1028// ⚠The offending call is deliberately NOT spelled out literally in this comment: prose is source 1029// bytes, so writing the pattern here would make every future grep for it match this note; 1030// - 10 MORE each define their OWN private 0644 const (IP_ VR_ VP_ LIVE_ FD_ FP_ WL_ PUB_ REG_ HFF_), 1031// nine written 0x1a4 and one written 420 -- THE SAME CONSTANT IN TWO DIFFERENT BASES. 1032// Ten seats each solved this privately and none put the answer where the next one would look. That is 1033// the duplicate-ruler defect precisely: changing the estate's default artifact mode today means finding 1034// 39 sites in two notations and hoping none was missed. One name, in the shim every organ already 1035// imports, is the entire fix -- and it belongs HERE, beside the flags, not in a 40th private copy. 1036const MODE_0644: i64 = 0x1a4 // rw-r--r-- : default mode for a generated artifact 1037// rwxr-xr-x : default mode for a created DIRECTORY. A directory without the execute bit cannot be 1038// traversed, so MODE_0644 is not merely stricter here -- it is wrong, and the failure surfaces later 1039// as an unopenable path rather than as a refused mkdir. Named beside its sibling so the choice is a 1040// lookup rather than a recollection; the estate otherwise spells this as a raw 0x1ed at every site. 1041const MODE_0755: i64 = 0x1ed 1042// Seconds of ZERO PROGRESS on one socket operation before an accepted connection is abandoned. 1043// A single-threaded accept-loop daemon that loop-reads to Content-Length can be starved FOREVER by one 1044// peer that declares a body it never finishes sending -- a one-request DoS, hostile OR merely buggy. 1045// nx_dos_timeout_scan supervises the class and named 16 daemons carrying no timeout at all; the cure is 1046// sys_set_socket_timeout(cfd, ACCEPT_TMO_S) folded in right after accept. 1047// WHY 30 AND NOT THE 5 THE LOGIN DAEMONS USE: this bound must be wrong in the direction of SERVING, not 1048// of dropping. The attack is an UNBOUNDED wait, so ANY finite bound closes it; a short one additionally 1049// risks aborting a legitimate slow client. 30s of zero progress on a single recv/send is pathological 1050// for every daemon in the class -- including the streaming ones, where data is flowing and the timer 1051// never approaches its bound -- while still converting an infinite starvation into a bounded one. 1052// It is the calibration nx_galx_bridge already uses for an accepted cfd; named here rather than copied 1053// into a 16th private literal, exactly as MODE_0644 above. 1054const ACCEPT_TMO_S: i64 = 30 1055func sys_openat_wr(path: *u8, mode: i64) -> i64 { 1056 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CT, mode, 0, 0) 1057} 1058 1059// Linux O_WRONLY | O_CREAT | O_EXCL. An existing final component, including 1060// a symlink, is a conflict; callers acquire ownership only on success. 1061const O_WRONLY_CREATE_EXCLUSIVE: i64 = 0x1 | 0x40 | 0x80 1062func sys_openat_exclusive(path: *u8, mode: i64) -> i64 { 1063 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CREATE_EXCLUSIVE, mode, 0, 0) 1064} 1065 1066// Linux O_DIRECTORY: require a directory, rather than merely an openable node. 1067const O_DIRECTORY: i64 = 0x10000 1068func sys_openat_directory(path: *u8) -> i64 { 1069 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_RDONLY | O_DIRECTORY, 0, 0, 0) 1070} 1071 1072// Open path for append (create if missing). Used by append-only 1073// journals such as .race_telemetry.tsv. RV64 syscall numbers; the 1074// x86_64 mirror lives in nx_syscalls_x86_64.nx. 1075func sys_openat_append(path: *u8, mode: i64) -> i64 { 1076 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CA, mode, 0, 0) 1077} 1078 1079// Linux open ABI flags: acquire close-on-exec atomically and refuse a final 1080// symlink. Nonblocking also prevents an unexpected FIFO from stalling admission. 1081const O_CLOEXEC: i64 = 0x80000 1082const O_NOFOLLOW: i64 = 0x20000 1083const O_NONBLOCK: i64 = 0x800 1084const MODE_0600: i64 = 0x180 1085func sys_openat_lock(path: *u8) -> i64 { 1086 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CA | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, MODE_0600, 0, 0) 1087} 1088 1089// symlinkat(target, AT_FDCWD, linkpath) -- raw x86_64 266 forced RUNTIME (the chdir escape, same as 1090// readlinkat below). THE atomic-repoint primitive for release management: create releases/current.new -> 1091// sys_renameat over releases/current = an atomic symlink swap (golive/rollback are instant + crash-safe). 1092// 0 on success, -errno (notably -EEXIST=-17 if linkpath exists -- create the .new name, then rename). 1093func sys_symlinkat(target: *u8, linkpath: *u8) -> i64 { 1094 let nbox: *i64 = sys_mmap(16) as *i64 1095 nbox[0] = 266 1096 let r: i64 = __syscall(nbox[0], target as i64, AT_FDCWD, linkpath as i64, 0, 0, 0) 1097 sys_munmap(nbox as *u8, 16) 1098 return r 1099} 1100 1101// readlinkat(AT_FDCWD, path, buf, cap) -- raw x86_64 267 forced RUNTIME (the chdir escape: keep the 1102// number out of the rv64->x86 constant-translate path). Returns link length (NO NUL appended), -errno 1103// on fail. nbox is munmap'd before return: the daemon supervisor calls this hundreds of times PER CYCLE 1104// (exe-identity sweeps), and a leaked page per call is exactly the VSZ-balloon class that broke fork. 1105func sys_readlinkat(path: *u8, buf: *u8, cap: i64) -> i64 { 1106 let nbox: *i64 = sys_mmap(16) as *i64 1107 nbox[0] = 267 1108 let r: i64 = __syscall(nbox[0], AT_FDCWD, path as i64, buf as i64, cap, 0, 0) 1109 sys_munmap(nbox as *u8, 16) 1110 return r 1111} 1112 1113// Atomically replace newpath with oldpath (rename(2) on one filesystem: a concurrent reader sees the 1114// whole old file or the whole new file, never a torn read). The S-class content-publish primitive: 1115// write the new page to a temp file, then sys_renameat(tmp, live) -> hot-swap, NO rm+ln race. 1116// renameat2: rv64=276, x86_64=316, flags=0. The known-good compiler translates most rv64 syscall 1117// numbers to the x86_64 target but its table MISSES 276 -- verified 2026-06-14 via nx_rename_probe: 1118// raw 276 -> -EINVAL (lands on x86_64 `tee`), raw 316 -> renames OK. That silently broke every 1119// cst_write_atomic publish (page.html.new written, never swapped in). Try the x86_64 number first 1120// (works on every x86_64 build incl. known-good); fall back to the rv64 number for native-rv64 or 1121// translating compilers that do map it. flags=0 so renameat2 == renameat semantics. 1122func sys_renameat(oldpath: *u8, newpath: *u8) -> i64 { 1123 let r: i64 = __syscall(316, AT_FDCWD, oldpath, AT_FDCWD, newpath, 0, 0) 1124 if r == 0 { return 0 } 1125 return __syscall(276, AT_FDCWD, oldpath, AT_FDCWD, newpath, 0, 0) 1126} 1127 1128// fsync(2): flush file (or directory) data+metadata to stable storage. 1129// PROBE-PROVEN 2026-06-10 (_fsync_probe): rv64 82 is NOT in the compiler's 1130// translation table (lands on x86 rename -> -EFAULT both ways); direct 1131// x86_64 74 passes through raw (the unlinkat-263 precedent) and behaves as 1132// fsync (0 on a valid fd, -9 EBADF on a bad one). Storage commit points 1133// fsync the data files AND their directory around rename(2) so a committed 1134// segment survives power loss, not just process death. 1135func sys_fsync(fd: i64) -> i64 { 1136 return __syscall(74, fd, 0, 0, 0, 0, 0) 1137} 1138 1139// flock(2): BSD-style whole-file ADVISORY lock. rv64 32 -> x86_64 73 via the compiler's 1140// x86ctx_rv64_to_x86_64_syscall table (nx_x86_64_ctx.nx:961, PROVEN LIVE in flock_deploy.log). 1141// op: SYS_LOCK_SH=1 / SYS_LOCK_EX=2 / SYS_LOCK_NB=4 (OR) / SYS_LOCK_UN=8. Returns 0 on success, 1142// -errno on failure. Used by the framed-append durability floor to serialize the write-until- 1143// complete loop so a partial/short write under contention can NEVER misalign a concurrent appender 1144// (O_APPEND single-write atomicity is necessary but not sufficient on every fs -- the lock makes 1145// the whole framed record write atomic against other lockers). Additive: no existing caller in 1146// this file changes. NOTE: nx_flock.nx is a separate organ importing the LEGACY "syscalls.nx" 1147// name; this wrapper lives HERE so organs already on nx_syscalls.nx (e.g. nx_framed_append) get 1148// flock without a second import (double-import rc=6 trap). 1149const SYS_LOCK_SH: i64 = 1 1150const SYS_LOCK_EX: i64 = 2 1151const SYS_LOCK_NB: i64 = 4 1152const SYS_LOCK_UN: i64 = 8 1153func sys_flock(fd: i64, op: i64) -> i64 { 1154 return __syscall(32, fd, op, 0, 0, 0, 0) 1155} 1156 1157// newfstatat(2): stat `path` into a 144-byte x86-64 struct stat at `statbuf`. x86_64 nr 262 is passed 1158// DIRECTLY (the unlinkat-263 / fsync-74 precedent: stat-family rv64 numbers aren't in the compiler's 1159// translation table, so a raw x86_64 number passes through untranslated). Returns 0 on success, <0 1160// (e.g. -2 ENOENT) on error. st_mtim.tv_sec @ offset 88, st_mtim.tv_nsec @ 96 (the freshness channel). 1161func sys_fstatat(path: *u8, statbuf: *u8) -> i64 { 1162 return __syscall(262, AT_FDCWD, path, statbuf, 0, 0, 0) 1163} 1164 1165// utimensat(2): set `path` atime+mtime from `times` (a struct timespec[2] = [atime.sec,atime.nsec, 1166// mtime.sec,mtime.nsec]). x86_64 nr 280 passed DIRECTLY. A sovereign `touch`; also makes freshness 1167// tests deterministic. Returns 0 on success, <0 on error. 1168func sys_utimensat(path: *u8, times: *i64) -> i64 { 1169 return __syscall(280, AT_FDCWD, path, times as i64, 0, 0, 0) 1170} 1171 1172// ---- sovereign host control-plane syscalls (x86_64; single unconditional consts, 1173// per the known-good-compiler @ifdef finding). The Nishi supervisor uses these to 1174// manage the daemon lifecycle WITHOUT any shell (no pkill / mkdir / chmod glue). ---- 1175 1176// COMPILER NOTE: the known-good compiler BAKES whole function bodies by NAME for some syscalls 1177// (proven via emitted .s: a function literally named sys_kill emits number 8, sys_chmod emits 155 1178// -- both wrong, regardless of the const referenced). So these wrappers use NON-baked names 1179// (nx_kill / nx_chmod). sys_mkdir / sys_renameat are not baked, so those keep the sys_ name. 1180 1181// DESIGN: __syscall takes the RV64/generic number; the compiler's x86ctx_rv64_to_x86_64_syscall table 1182// (nx_x86_64_ctx.nx) translates it to the build target. So pass the RV64 number. These four were added 1183// to that sovereign table 2026-06-06 (kill 129->62, mkdirat 34->258, fchmodat 53->268, renameat2 1184// 276->316); x86 kill(62) had collided with rv64 lseek(62), x86 fchmodat(268) with rv64 pivot_root(268). 1185 1186// kill(pid, sig) -- rv64 129 -> x86_64 62. SIGTERM=15 / SIGKILL=9. Host control plane. 1187func nx_kill(pid: i64, sig: i64) -> i64 { return __syscall(129, pid, sig, 0, 0, 0, 0) } 1188 1189// setpgid(pid, pgid) -- put a process in its own PROCESS GROUP so a killer can reach its whole 1190// subtree. nx_kill(0 - pgid, sig) signals every member, not just the one process you forked. 1191// A BOUND THAT ONLY REACHES THE PROCESS YOU FORKED IS NOT A BOUND ON THE WORK IT STARTED. 1192// Per-target const, NOT a bare generic number: x86ctx_rv64_to_x86_64_syscall translates only the 1193// numbers it knows and FALLS THROUGH for the rest. MEASURED on the laptop lane 2026-08-10: a bare 1194// generic 154 reached x86_64 as 154 and returned -38 (ENOSYS), silently -- and a fix built on it 1195// reproduced the original bug exactly. Callers must treat setpgid as BEST-EFFORT. 1196@ifdef TARGET_X86_64 1197const SYS_SETPGID: i64 = 109 1198@endif 1199@ifndef TARGET_X86_64 1200const SYS_SETPGID: i64 = 154 1201@endif 1202func sys_setpgid(pid: i64, pgid: i64) -> i64 { return __syscall(SYS_SETPGID, pid, pgid, 0, 0, 0, 0) } 1203 1204// prlimit64(pid, resource, new_limit, old_limit) -- the Linux RESOURCE-LIMIT primitive = 1205// the Job-Object ActiveProcessLimit / memory-limit analog for the sovereign supervisor (M5). 1206// x86_64 prlimit64 = 302 (PASSED DIRECTLY, the unlinkat-263 / fsync-74 / fstatat-262 1207// precedent: a raw x86_64 number not in the compiler's rv64->x86 swap table passes through 1208// untranslated). NOTE: rv64 prlimit64 IS 261 but x86_64 261 = futimesat -- so the naive 1209// "261 is the same on both" is WRONG (PROBE-PROVEN: 261 returned EFAULT/EINVAL because it 1210// hit futimesat); the build target here is x86_64, so we emit 302 directly. pid=0 => the 1211// calling process (a forked child caps ITSELF before running its payload). new_limit / 1212// old_limit each point at a struct rlimit64 { rlim_cur: i64, rlim_max: i64 } (16 bytes); 1213// pass 0 for old_limit to skip read-back. Returns 0 on success, -errno (e.g. -1 EPERM if 1214// raising a hard limit unprivileged) on failure. NON-baked name (the compiler bakes some 1215// sys_* bodies by name; the nx_ prefix avoids that trap). 1216func nx_prlimit(pid: i64, resource: i64, new_limit: *u8, old_limit: *u8) -> i64 { 1217 return __syscall(302, pid, resource, new_limit as i64, old_limit as i64, 0, 0) 1218} 1219 1220// RLIMIT resource ids (Linux generic; identical rv64/x86_64). RLIMIT_AS = address-space 1221// (virtual memory) cap -- the cleanest userspace-settable "memory budget" for a supervised 1222// job. RLIMIT_CPU = CPU-seconds cap. WNOHANG=1 = wait4 non-blocking liveness poll option. 1223const RLIMIT_CPU: i64 = 0 1224const RLIMIT_AS: i64 = 9 1225const WNOHANG: i64 = 1 1226 1227// mkdirat -- rv64 34 -> x86_64 258. Create a doc-root directory. mode e.g. 0x1ed (0755). 1228func sys_mkdir(path: *u8, mode: i64) -> i64 { return __syscall(34, AT_FDCWD, path, mode, 0, 0, 0) } 1229 1230// fchmodat -- rv64 53 -> x86_64 268. +x a freshly-deployed daemon binary (mode 0x1ed). flags=0. 1231func nx_chmod(path: *u8, mode: i64) -> i64 { return __syscall(53, AT_FDCWD, path, mode, 0, 0, 0) } 1232 1233// setsid -- x86_64 = 112 (not in the rv64->x86 table, so the literal passes through). Detach a forked 1234// process into a NEW session so it survives the SSH/parent close -- sovereign daemonization (no shell setsid). 1235func nx_setsid() -> i64 { return __syscall(112, 0, 0, 0, 0, 0, 0) } 1236 1237// CLOCK_MONOTONIC = 1. ts is 16 bytes {sec: i64, nsec: i64}. 1238// Returns 0 / -errno. 1239func sys_clock_gettime_mono(ts: *i64) -> i64 { 1240 return __syscall(SYS_CLOCK_GETTIME, 1, ts, 0, 0, 0, 0) 1241} 1242 1243// CLOCK_REALTIME = 0 -- wall-clock seconds since the Unix epoch. Use 1244// this (NOT monotonic) for anything that must match calendar time: 1245// X.509 notBefore/notAfter, logs, TLS timestamps. Monotonic returns 1246// time-since-boot, which encodes as ~1970 when (mis)used as an epoch. 1247func sys_clock_gettime_real(ts: *i64) -> i64 { 1248 return __syscall(SYS_CLOCK_GETTIME, 0, ts, 0, 0, 0, 0) 1249} 1250 1251// Wall-clock seconds since the Unix epoch. 1252func sys_now_realtime_sec() -> i64 { 1253 let ts: *i64 = sys_mmap(16) as *i64 1254 sys_clock_gettime_real(ts) 1255 return ts[0] 1256} 1257 1258// Wall-clock milliseconds since the Unix epoch. 1259func sys_now_realtime_ms() -> i64 { 1260 let ts: *i64 = sys_mmap(16) as *i64 1261 sys_clock_gettime_real(ts) 1262 return ts[0] * 1000 + ts[1] / SYS_MAGIC_1000000 1263} 1264 1265// Wall-clock MICROSECONDS since the Unix epoch -- the CROSS-MACHINE stamp. 1266// ★ Use this, never sys_now_us(), for any value one machine writes and ANOTHER machine judges 1267// (fleet beats, lease expiry, telemetry rows). Monotonic counts from each machine's OWN boot, so 1268// subtracting one node's monotonic stamp from another's monotonic now yields the difference of two 1269// unrelated boot epochs -- the remote row then reads as ancient (or future-forged) and a freshness 1270// guard rejects every honest remote node while looking like it is working. 1271func sys_now_realtime_us() -> i64 { 1272 let ts: *i64 = sys_mmap(16) as *i64 1273 sys_clock_gettime_real(ts) 1274 return ts[0] * SYS_MAGIC_1000000 + ts[1] / 1000 1275} 1276 1277// Convenience: monotonic time in milliseconds. Caller does not own 1278// the timespec buffer -- it is mmap'd once per call (cheap; the 1279// underlying syscall already costs more than the page fault). 1280func sys_now_ms() -> i64 { 1281 let ts: *i64 = sys_mmap(16) as *i64 1282 sys_clock_gettime_mono(ts) 1283 let sec_part: i64 = ts[0] * 1000 1284 let nsec_part: i64 = ts[1] / SYS_MAGIC_1000000 1285 return sec_part + nsec_part 1286} 1287 1288// Convenience: monotonic time in microseconds. Used by per-request 1289// elapsed-time tracking in search engines + benches where ms is too 1290// coarse. Same caller-ownership rules as sys_now_ms. 1291func sys_now_us() -> i64 { 1292 let ts: *i64 = sys_mmap(16) as *i64 1293 sys_clock_gettime_mono(ts) 1294 let sec_part: i64 = ts[0] * SYS_MAGIC_1000000 1295 let nsec_part: i64 = ts[1] / 1000 1296 return sec_part + nsec_part 1297} 1298 1299// Alias used by nx_search_onsite_engine etc. Matches `_us` naming 1300// convention. Substrate-canonical name is sys_now_us; this alias 1301// preserves existing call sites without churn. 1302func sys_clock_now_us() -> i64 { 1303 return sys_now_us() 1304} 1305 1306// Read the entire file at `path` into a fresh mmap'd buffer. Returns 1307// a null-terminated *u8 plus writes the byte count to *out_len. On 1308// error (open failure, oversize) returns null and leaves out_len = 0. 1309// Uses a fixed 1 MiB buffer for the first pass; larger sources need a 1310// growth loop. 1311// ---- process control (Linux RV64) ---------------------------- 1312// 1313// Lets NishiLang programs spawn other processes -- prerequisite 1314// for replacing shell scripts (f6_gate.sh) with .nx equivalents. 1315// NishiOS will expose a different process model (capability-based); 1316// these wrappers are the Linux-host compatibility layer. 1317 1318@ifdef TARGET_X86_64 1319const SYS_CLONE: i64 = 56 1320const SYS_EXECVE: i64 = 59 1321const SYS_WAIT4: i64 = 61 1322const SYS_PIPE2: i64 = 293 1323const SYS_DUP3: i64 = 292 1324@endif 1325 1326@ifndef TARGET_X86_64 1327const SYS_CLONE: i64 = 220 1328const SYS_EXECVE: i64 = 221 1329const SYS_WAIT4: i64 = 260 1330const SYS_PIPE2: i64 = 59 1331const SYS_DUP3: i64 = 24 1332@endif 1333 1334// Clone flags (subset). CLONE_VFORK blocks parent until child 1335// exec's or exits, matching fork() semantics closely enough for 1336// our spawn-then-wait patterns. 1337const CLONE_VM: i64 = 0x00000100 1338const CLONE_VFORK: i64 = 0x00004000 1339const SIGCHLD: i64 = 17 1340 1341// Create a child process via Linux clone(). Returns: 1342// > 0 in the parent: child PID 1343// == 0 in the child: child should exec or exit 1344// < 0 on error: -errno 1345// Uses SIGCHLD as the signal that parent receives on child exit 1346// (the libc fork() default); no shared memory or thread flags. 1347// ---- namespace / container family (debt 1785528831) ---------------- 1348// Moved here from nx_syscalls_x86_64.nx so ONE module owns the wrapper set. Their 1349// absence here is why nx_container.nx had to import that module as a SECOND syscall 1350// layer, which put every wrapper in the TU twice and let definition ORDER pick the 1351// winner, silently, until the duplicate-definition guard made it fail closed. 1352func sys_unshare(flags: i64) -> i64 { 1353 return __syscall(SYS_UNSHARE, flags, 0, 0, 0, 0, 0) 1354} 1355func sys_mount(source: *u8, target: *u8, fs_type: *u8, mountflags: i64, data: *u8) -> i64 { 1356 return __syscall(SYS_MOUNT, source, target, fs_type, mountflags, data, 0) 1357} 1358func sys_chroot(path: *u8) -> i64 { 1359 return __syscall(SYS_CHROOT, path, 0, 0, 0, 0, 0) 1360} 1361func sys_getuid() -> i64 { 1362 return __syscall(SYS_GETUID, 0, 0, 0, 0, 0, 0) 1363} 1364func sys_getgid() -> i64 { 1365 return __syscall(SYS_GETGID, 0, 0, 0, 0, 0, 0) 1366} 1367 1368func sys_fork() -> i64 { 1369 return __syscall(SYS_CLONE, SIGCHLD, 0, 0, 0, 0, 0) 1370} 1371 1372// Replace the current process image. `path` is the executable 1373// (absolute or in $PATH if the child first does a fresh clone). 1374// `argv` is a null-terminated array of *u8 (already-marshalled). 1375// `envp` same shape, or null for "inherit parent's env". 1376// Only returns on failure (-errno). 1377// EXEC WITH A CLEAN FD TABLE (seq1785451144). A child inherits every fd its parent held, INCLUDING 1378// listen sockets, across fork AND execve. That is how nx_opaque_login came to hold mgmt s :18098 1379// alongside mgmt itself -- two listeners on one port, connections split between them, a VALID route 1380// answering 404 on some requests. There is no error anywhere in that state, which is why it was 1381// filed as a transport flake for months. 1382// ADDITIVE ON PURPOSE: sys_execve is left byte-identical (910 call sites across 719 files -- a 1383// global change there is unverifiable in one session). Spawners opt in by calling THIS instead. 1384// AUDIT THAT MAKES IT SAFE: zero call sites in the tree dup3 to a target fd above 2, so no exec d 1385// child is deliberately handed a high fd; 0/1/2 are preserved untouched. 1386// Linux child lifetime binding: call in the freshly forked child, before exec. 1387// The expected parent PID is captured before fork, closing the pre-arm death race. 1388// Kernel semantics bind to the creating thread; privileged exec can clear this. 1389const NX_SYS_PRCTL: i64 = 167 1390const NX_PR_SET_PDEATHSIG: i64 = 1 1391const NX_PR_SET_CHILD_SUBREAPER: i64 = 36 1392func sys_prctl(option: i64, arg: i64) -> i64 { 1393 return __syscall(NX_SYS_PRCTL,option,arg,0,0,0,0) 1394} 1395func sys_bind_parent_lifetime(expected_parent: i64, signal: i64) -> i64 { 1396 if expected_parent <= 0 || signal <= 0 { return 0-22 } 1397 let armed: i64=sys_prctl(NX_PR_SET_PDEATHSIG,signal) 1398 if armed < 0 { return armed } 1399 let parent: i64=__syscall(173,0,0,0,0,0,0) 1400 if parent != expected_parent { return 0-10 } 1401 return 0 1402} 1403 1404// Linux waitid observes termination without releasing the child's PID when WNOWAIT is set. 1405// Portable syscall 95 requires the matching x86 backend translation to 247. 1406const SYS_WAITID_PORTABLE: i64 = 95 1407const NX_WAIT_P_PID: i64 = 1 1408const NX_WAIT_EXITED: i64 = 4 1409const NX_WAIT_NOWAIT: i64 = 0x01000000 1410const NX_WAIT_SIGINFO_BYTES: i64 = 128 1411func sys_waitid(idtype: i64, id: i64, info: *u8, options: i64) -> i64 { 1412 return __syscall(SYS_WAITID_PORTABLE,idtype,id,info as i64,options,0,0) 1413} 1414 1415// Post-fork only: the child owns its descriptor table. The buffer bounds a 1416// getdents batch, never the descriptor numbers or number of open handles. 1417const NX_FD_DENT_BUFFER: i64 = 4096 1418const NX_SYS_CLOSE_RANGE: i64 = 436 // Linux x86_64 and asm-generic ABI 1419const NX_FD_UINT_MAX: i64 = 4294967295 1420func sys_close_inherited_proc(first: i64) -> i64 { 1421 let directory: i64=sys_openat_rd("/proc/self/fd") 1422 if directory < 0 { return directory } 1423 let buf: *u8=sys_mmap(NX_FD_DENT_BUFFER) 1424 var result: i64=0 1425 var running: i64=1 1426 while running == 1 { 1427 let n: i64=sys_getdents64(directory,buf,NX_FD_DENT_BUFFER) 1428 if n == (0-4) { continue } 1429 if n <= 0 { result=n; break } 1430 var off: i64=0 1431 while off < n { 1432 if n-off < 20 { result=0-5; running=0; break } 1433 let rec: *u8=buf+off 1434 let size: i64=dirent_reclen(rec) 1435 if size < 20 || size > n-off { result=0-5; running=0; break } 1436 var i: i64=19 1437 var fd: i64=0 1438 var valid: i64=1 1439 while i < size { 1440 let c: i64=rec[i] as i64 1441 if c == 0 { break } 1442 if c < 48 || c > 57 { valid=0; break } 1443 if fd > (2147483647-(c-48))/10 { valid=0; break } 1444 fd=fd*10+c-48; i=i+1 1445 } 1446 if i == 19 || i == size { valid=0 } 1447 if valid == 1 && fd >= first && fd != directory { 1448 // Linux releases the descriptor even when close reports a late 1449 // I/O error; never retry close and risk a reused descriptor. 1450 let closed: i64=sys_close(fd) 1451 if closed < 0 && closed != (0-9) { result=closed; running=0; break } 1452 } 1453 off=off+size 1454 } 1455 } 1456 let closedir: i64=sys_close(directory) 1457 sys_munmap(buf,NX_FD_DENT_BUFFER) 1458 if result == 0 && closedir < 0 { result=closedir } 1459 return result 1460} 1461func sys_close_inherited(first: i64) -> i64 { 1462 if first < 0 { return 0-22 } 1463 let rc: i64=__syscall(NX_SYS_CLOSE_RANGE,first,NX_FD_UINT_MAX,0,0,0,0) 1464 if rc == (0-38) { return sys_close_inherited_proc(first) } 1465 return rc 1466} 1467func sys_execve_clean(path: *u8, argv: *i64, envp: *i64) -> i64 { 1468 let rc: i64=sys_close_inherited(3) 1469 if rc < 0 { return rc } 1470 return sys_execve(path,argv,envp) 1471} 1472 1473func sys_execve(path: *u8, argv: *i64, envp: *i64) -> i64 { 1474 return __syscall(SYS_EXECVE, path, argv, envp, 0, 0, 0) 1475} 1476 1477// Wait for a child to exit. `pid` = -1 waits for ANY child, 1478// otherwise waits for that specific PID. `status` is a caller- 1479// mmapped i64 slot: on exit the low 16 bits carry Linux's w* status 1480// flags (WIFEXITED / WEXITSTATUS). Returns the reaped child's PID 1481// or -errno. 1482func sys_wait4(pid: i64, status: *i64, options: i64) -> i64 { 1483 return __syscall(SYS_WAIT4, pid, status, options, 0, 0, 0) 1484} 1485 1486// Extract exit code from a wait4 status word. Matches the glibc 1487// WEXITSTATUS macro: bits 8-15 of the low 16. 1488func wait_exit_code(status: i64) -> i64 { 1489 return (status >> 8) & 0xFF 1490} 1491 1492// Terminating signal from a wait4 status (0 when the child exited normally). Sibling of 1493// wait_exit_code; RESTORED 2026-07-30 after a stale whole-tree push erased both it and 1494// sys_ignore_sigpipe below, while three files still CALLED them (nx_http_server, nx_sigpipe_gate, 1495// nx_tools_api_serve) -- so the tree could not build until they came back. 1496func wait_term_signal(status: i64) -> i64 { 1497 return status & 0x7f 1498} 1499 1500// THE ONE RULER for "what result code did this process actually produce". Use this, not 1501// wait_exit_code, anywhere the answer becomes a VERDICT. 1502// 1503// WHY IT EXISTS, MEASURED 2026-08-25. wait_exit_code is WEXITSTATUS and is correctly named: 1504// bits 8-15 of the status word. But a child KILLED BY A SIGNAL has no exit status at all, and 1505// those bits are ZERO -- so a SEGFAULTING process is indistinguishable from a clean exit 0 to 1506// every caller that reads only wait_exit_code. Measured live: a gate that SIGSEGV'd mid-run was 1507// served by /api/gate_run as exit_code 0, verdict GREEN. A CRASHED GATE WORE A PASS. 1508// 1509// This is not a new discovery in this estate -- and that is the point. nx_gatekit_lib's 1510// gk_wait_code already carried exactly this rule, with its own measurement recorded (two gates 1511// the 60 s watchdog KILLED journaled `GREEN exit=0 ms=60443`). It was fixed THERE in August and 1512// left unfixed in nx_tool_run, which is the shared exec primitive sitting behind /api/gate_run, 1513// /api/build and 51 other consumers. A LAW APPLIED IN ONE ORGAN AND NOT ITS SIBLING IS HALF A 1514// LAW, AND THE HALF LEFT UNDONE IS THE ONE ON THE PRODUCTION PATH. So the rule now lives HERE, 1515// beside the two accessors it is composed of, and gk_wait_code delegates to it: one ruler. 1516// 1517// Shell convention 128+signal (137 SIGKILL, 139 SIGSEGV) is deliberate: it makes the death both 1518// VISIBLE and NON-ZERO, so every existing caller that branches on rc != 0 sees it with no change. 1519// wait_exit_code is left EXACTLY as it was -- 85 call sites across the corpus (corpus_complete=1) 1520// read it, and silently redefining WEXITSTATUS under them would be the cure being worse. 1521func wait_status_rc(status: i64) -> i64 { 1522 let sig: i64 = wait_term_signal(status) 1523 if sig != 0 { return 128 + sig } 1524 return wait_exit_code(status) 1525} 1526 1527// Ignore SIGPIPE process-wide, so writing to a socket the peer already closed returns -EPIPE 1528// instead of KILLING the process. SIGPIPE default action is TERMINATE, which for a daemon means 1529// every client that walks away mid-response is an outage -- this one call at the listen primitive 1530// is inherited by all 52 consumers of nx_http_server_listen. 1531// rt_sigaction(SIGPIPE, {handler=SIG_IGN}, NULL, 8): syscall 13 on x86-64, which happens to equal 1532// the signal number. SA_RESTORER is deliberately NOT set -- the kernel consults it only when it 1533// DELIVERS a handler frame, and SIG_IGN never delivers one. 1534// PROVEN, not asserted: nx_sigpipe_gate forks a child that writes to a closed pipe and demands 1535// death-by-signal-13 WITHOUT this call and a clean -EPIPE WITH it. 1536// Restore a signal to its DEFAULT disposition. THE INVERSE OF sys_ignore_sigpipe, and it exists 1537// because SIG_IGN is inherited across BOTH fork and execve: a daemon that ignores SIGPIPE hands 1538// that ignore to every child it spawns, FOREVER. That silently corrupted verification -- the 1539// sigpipe gate reported 4/5 RED under /api/gate_run and 5/5 GREEN under a shell, same binary, 1540// same minute, because its DISEASE control (writing to a closed peer must KILL) could not be 1541// observed inside an environment where the kill was already disabled (seq1463). A harness must 1542// not change the state it is verifying; where it must, it has to hand back a clean slate. 1543// ⚠the same inheritance can also produce a FALSE GREEN, which is the far more dangerous half. 1544func sys_default_signal(sig: i64) -> i64 { 1545 let act: *i64 = sys_mmap(64) as *i64 1546 act[0] = 0 1547 act[1] = 0 1548 act[2] = 0 1549 act[3] = 0 1550 return __syscall(13, sig, act as i64, 0, 8, 0, 0) 1551} 1552 1553func sys_ignore_sigpipe() -> i64 { 1554 let act: *i64 = sys_mmap(64) as *i64 1555 act[0] = 1 1556 act[1] = 0 1557 act[2] = 0 1558 act[3] = 0 1559 return __syscall(13, 13, act as i64, 0, 8, 0, 0) 1560} 1561 1562// Create a pipe. `fds` must point at 8+ writable bytes; the kernel 1563// packs BOTH int32 fds into fds[0]: read end = low 32 bits, write end 1564// = HIGH 32 bits (fds[1] is never written -- the old comment claiming 1565// fds[1]=write-end caused a false-pass KAT + a hung gate, 2026-07-16). 1566// Extract: rfd = fds[0] & 0xffffffff; wfd = (fds[0] / 4294967296) & 1567// 0xffffffff. Returns 0 on success, -errno on failure. 1568func sys_pipe2(fds: *i64, flags: i64) -> i64 { 1569 return __syscall(SYS_PIPE2, fds, flags, 0, 0, 0, 0) 1570} 1571 1572// Duplicate `oldfd` onto `newfd`, closing `newfd` first if open. 1573// Used to wire child stdout to a pipe: dup3(pipe_write_end, 1). 1574func sys_dup3(oldfd: i64, newfd: i64, flags: i64) -> i64 { 1575 return __syscall(SYS_DUP3, oldfd, newfd, flags, 0, 0, 0) 1576} 1577 1578// ---- directory listing (Linux RV64 getdents64) --------------- 1579// 1580// Foundation for ls / glob / dir-walk helpers. Linux returns 1581// linux_dirent64 records: 1582// u64 d_ino (inode, ignored here) 1583// s64 d_off (next-record offset) 1584// u16 d_reclen (this record's byte length) 1585// u8 d_type (file type; DT_DIR=4, DT_REG=8, DT_LNK=10) 1586// char d_name[] (null-terminated name, padded so d_reclen 1587// carries us to the next record boundary) 1588// Total struct header: 19 bytes, then name up to d_reclen - 19. 1589 1590@ifdef TARGET_X86_64 1591const SYS_GETDENTS64: i64 = 217 1592@endif 1593@ifndef TARGET_X86_64 1594const SYS_GETDENTS64: i64 = 61 1595@endif 1596 1597const DT_UNKNOWN: i64 = 0 1598const DT_FIFO: i64 = 1 1599const DT_CHR: i64 = 2 1600const DT_DIR: i64 = 4 1601const DT_BLK: i64 = 6 1602const DT_REG: i64 = 8 1603const DT_LNK: i64 = 10 1604const DT_SOCK: i64 = 12 1605 1606// Raw syscall. Returns bytes written on success (0 = end-of-dir), 1607// or -errno on failure. 1608func sys_getdents64(fd: i64, buf: *u8, buf_len: i64) -> i64 { 1609 return __syscall(SYS_GETDENTS64, fd, buf, buf_len, 0, 0, 0) 1610} 1611 1612// Extract fields from a linux_dirent64 record. `rec` points at 1613// the start of the record; fields are at fixed offsets. 1614func dirent_reclen(rec: *u8) -> i64 { 1615 // d_reclen is u16 at offset 16. Read as two bytes little-endian. 1616 let lo: i64 = rec[16] 1617 let hi: i64 = rec[17] 1618 return lo | (hi << 8) 1619} 1620 1621func dirent_type(rec: *u8) -> i64 { 1622 return rec[18] 1623} 1624 1625// Pointer to the null-terminated name inside the record. 1626func dirent_name(rec: *u8) -> *u8 { 1627 let base: i64 = rec as i64 1628 return (base + 19) as *u8 1629} 1630 1631// ---- content-addressed file reader --------------------------- 1632 1633func sys_read_file(path: *u8, out_len: *i64) -> *u8 { 1634 let fd: i64 = sys_openat_rd(path) 1635 if fd < 0 { 1636 *out_len = 0 1637 return 0 as *u8 1638 } 1639 // DEBT-EATEN 2026-07-15: the old fixed 4 GiB cap SILENTLY TRUNCATED bigger files (a 9 GB gguf would 1640 // short-read into plausible-garbage tensors -- the worst failure class). Now the buffer is sized from 1641 // the file itself (lseek END), so ANY size reads fully. Physical pages still allocate on-demand. For 1642 // zero-copy any-size READ-ONLY access prefer sys_map_file (below). 1643 // DEBT-EATEN 2026-08-19 (1787076780): when the size is UNKNOWABLE (lseek END <= 0: /proc files, pipes 1644 // -- AND every empty regular file, which reports 0 just the same) this used to reserve 1645 // SYS_MAGIC_4294967296 of address space per call. Untouched pages were never resident, but the 1646 // mapping WAS: a daemon that read an empty registry every sweep ballooned its VmSize by 4 GiB per 1647 // read (measured: smoke instances at a 4.2 GB base), the leak screens flagged it, and sys_free_file 1648 // could only release what was read. The size-unknowable path now GROWS: start at SYS_READ_GROW_INIT, 1649 // double while the window fills, and hand back an EXACT mapping (total + 16) so sys_free_file 1650 // releases all of it. An empty file costs one small read and a 16-byte arena cell; /proc/stat fits 1651 // the first window; a pipe of any length still reads whole. The known-size path is unchanged. 1652 let fsz: i64 = sys_lseek(fd, 0, 2) 1653 sys_lseek(fd, 0, 0) 1654 var cap: i64 = SYS_READ_GROW_INIT 1655 var grow: i64 = 1 1656 if fsz > 0 { cap = fsz; grow = 0 } 1657 var buf: *u8 = sys_mmap(cap + 16) 1658 var total: i64 = 0 1659 var go: i64 = 1 1660 while go == 1 { 1661 let base: i64 = buf as i64 1662 let tail: *u8 = (base + total) as *u8 1663 let n: i64 = sys_read(fd, tail, cap - total) 1664 if n <= 0 { go = 0 } 1665 if n > 0 { total = total + n } 1666 if total >= cap { 1667 if grow == 0 { go = 0 } else { 1668 // the window filled and the size is unknown: double it, copy, release the old mapping 1669 let ncap: i64 = cap * 2 1670 let nb: *u8 = sys_mmap(ncap + 16) 1671 var ci: i64 = 0 1672 let obase: i64 = buf as i64 1673 let nbase: i64 = nb as i64 1674 while ci < total { let src: *u8 = (obase + ci) as *u8; let dst: *u8 = (nbase + ci) as *u8; dst[0] = src[0]; ci = ci + 1 } 1675 sys_munmap(buf, cap + 16) 1676 buf = nb 1677 cap = ncap 1678 } 1679 } 1680 } 1681 sys_close(fd) 1682 if grow == 1 { 1683 // hand back an EXACT mapping so the paired free releases everything (the doubled window would 1684 // otherwise leave its slack mapped forever -- the address-space leak this change exists to end) 1685 let xb: *u8 = sys_mmap(total + 16) 1686 var xi: i64 = 0 1687 let gbase: i64 = buf as i64 1688 let xbase: i64 = xb as i64 1689 while xi < total { let gsrc: *u8 = (gbase + xi) as *u8; let xdst: *u8 = (xbase + xi) as *u8; xdst[0] = gsrc[0]; xi = xi + 1 } 1690 sys_munmap(buf, cap + 16) 1691 buf = xb 1692 } 1693 // Null-terminate for the lexer. 1694 let bbase: i64 = buf as i64 1695 let term: *u8 = (bbase + total) as *u8 1696 term[0] = 0 1697 *out_len = total 1698 return buf 1699} 1700 1701// PAIRED FREE FOR sys_read_file (2026-08-17). sys_read_file mmaps `cap + 16` where cap is the FILE SIZE 1702// and returns only the pointer -- so any caller that frees it must know the padding, and a caller that 1703// unmaps `len` alone leaks the tail page whenever the file size sits just under a page boundary. 1704// ★A CALLER FORCED TO KNOW ITS ALLOCATOR'S PADDING IS A COUPLING THAT WILL DRIFT -- so the +16 lives 1705// HERE, beside the +16 it mirrors, instead of being retyped at every call site. 1706// Pass the length sys_read_file reported through out_len; this re-derives the mapping from it. 1707// Null-safe by construction: sys_read_file returns 0 on failure, so callers need no extra guard -- 1708// ★A FREE THAT REFUSES NULL IS A FREE NOBODY HAS TO WRAP IN AN IF. 1709// EXACT for every path since 2026-08-19: the size-unknowable fallback (lseek <= 0: /proc, pipes, empty 1710// regular files) now returns a mapping of exactly total + 16, so this releases ALL of it. (It used to 1711// map SYS_MAGIC_4294967296 of address space and release only what was read -- stated then, ended now.) 1712// WHY IT EXISTS: nx_sites_daemon serves /wiki/roadmap by calling sys_read_file PER REQUEST inside a loop 1713// that runs up to NX_SD_MAX_REQ_PER_CONN (64) times per connection and never released it -- an 8,408 B 1714// file became 3 fresh pages and a fresh kernel VMA on every hit, held until the child exited. 1715func sys_free_file(buf: *u8, len: i64) -> i64 { 1716 if (buf as i64) == 0 { return 0 } 1717 if len < 0 { return 0 } 1718 return sys_munmap(buf, len + 16) 1719} 1720 1721// Read-only FILE-BACKED map of the whole file (PROT_READ=1, MAP_PRIVATE=2): any size, zero-copy -- only 1722// touched pages become resident (the lazy-MoE shape: a 9 GB model serves in ~active-set RSS, and load 1723// time is ~0 because nothing is copied). NO NUL pad (a file mapping cannot be extended) -- BINARY 1724// consumers only; text/lexer callers keep sys_read_file. Returns 0 on failure; *out_len = file size. 1725// Read-only by construction (PROT_READ; writes fault -- Rule 26-friendly). 1726func sys_map_file(path: *u8, out_len: *i64) -> *u8 { 1727 *out_len = 0 1728 let fd: i64 = sys_openat_rd(path) 1729 if fd < 0 { return 0 as *u8 } 1730 let fsz: i64 = sys_lseek(fd, 0, 2) 1731 if fsz <= 0 { sys_close(fd); return 0 as *u8 } 1732 let r: i64 = __syscall(SYS_MMAP, 0, fsz, 1, 2, fd, 0) 1733 sys_close(fd) 1734 if r <= 0 { return 0 as *u8 } 1735 *out_len = fsz 1736 return r as *u8 1737} 1738 1739// Sleep for `ms` milliseconds against CLOCK_MONOTONIC (relative). 1740// Returns 0 on success, negative errno on failure. Caller-supplied 1741// budget: ms <= 0 is a no-op; very large values are accepted as-is 1742// (the kernel will saturate to its own clamp). Defined at the bottom 1743// of this file so sys_mmap is in scope (single-pass parser). 1744func sys_sleep_ms(ms: i64) -> i64 { 1745 if ms <= 0 { return 0 } 1746 // struct timespec { sec: i64, nsec: i64 } -- 16 bytes RV64. 1747 let req: *u8 = sys_mmap(16) 1748 let rem: *u8 = sys_mmap(16) 1749 let secs: i64 = ms / 1000 1750 let nsec: i64 = (ms - secs * 1000) * SYS_MAGIC_1000000 // remainder ms -> ns 1751 let req_sec: *i64 = req as *i64 1752 let req_nsec: *i64 = ((req as i64) + 8) as *i64 1753 req_sec[0] = secs 1754 req_nsec[0] = nsec 1755 // clock_nanosleep(CLOCK_MONOTONIC=1, flags=0, req, rem). On EINTR (-4) a signal (e.g. SIGCHLD from a 1756 // reaped child) cut the sleep short and wrote the leftover into rem -- RESUME it, otherwise a caller 1757 // that uses the sleep as a timer (the torrent pool's 2s tick) gets spun into a busy loop by child 1758 // deaths and any tick-based budget collapses to milliseconds. A sleep must sleep its full duration. 1759 var r: i64 = __syscall(SYS_CLOCK_NANOSLEEP, 1, 0, req as i64, rem as i64, 0, 0) 1760 var guard: i64 = 0 1761 while r == (0 - 4) { 1762 if guard > SYS_MAGIC_100000 { r = 0 } else { 1763 let rs: *i64 = rem as *i64 1764 let rn: *i64 = ((rem as i64) + 8) as *i64 1765 req_sec[0] = rs[0] 1766 req_nsec[0] = rn[0] 1767 r = __syscall(SYS_CLOCK_NANOSLEEP, 1, 0, req as i64, rem as i64, 0, 0) 1768 guard = guard + 1 1769 } 1770 } 1771 sys_munmap(req, 16); sys_munmap(rem, 16) // FREE the timespec pages -- every call mmap'd 2 pages; in a 1772 // long-running poll loop (the supervisor's 15s tick) that leaked ~8KB/iter until mmap -> -12 -> SEGFAULT. 1773 return r 1774} 1775 1776// ---- sockets (RV64 generic syscall numbers) ---------------------- 1777// 1778// Source uses RV64 numbers; the x86_64 backend's 1779// x86ctx_rv64_to_x86_64_syscall table translates at codegen time. 1780// Numbers from arch/arm64/include/asm/unistd.h (RV64 inherits the 1781// generic ABI). 1782 1783// Socket-family syscall numbers via @ifdef macro -- mirrors the 1784// pattern already used for SYS_READ/WRITE/MMAP/etc. above. Without 1785// this gate, --target x86_64 compiled the RV64 numbers as literals 1786// into the `syscall` instruction (e.g. 198 = sched_setaffinity on 1787// x86_64, not socket) and any daemon using sys_socket() died with 1788// ENOSYS before printing its banner -- caught by the nx_signaling 1789// stone S2 deploy on 2026-05-20 (see [[project-cross-isa-syscall- 1790// unification-gap-2026-05-20]]). 1791@ifdef TARGET_X86_64 1792const SYS_SOCKET: i64 = 41 1793const SYS_BIND: i64 = 49 1794const SYS_LISTEN: i64 = 50 1795const SYS_ACCEPT: i64 = 43 1796const SYS_CONNECT: i64 = 42 1797const SYS_SETSOCKOPT: i64 = 54 1798const SYS_SENDTO: i64 = 44 1799const SYS_RECVFROM: i64 = 45 1800const SYS_SHUTDOWN: i64 = 48 1801@endif 1802 1803@ifndef TARGET_X86_64 1804const SYS_SOCKET: i64 = 198 1805const SYS_BIND: i64 = 200 1806const SYS_LISTEN: i64 = 201 1807const SYS_ACCEPT: i64 = 202 1808const SYS_CONNECT: i64 = 203 1809const SYS_SETSOCKOPT: i64 = 208 1810const SYS_SENDTO: i64 = 206 1811const SYS_RECVFROM: i64 = 207 1812const SYS_SHUTDOWN: i64 = 210 1813@endif 1814 1815// Socket-option constants used by nx_http_server / nx_https_server. 1816const SOL_SOCKET: i64 = 1 1817const SO_REUSEADDR: i64 = 2 1818// Receive/send timeouts (Linux x86_64). optval is a struct timeval 1819// {tv_sec: i64, tv_usec: i64} (16 bytes). Essential on PUBLIC sockets: 1820// without them, a single silent/slow client hangs a blocking read 1821// forever -> trivial DoS on a single-threaded accept loop. 1822const SO_SNDTIMEO: i64 = 21 1823const SO_RCVTIMEO: i64 = 20 1824 1825// setsockopt(2) -- set a socket option. Defined BEFORE its first caller 1826// (sys_set_socket_timeout, below): NishiLang forbids forward references, 1827// so the definition must precede every use. 1828func sys_setsockopt(fd: i64, level: i64, optname: i64, 1829 optval: *u8, optlen: i64) -> i64 { 1830 return __syscall(SYS_SETSOCKOPT, fd, level, optname, optval, optlen, 0) 1831} 1832 1833// Set a receive+send timeout (in whole seconds) on a socket fd. 1834// tv is munmap'd before return (LEAK FIXED 2026-07-16): this is called once per PROBE by the daemon 1835// supervisor (35/cycle forever -> ~800MB VSZ/day) and once per CONNECTION by fork-per-connection daemons. 1836// The unfreed page-per-call ballooned VSZ until heuristic overcommit made fork() return -ENOMEM (the 1837// proven pid=-12 failure class) -- likely the historical VSZ pressure behind the vsz_watchdog. 1838func sys_set_socket_timeout(fd: i64, secs: i64) -> i64 { 1839 let tv: *i64 = (sys_mmap(16)) as *i64 1840 tv[0] = secs // tv_sec 1841 tv[1] = 0 // tv_usec 1842 sys_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, tv as *u8, 16) 1843 sys_setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, tv as *u8, 16) 1844 sys_munmap(tv as *u8, 16) 1845 return 0 1846} 1847 1848// alarm(2): deliver SIGALRM after `secs` seconds (0 cancels a pending alarm). No SIGALRM handler is installed, so 1849// the default action TERMINATES the process. Used as a per-request watchdog inside a forked request-child: a 1850// pathologically-slow page can then never hang the child forever (which would leak its buffers + pile up procs). 1851const SYS_ALARM: i64 = 37 1852func sys_alarm(secs: i64) -> i64 { return __syscall(SYS_ALARM, secs, 0, 0, 0, 0, 0) } 1853 1854const AF_INET: i64 = 2 1855const SOCK_STREAM: i64 = 1 1856const SOCK_DGRAM: i64 = 2 1857 1858func sys_socket(domain: i64, sock_type: i64, protocol: i64) -> i64 { 1859 return __syscall(SYS_SOCKET, domain, sock_type, protocol, 0, 0, 0) 1860} 1861// Pack an AF_INET any-address sockaddr_in (16 bytes) for `port` at `addr`. 1862// RESTORED INTO THE OWNER 2026-08-19: this lived in the old full nx_syscalls_x86_64.nx and was the 1863// one wrapper WITH LIVE CALLERS (nx_nishipages_serve, nx_udp) that the 2026-07-31 alias-stub 1864// consolidation dropped -- both lanes sat NAS-unbuildable ("I do not know the name") until the 1865// rebuild-drain surfaced them. Body verbatim from the old file, including its documented 1866// workaround: NO `as u8` casts on the byte stores -- the array-element-store already truncates 1867// when the lvalue is *u8, and casts on this path once tripped a codegen defect. 1868// (The old file's other two uncalled orphans, sys_pivot_root/sys_umount2, were left dead on a 1869// zero-caller full-tree grep -- restoring an uncalled wrapper is inventory, not capability.) 1870func sockaddr_in_init(addr: *u8, port: i64) -> i64 { 1871 addr[0] = 2 // AF_INET low byte 1872 addr[1] = 0 1873 // Port in network byte order (big-endian). 1874 let hi: i64 = (port >> 8) & 0xFF 1875 let lo: i64 = port & 0xFF 1876 addr[2] = hi 1877 addr[3] = lo 1878 addr[4] = 0 1879 addr[5] = 0 1880 addr[6] = 0 1881 addr[7] = 0 1882 addr[8] = 0 1883 addr[9] = 0 1884 addr[10] = 0 1885 addr[11] = 0 1886 addr[12] = 0 1887 addr[13] = 0 1888 addr[14] = 0 1889 addr[15] = 0 1890 return 0 1891} 1892 1893func sys_bind(fd: i64, addr: *u8, addr_len: i64) -> i64 { 1894 return __syscall(SYS_BIND, fd, addr, addr_len, 0, 0, 0) 1895} 1896func sys_listen(fd: i64, backlog: i64) -> i64 { 1897 return __syscall(SYS_LISTEN, fd, backlog, 0, 0, 0, 0) 1898} 1899// accept(2) -- accept the next pending connection on a listening socket. 1900// Single-arg form (kernel ignores NULL addr/addr_len writes). Existing 1901// nx_http_server callers use this signature; the 3-arg form is provided 1902// as sys_accept_with_addr for outliers needing peer address. 1903func sys_accept(fd: i64) -> i64 { 1904 return __syscall(SYS_ACCEPT, fd, 0, 0, 0, 0, 0) 1905} 1906func sys_accept_with_addr(fd: i64, addr: *u8, addr_len: *i64) -> i64 { 1907 return __syscall(SYS_ACCEPT, fd, addr, addr_len, 0, 0, 0) 1908} 1909// shutdown(2) -- half-close a socket. how: 0=RD, 1=WR, 2=RDWR. 1910func sys_shutdown(fd: i64, how: i64) -> i64 { 1911 return __syscall(SYS_SHUTDOWN, fd, how, 0, 0, 0, 0) 1912} 1913func sys_connect(fd: i64, addr: *u8, addr_len: i64) -> i64 { 1914 return __syscall(SYS_CONNECT, fd, addr, addr_len, 0, 0, 0) 1915} 1916func sys_sendto(fd: i64, buf: *u8, n: i64, flags: i64, 1917 dest_addr: *u8, addr_len: i64) -> i64 { 1918 return __syscall(SYS_SENDTO, fd, buf, n, flags, dest_addr, addr_len) 1919} 1920func sys_recvfrom(fd: i64, buf: *u8, n: i64, flags: i64, 1921 src_addr: *u8, addr_len: *i64) -> i64 { 1922 return __syscall(SYS_RECVFROM, fd, buf, n, flags, src_addr, addr_len) 1923} 1924 1925// ---- SCM_RIGHTS DESCRIPTOR PASSING (sendmsg/recvmsg over AF_UNIX) ----------------------------- 1926// ADDED 2026-08-21 for /compare/trafficsafety TS1. Until now sys_sendmsg was ABSENT-PROVEN from the 1927// whole tree (corpus_complete=1), so the mechanism nginx, HAProxy and Envoy all use for hitless 1928// replacement -- MOVING the listening descriptor rather than re-binding it -- could not be written 1929// at all. SO_REUSEPORT co-binding is an ACCEPT-DISTRIBUTION primitive, NOT a handoff primitive: 1930// LWN documents that changing the set of listening sockets on a port drops connections during the 1931// three-way handshake, so co-binding proves two binders and can never prove zero drops. 1932// 1933// EVERY OFFSET BELOW IS MEASURED, NOT RECALLED. They were read out of the platform's own headers 1934// with offsetof/sizeof/CMSG_LEN compiled for x86_64: 1935// msghdr 56 = name 0 | namelen 8 (u32) | iov 16 | iovlen 24 | control 32 | controllen 40 | flags 48 (u32) 1936// iovec 16 = base 0 | len 8 1937// cmsghdr 16 = len 0 (u64) | level 8 (u32) | type 12 (u32), data at 16 1938// CMSG_LEN(4)=20 CMSG_SPACE(4)=24 sendmsg=46 recvmsg=47 socketpair=53 1939// AF_UNIX=1 SOL_SOCKET=1 SCM_RIGHTS=1 MSG_CMSG_CLOEXEC=1073741824 1940// A WRONG LAYOUT HERE DOES NOT FAIL LOUD. The syscall still returns a positive byte count and 1941// simply transfers no descriptor, which is why the gate for this proves the property by passing a 1942// REAL descriptor between two REAL processes and then USING it, never by reading a return code. 1943// x86_64 Linux numbers, DELIBERATELY UNGUARDED, and the reason is a measurement rather than a 1944// preference. The first draft of this block wrapped these three in the same 1945// @ifdef TARGET_X86_64 / @ifndef pair every other syscall number in this file uses. On an x86 build 1946// that made every call ENOSYS, and the probe that caught it printed why: 1947// CONSTS SYS_SENDMSG=211 SYS_RECVMSG=212 SYS_SOCKETPAIR=199 SYS_WRITE=64 1948// N sendmsg PLAIN via the CONST rc=-38 (211 is unassigned on x86_64) 1949// N2 sendmsg PLAIN via the LITERAL rc=1 1950// SYS_WRITE reading 64 is the tell and it is NOT MINE: the file's own original guarded block 1951// resolves to its RV64 branch when the constant is referenced, on a build whose sys_write plainly 1952// works. So a constant inside these guards is not reliably the value the guard appears to select. 1953// !! A GUARD THAT SILENTLY SELECTS THE OTHER TARGET'S NUMBER IS WORSE THAN NO GUARD: the call still 1954// compiles, still returns, and dispatches a DIFFERENT SYSCALL. Syscall 199 on x86_64 is 1955// fremovexattr, which is why socketpair appeared to answer EFAULT for every input including a NULL 1956// vector and an unsupported domain -- varying the ARGUMENTS can never reveal that the NUMBER is 1957// wrong, because every variant was equally wrong. 1958// => RV64 support for these three is an OPEN, NAMED requirement, blocked on that toolchain 1959// behaviour. It is left undone and stated rather than papered over with a guard measured not to 1960// work. The estate already keeps nx_syscalls_x86_64.nx as the explicit single-target mirror for 1961// exactly this class of problem. 1962const SYS_SENDMSG: i64 = 46 1963const SYS_RECVMSG: i64 = 47 1964const SYS_SOCKETPAIR: i64 = 53 1965const SCM_AF_UNIX: i64 = 1 1966const SCM_SOL_SOCKET: i64 = 1 1967const SCM_RIGHTS_TYPE: i64 = 1 1968const SCM_MSG_CMSG_CLOEXEC: i64 = 1073741824 1969const SCM_MSGHDR_BYTES: i64 = 56 1970const SCM_MSGHDR_OFF_IOV: i64 = 16 1971const SCM_MSGHDR_OFF_IOVLEN: i64 = 24 1972const SCM_MSGHDR_OFF_CTRL: i64 = 32 1973const SCM_MSGHDR_OFF_CTRLLEN: i64 = 40 1974const SCM_IOVEC_BYTES: i64 = 16 1975const SCM_IOVEC_OFF_BASE: i64 = 0 1976const SCM_IOVEC_OFF_LEN: i64 = 8 1977const SCM_CMSG_OFF_LEN: i64 = 0 1978const SCM_CMSG_OFF_LEVEL: i64 = 8 1979const SCM_CMSG_OFF_TYPE: i64 = 12 1980const SCM_CMSG_OFF_DATA: i64 = 16 1981const SCM_CMSG_LEN_1FD: i64 = 20 1982const SCM_CMSG_SPACE_1FD: i64 = 24 1983const SCM_IOV_COUNT_ONE: i64 = 1 1984const SCM_U32_BYTES: i64 = 4 1985const SCM_BYTE_RADIX: i64 = 256 1986const SCM_FDPAIR_BYTES: i64 = 8 1987// One real data byte travels with the ancillary data ON PURPOSE: a sendmsg carrying SCM_RIGHTS and 1988// NO ordinary payload is the classic silent no-transfer, and it returns 0 rather than an error. 1989const SCM_PAYLOAD_BYTES: i64 = 1 1990const SCM_PAYLOAD_BYTE: i64 = 70 1991// Distinguishable refusals, each naming WHICH conjunct failed -- a compound assertion that will not 1992// name its failing conjunct is a false-alarm generator. All are negative and all sit far outside the 1993// errno range, so no caller can confuse one with a kernel error or with a valid descriptor. 1994const SCM_ERR_NO_CMSG: i64 = 0 - 901 1995const SCM_ERR_CMSG_LEN: i64 = 0 - 902 1996const SCM_ERR_CMSG_LEVEL: i64 = 0 - 903 1997const SCM_ERR_CMSG_TYPE: i64 = 0 - 904 1998 1999func scm_zero(base: *u8, n: i64) -> i64 { var i: i64 = 0; while i < n { base[i] = 0; i = i + 1 } return 0 } 2000func scm_put_i64(base: *u8, off: i64, v: i64) -> i64 { 2001 let p: *i64 = ((base as i64) + off) as *i64 2002 p[0] = v 2003 return 0 2004} 2005func scm_get_i64(base: *u8, off: i64) -> i64 { 2006 let p: *i64 = ((base as i64) + off) as *i64 2007 return p[0] 2008} 2009// The two cmsg header fields and the descriptor slot itself are 4-byte ints, so they are packed and 2010// unpacked byte by byte in little-endian order. Radix arithmetic rather than bit shifts, matching 2011// sockaddr_in_init's documented style on this exact path. 2012func scm_put_u32(base: *u8, off: i64, v: i64) -> i64 { 2013 var i: i64 = 0 2014 var m: i64 = v 2015 while i < SCM_U32_BYTES { 2016 base[off + i] = m % SCM_BYTE_RADIX 2017 m = m / SCM_BYTE_RADIX 2018 i = i + 1 2019 } 2020 return 0 2021} 2022func scm_get_u32(base: *u8, off: i64) -> i64 { 2023 var v: i64 = 0 2024 var mult: i64 = 1 2025 var i: i64 = 0 2026 while i < SCM_U32_BYTES { 2027 v = v + (base[off + i] as i64) * mult 2028 mult = mult * SCM_BYTE_RADIX 2029 i = i + 1 2030 } 2031 return v 2032} 2033 2034func sys_sendmsg(fd: i64, msg: *u8, flags: i64) -> i64 { 2035 return __syscall(SYS_SENDMSG, fd, msg, flags, 0, 0, 0) 2036} 2037func sys_recvmsg(fd: i64, msg: *u8, flags: i64) -> i64 { 2038 return __syscall(SYS_RECVMSG, fd, msg, flags, 0, 0, 0) 2039} 2040// socketpair(2). sv receives TWO 4-byte descriptors, so it is a *u8 read with scm_get_u32 -- a 2041// single *i64 read would splice both descriptors into one number and the second would vanish. 2042// !! THIS NUMBER IS NOT REACHING socketpair, AND THE FIRST DIAGNOSIS OF THAT WAS WRONG. 2043// Measured 2026-08-21: every call returns -14 (EFAULT) -- with a valid pointer, with a NULL vector, 2044// and with an UNSUPPORTED DOMAIN alike. The first reading of that evidence was "the host refuses 2045// this call for every input", and it was REFUTED by measuring the emitted constants instead of the 2046// arguments. TARGET_X86_64 is hard-pinned UNDEFINED in this toolchain (see nx_syscalls_x86_64.nx 2047// and nx_tokenizer.nx), so the @ifndef branch is what compiles and the x86 backend TRANSLATES RV64 2048// syscall numbers at emit time. Under that translation 53 is RV64 fchmodat, whose SECOND argument 2049// is a path pointer -- and SOCK_STREAM==1 as a path pointer is exactly EFAULT, every time, 2050// regardless of the other arguments. 2051// * VARYING THE ARGUMENTS CAN NEVER REVEAL THAT THE SYSCALL NUMBER IS WRONG: every variant is 2052// equally wrong, so a set of controls that all agree reads as a confident finding about the host. 2053// The control that actually discriminated was PRINTING THE CONSTANT the binary emits. 2054// => The likely correct value here is the RV64 number 199, exactly as sendmsg/recvmsg above needed 2055// their own numbers rather than the guarded pair. That is NOT asserted: it is UNTESTED, and this 2056// comment says so rather than shipping a plausible number with a confident sentence. 2057// => NOTHING DEPENDS ON IT. The descriptor-passing lane uses a NAMED AF_UNIX rendezvous 2058// (sys_unix_listen + sys_unix_connect_fd below), which is proven end to end by nx_scm_rights_gate 2059// and is also what nginx, HAProxy and systemd actually use to move a listener between processes. 2060// socketpair was only ever the convenience. 2061func sys_socketpair(domain: i64, sock_type: i64, protocol: i64, sv: *u8) -> i64 { 2062 return __syscall(SYS_SOCKETPAIR, domain, sock_type, protocol, sv, 0, 0) 2063} 2064 2065// Bind+listen a NAMED AF_UNIX stream socket -- the accepting half of the rendezvous whose 2066// connecting half is nx_unix_connect. Returns the listening fd, or a negative errno. 2067// The caller owns the path: unlink it first (a stale node makes bind return EADDRINUSE) and unlink 2068// it after, because an AF_UNIX bind leaves a filesystem entry that outlives the process. 2069const SCM_SUN_PATH_OFF: i64 = 2 // sockaddr_un = [sa_family: u16][sun_path: 108] 2070const SCM_SUN_BYTES: i64 = 110 2071const SCM_SUN_PATH_MAX: i64 = 107 2072func sys_unix_listen(path: *u8, backlog: i64) -> i64 { 2073 let fd: i64 = sys_socket(SCM_AF_UNIX, SOCK_STREAM, 0) 2074 if fd < 0 { return fd } 2075 let sa: *u8 = sys_mmap(SCM_SUN_BYTES) 2076 var i: i64 = 0 2077 while i < SCM_SUN_BYTES { sa[i] = 0; i = i + 1 } 2078 sa[0] = SCM_AF_UNIX 2079 sa[1] = 0 2080 var p: i64 = 0 2081 while path[p] != (0 as u8) { 2082 if p >= SCM_SUN_PATH_MAX { sys_close(fd); return 0 - 36 } 2083 sa[SCM_SUN_PATH_OFF + p] = path[p] 2084 p = p + 1 2085 } 2086 let br: i64 = sys_bind(fd, sa, SCM_SUN_PATH_OFF + p + 1) 2087 if br < 0 { sys_close(fd); return br } 2088 let lr: i64 = sys_listen(fd, backlog) 2089 if lr < 0 { sys_close(fd); return lr } 2090 return fd 2091} 2092 2093// The CONNECTING half of the same rendezvous. Returns the connected fd or a negative errno. 2094// RESIDUAL NAMED RATHER THAN LEFT SILENT: nx_unix_socket.nx already carries an nx_unix_connect with 2095// this exact body. It is not composed here because that file also defines a main(), so importing it 2096// would inject a second main into every one of the 52 daemons that reach nx_http_server -- a 2097// resolution-by-definition-order hazard this tree has already been bitten by. The primitive belongs 2098// in the shim; the older standalone file should be reduced to a caller of this one, and that is a 2099// separate change to a file with its own consumers rather than something to fold in silently here. 2100func sys_unix_connect_fd(path: *u8) -> i64 { 2101 let fd: i64 = sys_socket(SCM_AF_UNIX, SOCK_STREAM, 0) 2102 if fd < 0 { return fd } 2103 let sa: *u8 = sys_mmap(SCM_SUN_BYTES) 2104 var i: i64 = 0 2105 while i < SCM_SUN_BYTES { sa[i] = 0; i = i + 1 } 2106 sa[0] = SCM_AF_UNIX 2107 sa[1] = 0 2108 var p: i64 = 0 2109 while path[p] != (0 as u8) { 2110 if p >= SCM_SUN_PATH_MAX { sys_close(fd); return 0 - 36 } 2111 sa[SCM_SUN_PATH_OFF + p] = path[p] 2112 p = p + 1 2113 } 2114 let cr: i64 = sys_connect(fd, sa, SCM_SUN_PATH_OFF + p + 1) 2115 if cr < 0 { sys_close(fd); return cr } 2116 return fd 2117} 2118 2119// Send ONE open descriptor over a connected AF_UNIX socket. Returns the sendmsg result: the number 2120// of ordinary data bytes sent (SCM_PAYLOAD_BYTES on success) or a negative errno. The descriptor 2121// itself is NOT closed here -- both ends legitimately hold it until the sender chooses to let go, 2122// and that overlap is the entire point: there must be no instant at which zero processes hold the 2123// listening socket. 2124func sys_send_fd(sock: i64, fd: i64) -> i64 { 2125 let msg: *u8 = sys_mmap(SCM_MSGHDR_BYTES) 2126 let iov: *u8 = sys_mmap(SCM_IOVEC_BYTES) 2127 let cbuf: *u8 = sys_mmap(SCM_CMSG_SPACE_1FD) 2128 let data: *u8 = sys_mmap(SCM_PAYLOAD_BYTES) 2129 scm_zero(msg, SCM_MSGHDR_BYTES) 2130 scm_zero(cbuf, SCM_CMSG_SPACE_1FD) 2131 data[0] = SCM_PAYLOAD_BYTE 2132 scm_put_i64(iov, SCM_IOVEC_OFF_BASE, data as i64) 2133 scm_put_i64(iov, SCM_IOVEC_OFF_LEN, SCM_PAYLOAD_BYTES) 2134 scm_put_i64(msg, SCM_MSGHDR_OFF_IOV, iov as i64) 2135 scm_put_i64(msg, SCM_MSGHDR_OFF_IOVLEN, SCM_IOV_COUNT_ONE) 2136 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRL, cbuf as i64) 2137 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRLLEN, SCM_CMSG_SPACE_1FD) 2138 scm_put_i64(cbuf, SCM_CMSG_OFF_LEN, SCM_CMSG_LEN_1FD) 2139 scm_put_u32(cbuf, SCM_CMSG_OFF_LEVEL, SCM_SOL_SOCKET) 2140 scm_put_u32(cbuf, SCM_CMSG_OFF_TYPE, SCM_RIGHTS_TYPE) 2141 scm_put_u32(cbuf, SCM_CMSG_OFF_DATA, fd) 2142 let r: i64 = sys_sendmsg(sock, msg, 0) 2143 sys_munmap(msg, SCM_MSGHDR_BYTES) 2144 sys_munmap(iov, SCM_IOVEC_BYTES) 2145 sys_munmap(cbuf, SCM_CMSG_SPACE_1FD) 2146 sys_munmap(data, SCM_PAYLOAD_BYTES) 2147 return r 2148} 2149 2150// Receive ONE descriptor from a connected AF_UNIX socket. Returns the NEW descriptor number in this 2151// process (>= 0), a negative errno from recvmsg, or one of the SCM_ERR_* codes above. 2152// flags: 0, or SCM_MSG_CMSG_CLOEXEC so the arriving descriptor is not leaked into grandchildren -- 2153// the estate has already lost a port for six days to exactly that inheritance (nx_cloexec_gate). 2154// THE VALIDATION IS THE WHOLE POINT. recvmsg happily returns a positive byte count having delivered 2155// no ancillary data at all, so the kernel's REWRITTEN msg_controllen is read back rather than the 2156// value we asked for, and each of the three cmsg header fields is checked separately so a failure 2157// says which one. 2158func sys_recv_fd(sock: i64, flags: i64) -> i64 { 2159 let msg: *u8 = sys_mmap(SCM_MSGHDR_BYTES) 2160 let iov: *u8 = sys_mmap(SCM_IOVEC_BYTES) 2161 let cbuf: *u8 = sys_mmap(SCM_CMSG_SPACE_1FD) 2162 let data: *u8 = sys_mmap(SCM_PAYLOAD_BYTES) 2163 scm_zero(msg, SCM_MSGHDR_BYTES) 2164 scm_zero(cbuf, SCM_CMSG_SPACE_1FD) 2165 scm_put_i64(iov, SCM_IOVEC_OFF_BASE, data as i64) 2166 scm_put_i64(iov, SCM_IOVEC_OFF_LEN, SCM_PAYLOAD_BYTES) 2167 scm_put_i64(msg, SCM_MSGHDR_OFF_IOV, iov as i64) 2168 scm_put_i64(msg, SCM_MSGHDR_OFF_IOVLEN, SCM_IOV_COUNT_ONE) 2169 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRL, cbuf as i64) 2170 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRLLEN, SCM_CMSG_SPACE_1FD) 2171 let r: i64 = sys_recvmsg(sock, msg, flags) 2172 var out: i64 = r 2173 if r >= 0 { 2174 out = SCM_ERR_NO_CMSG 2175 if scm_get_i64(msg, SCM_MSGHDR_OFF_CTRLLEN) >= SCM_CMSG_LEN_1FD { 2176 out = SCM_ERR_CMSG_LEN 2177 if scm_get_i64(cbuf, SCM_CMSG_OFF_LEN) == SCM_CMSG_LEN_1FD { 2178 out = SCM_ERR_CMSG_LEVEL 2179 if scm_get_u32(cbuf, SCM_CMSG_OFF_LEVEL) == SCM_SOL_SOCKET { 2180 out = SCM_ERR_CMSG_TYPE 2181 if scm_get_u32(cbuf, SCM_CMSG_OFF_TYPE) == SCM_RIGHTS_TYPE { 2182 out = scm_get_u32(cbuf, SCM_CMSG_OFF_DATA) 2183 } 2184 } 2185 } 2186 } 2187 } 2188 sys_munmap(msg, SCM_MSGHDR_BYTES) 2189 sys_munmap(iov, SCM_IOVEC_BYTES) 2190 sys_munmap(cbuf, SCM_CMSG_SPACE_1FD) 2191 sys_munmap(data, SCM_PAYLOAD_BYTES) 2192 return out 2193} 2194 2195// Ordinary permission bits only. Special privilege bits are never copied by staging. 2196const NX_FILE_PERMISSION_MASK:i64=511 2197const NX_FILE_DESCRIPTOR_INVALID:i64=0-22 2198func sys_fchmod_fd(fd:i64,mode:i64)->i64{ 2199 if fd<0 || mode<0 || mode>NX_FILE_PERMISSION_MASK {return NX_FILE_DESCRIPTOR_INVALID} 2200 return __syscall(52,fd,mode,0,0,0,0) 2201} 2202// Portable descriptor syscall; consumers below use the x86-64 stat ABI layout. 2203const NX_STAT_X64_BYTES:i64=144 2204const NX_STAT_X64_MODE_OFFSET:i64=24 2205const NX_STAT_X64_BLOCK_OFFSET:i64=56 2206const NX_STAT_X64_SIZE_OFFSET:i64=48 2207const NX_STAT_X64_DEVICE_OFFSET:i64=0 2208const NX_STAT_X64_INODE_OFFSET:i64=8 2209const NX_STAT_TYPE_MASK:i64=61440 2210const NX_STAT_REGULAR_FILE:i64=32768 2211func sys_fstat_fd(fd:i64,stat:*u8)->i64{ 2212 if fd<0 || (stat as i64)==0{return NX_FILE_DESCRIPTOR_INVALID} 2213 return __syscall(80,fd,stat,0,0,0,0) 2214} 2215func sys_stat_permissions(stat:*u8)->i64{ 2216 let mode:i64=(stat[NX_STAT_X64_MODE_OFFSET] as i64)+((stat[NX_STAT_X64_MODE_OFFSET+1] as i64)<<8) 2217 return mode & NX_FILE_PERMISSION_MASK 2218} 2219 2220// base64.nx -- RFC 4648 base64 encoder + decoder. 2221// 2222// Canonical: this is the substrate-wide canonical Base64 (RFC 4648 2223// §4 standard alphabet) per [[feedback-no-tool-proliferation-bit- 2224// level]]. Variants that need URL-safe alphabet (RFC 4648 §5) are 2225// candidates for ONE distinct sibling primitive nx_base64_url.nx 2226// (queued) that imports THIS file's encode/decode skeleton; all 2227// other consumers compose THIS file's encode/decode primitives. 2228// Re-implementing the Base64 alphabet or quantum-loop inline is 2229// refused. 2230// 2231// Used for: 2232// - PEM decoding of X.509 certs (thin ASCII wrapper around DER) 2233// - TLS 1.3 pre-shared key encoding 2234// - HTTP Basic auth, OAuth tokens, JWT 2235// - Web content (data: URIs, JSON-embedded bytes) 2236// 2237// Standard alphabet (RFC 4648 §4): 2238// 0-25 : A-Z 2239// 26-51 : a-z 2240// 52-61 : 0-9 2241// 62 : + 2242// 63 : / 2243// pad : = 2244// 2245// URL-safe alphabet variant (§5) swaps +/ for -_; provided as 2246// b64url_encode / b64url_decode. 2247// 2248// Invariants: 2249// B1 Input/output lengths are predictable: 2250// encode(n bytes) -> 4 * ceil(n / 3) chars 2251// decode(n chars) -> 3 * (n / 4) - padding bytes 2252// B2 Decoder rejects invalid input (non-alphabet chars) by 2253// returning a negative length. No silent skip. 2254// B3 Decoder is tolerant of missing padding (RFC 4648 §3.2 2255// permits this as "unpadded" variant). 2256// B4 Encoder is deterministic; same input -> same output. No 2257// trailing whitespace, no line breaks inserted. Callers 2258// that want MIME-style 76-char wrap do it outside. 2259// 2260// license_tier: INDEPENDENT_REDERIVE 2261// genealogy_id: international-research-sources/ietf/rfc_8446 2262// 2263 2264// nx_safety_envelope: 2265// intended_use: AUTO_APPLIED -- primitive-specific tuning queued 2266// sil_target: SIL1 2267// evidence: [bulk_applied_2026-05-16, see-file-comment-for-detail] 2268// verdict: NOT_YET_EVALUATED 2269// 2270// F-meta-4 refactor 2026-05-17: removed `import "nx_syscalls.nx"`. 2271// This file is pure -- all functions operate on caller-provided 2272// buffers + stack-local counters. Composing with any syscall layer 2273// (nx_syscalls.nx OR nx_syscalls_x86_64.nx) no longer hits the 2274// duplicate-symbol bug class. Unblocks crypto chain (nx_jwt -> 2275// nx_jose / jwk / acme / csr) for x86_64 native runtime testing. 2276 2277const B64_PAD: i64 = 0x3D // '=' 2278 2279// Encode one 6-bit index to an ASCII char. Standard alphabet. 2280func b64_enc_char(n: i64) -> i64 { 2281 let v: i64 = n & 0x3F 2282 if v < 26 { return 0x41 + v } // 'A'..'Z' 2283 if v < 52 { return 0x61 + (v - 26) } // 'a'..'z' 2284 if v < 62 { return 0x30 + (v - 52) } // '0'..'9' 2285 if v == 62 { return 0x2B } // '+' 2286 return 0x2F // '/' 2287} 2288 2289// URL-safe variant: replace + / with - _ 2290func b64url_enc_char(n: i64) -> i64 { 2291 let v: i64 = n & 0x3F 2292 if v < 26 { return 0x41 + v } 2293 if v < 52 { return 0x61 + (v - 26) } 2294 if v < 62 { return 0x30 + (v - 52) } 2295 if v == 62 { return 0x2D } // '-' 2296 return 0x5F // '_' 2297} 2298 2299// Decode one ASCII char to 6-bit value; returns -1 if invalid. 2300// Accepts either standard (+,/) or URL-safe (-,_) variants. 2301func b64_dec_char(c: i64) -> i64 { 2302 if c >= 0x41 { if c <= 0x5A { return c - 0x41 } } // A-Z 2303 if c >= 0x61 { if c <= 0x7A { return c - 0x61 + 26 } } // a-z 2304 if c >= 0x30 { if c <= 0x39 { return c - 0x30 + 52 } } // 0-9 2305 if c == 0x2B { return 62 } // + 2306 if c == 0x2F { return 63 } // / 2307 if c == 0x2D { return 62 } // - (URL-safe) 2308 if c == 0x5F { return 63 } // _ (URL-safe) 2309 return -1 2310} 2311 2312// Encode `n` bytes from `in_bytes` to `out`; returns written length. 2313// Output size: 4 * ceil(n / 3) chars. Pads with '=' to full groups. 2314func b64_encode(in_bytes: *u8, n: i64, out: *u8) -> i64 { 2315 var pos: i64 = 0 2316 var out_pos: i64 = 0 2317 while pos + 3 <= n { 2318 let b0: i64 = in_bytes[pos] 2319 let b1: i64 = in_bytes[pos + 1] 2320 let b2: i64 = in_bytes[pos + 2] 2321 out[out_pos + 0] = b64_enc_char((b0 >> 2) & 0x3F) 2322 out[out_pos + 1] = b64_enc_char(((b0 << 4) | (b1 >> 4)) & 0x3F) 2323 out[out_pos + 2] = b64_enc_char(((b1 << 2) | (b2 >> 6)) & 0x3F) 2324 out[out_pos + 3] = b64_enc_char(b2 & 0x3F) 2325 pos = pos + 3 2326 out_pos = out_pos + 4 2327 } 2328 let remain: i64 = n - pos 2329 if remain == 1 { 2330 let b0: i64 = in_bytes[pos] 2331 out[out_pos + 0] = b64_enc_char((b0 >> 2) & 0x3F) 2332 out[out_pos + 1] = b64_enc_char((b0 << 4) & 0x3F) 2333 out[out_pos + 2] = B64_PAD 2334 out[out_pos + 3] = B64_PAD 2335 out_pos = out_pos + 4 2336 } 2337 if remain == 2 { 2338 let b0: i64 = in_bytes[pos] 2339 let b1: i64 = in_bytes[pos + 1] 2340 out[out_pos + 0] = b64_enc_char((b0 >> 2) & 0x3F) 2341 out[out_pos + 1] = b64_enc_char(((b0 << 4) | (b1 >> 4)) & 0x3F) 2342 out[out_pos + 2] = b64_enc_char((b1 << 2) & 0x3F) 2343 out[out_pos + 3] = B64_PAD 2344 out_pos = out_pos + 4 2345 } 2346 return out_pos 2347} 2348 2349// Grab one sextet: return 0..63 on valid, -1 on '=' or end-of-input, 2350// -2 on any other invalid char. Advances *pos on success. 2351func b64_grab(in_chars: *u8, n: i64, pos: *i64) -> i64 { 2352 let p: i64 = *pos 2353 if p >= n { return -1 } 2354 let c: i64 = in_chars[p] 2355 if c == B64_PAD { 2356 *pos = n + 1 2357 return -1 2358 } 2359 let v: i64 = b64_dec_char(c) 2360 if v < 0 { return -2 } 2361 *pos = p + 1 2362 return v 2363} 2364 2365// Decode `n` base64 chars into raw bytes. Returns bytes written on 2366// success or -1 on invalid input. Tolerant of missing padding (B3). 2367// Whitespace is NOT skipped. 2368// 2369// F-meta-4 refactor: position counter is a stack-local; no sys_mmap. 2370func b64_decode(in_chars: *u8, n: i64, out: *u8) -> i64 { 2371 var pos: i64 = 0 2372 var out_pos: i64 = 0 2373 while pos < n { 2374 let s0: i64 = b64_grab(in_chars, n, &pos) 2375 if s0 == -2 { return -1 } 2376 if s0 < 0 { return out_pos } 2377 let s1: i64 = b64_grab(in_chars, n, &pos) 2378 if s1 == -2 { return -1 } 2379 if s1 < 0 { return -1 } // single lonely char invalid 2380 out[out_pos] = ((s0 << 2) | (s1 >> 4)) & 0xFF 2381 out_pos = out_pos + 1 2382 let s2: i64 = b64_grab(in_chars, n, &pos) 2383 if s2 == -2 { return -1 } 2384 if s2 < 0 { return out_pos } 2385 out[out_pos] = ((s1 << 4) | (s2 >> 2)) & 0xFF 2386 out_pos = out_pos + 1 2387 let s3: i64 = b64_grab(in_chars, n, &pos) 2388 if s3 == -2 { return -1 } 2389 if s3 < 0 { return out_pos } 2390 out[out_pos] = ((s2 << 6) | s3) & 0xFF 2391 out_pos = out_pos + 1 2392 } 2393 return out_pos 2394} 2395 2396// Self-test main() removed by F-meta-4 refactor (used sys_mmap; this 2397// file is now syscall-free). Round-trip smoke lives in a separate 2398// nx_base64_test.nx that imports a caller-chosen syscall layer. 2399 2400// Native packaging by artifact reference; no publication or engine-acceptance claim. 2401// nx_fsops_lib.nx -- CONSOLIDATED filesystem tool (MCP name: nx_fs, tool #4 of the 15), LIBRARY half. 2402// (Source is named nx_fsops because nx_fs.nx is the safety-enveloped file-I/O STDLIB -- a different thing.) 2403// READ-ONLY first increment: `read` (bounded file read) + `ls` (typed dir listing). Retires ssh-cat for 2404// remote reads per rule 27 (api-first, no shell plumbing). 2405// 2406// BOUNDARY DEFENSE (rule 12 -- MCP callers are EXTERNAL input): `read` REFUSES any path that matches the 2407// secret DENY-LIST: compiled-in default needles (secret/key/token/passw/.pem, matched case-insensitively 2408// against the WHOLE path) plus data-driven extras from fs_read_deny.conf (one lowercase needle per line, 2409// CWD-relative -- rule 11: policy in data, not code). The tools-api runs where key material lives; an 2410// arbitrary-read tool that could return opaque_keys.bin or tools_cap_secret.key would convert a read-cap 2411// into a key-theft primitive. Over-blocking is the SAFE failure direction for v1. 2412// WRITE/EDIT increment (2026-07-16): fsx_write (ATOMIC tmp+fsync+rename) + fsx_edit (exact-string replace 2413// with the Claude-Edit UNIQUENESS contract). Exposed as the SEPARATE tools-api name `nx_fs_write` (its own 2414// cap class per knowledge/mcp/exposure_policy.txt: read=broad, write=cap) -- the `nx_fs` name stays read-only. 2415// The write DENY is a superset of the read deny (never clobber key material) PLUS the OS device/kernel/ 2416// firmware namespace via the nx_os_fs seam (rule 26 never-brick BY CONSTRUCTION -- not config-disableable) 2417// PLUS the tool-registry escalation surface ("allowlist") PLUS data-driven extras (fs_write_deny.conf). 2418// license_tier: ORIGINAL 2419 2420// nx_fio.nx -- canonical sovereign file operations: unlink (delete) + existence check. Importable (no main). 2421// Retires Remove-Item / rm. rename is already canonical (sys_renameat in nx_syscalls). unlinkat x86_64=263 is passed 2422// DIRECTLY (the fsync-74 / fstatat-262 / unlinkat-263 precedent: a raw x86_64 number not in the rv64->x86 swap table 2423// passes through untranslated). AT_FDCWD=-100, flags=0. Returns 0 on success, -errno on failure. license_tier: ORIGINAL 2424 2425// sha256.nx -- SHA-256 in pure NishiLang (Phase G9, FIPS 180-4). 2426// 2427// Canonical: this is the substrate-wide canonical SHA-256 2428// implementation per [[feedback-no-tool-proliferation-bit-level]]. 2429// HMAC-SHA256 / HKDF-SHA256 / DRBG-SHA256 etc. compose THIS file's 2430// sha256 primitive; they're distinct primitives (different specs: 2431// FIPS 198-1 HMAC, RFC 5869 HKDF, NIST SP 800-90A DRBG) but all 2432// share THIS sha256 as their SHA-256 backbone. Re-implementing 2433// the SHA-256 K-table or round function inline is refused. 2434// 2435// license_tier: INDEPENDENT_REDERIVE 2436// genealogy_id: international-research-sources/nist/fips_180_4 2437// 2438// Used for: content-addressed build artifacts (F6), session tokens 2439// (rand.nx + sha256 = HMAC), TLS 1.3 handshake (G15), Git-style 2440// object addressing, reproducible-build attestation. 2441// 2442// Implementation follows FIPS 180-4 section 6.2 exactly -- no 2443// precomputed tables beyond the standard K[0..63] round constants. 2444// Pure i64 arithmetic; all 32-bit ops masked with 0xFFFFFFFF. 2445// 2446// API: 2447// sha256_init(*ctx) — reset a fresh Sha256 context 2448// sha256_update(*ctx, *u8 bytes, len) — feed input chunks 2449// sha256_final(*ctx, *u8 out32) — write 32-byte digest 2450// sha256_digest(*u8 bytes, len, *u8 out32) — one-shot convenience 2451// 2452// The context is ~128 bytes: 8 words of hash state + 64-byte partial 2453// block buffer + 8-byte length counter + an index. Caller allocates 2454// (stack or heap) and passes pointer. 2455// 2456// nx_safety_envelope: (schema: nishi-library/seeds/safety-critical-standards.toml) 2457// intended_use: "SHA-256 cryptographic hash -- HMAC + HKDF 2458// + content-addressed storage + digital 2459// signatures + Wheeler-DDC integrity chain" 2460// sil_target: SIL3 (integrity primitive; collision or 2461// preimage attack = signature forgery) 2462// asil_target: QM 2463// dal_target: DAL B 2464// iec_62304_class: B 2465// evidence: [no_floating_point, no_table_lookup, 2466// bit_equal_reproducible, 2467// FIPS_180-4_Sec_5_3_3_init_vector, 2468// NIST_CAVP_test_vectors_VERIFIED, 2469// constant_time_by_construction, 2470// license_tier_INDEPENDENT_REDERIVE] 2471// hazard_register: [bug-tape-length-extension-attack, 2472// bug-tape-implementation-skipping-final-block, 2473// bug-tape-state-not-cleared-after-use] 2474// residual_risk: "Length-extension attack applies to raw 2475// SHA-256. Callers MUST use HMAC-SHA-256 2476// (nx_hmac) for keyed scenarios; never raw 2477// SHA-256(key || msg). Substrate cannot 2478// enforce this from the hash primitive's 2479// boundary; it's a composition responsibility." 2480// verdict: NOT_YET_EVALUATED 2481 2482 2483// nx_bits.nx -- bit-manipulation primitives, dispatching to hardware 2484// intrinsics on supported backends with portable software fallbacks. 2485// 2486// Inspired by Hacker's Delight (Henry S. Warren Jr.) -- the canonical 2487// reference for bit-twiddling. Every soft path is BRANCHLESS or 2488// minimally-branched, FIXED-CYCLE, and CROSS-ARCH PORTABLE. 2489// 2490// Dispatch model: 2491// nx_bits_popcount64 / nx_bits_clz32 / nx_bits_ctz32 -> backend 2492// intrinsic on x86_64 (popcntq/bsrl+xor/bsfl) and rv64 with Zbb 2493// (cpop/clzw/ctzw). One machine instruction. Used by hot paths 2494// (sketches, hashing, bitmap iteration). 2495// 2496// nx_bits_popcount64_soft / nx_bits_clz32_soft / nx_bits_ctz32_soft 2497// -- pure-NishiLang SWAR + binary-search variants. Cross-arch 2498// portable to backends without bit-count opcodes. Used by paired 2499// correctness oracles and any caller targeting an exotic ISA. 2500// 2501// Substrate "get off C" trajectory: this module is pure NishiLang. 2502 2503// syscalls.nx -- alias stub. 2504// 2505// nx_syscalls.nx is the canonical syscall surface: same 15 funcs 2506// this file used to define (sys_write/read/mmap/openat/close/exit/ 2507// brk/lseek/getpid/kill/fork/execve/wait4/clone/ioctl) plus 9 2508// additions for sockets and time (sys_socket/bind/listen/accept/ 2509// connect/clock_gettime_mono/now_ms/sleep_ms/openat_append). 2510// 2511// Consumers using `import "syscalls.nx"` resolve via NishiLang's 2512// textual import splicing with path-dedup (runtime/import.nx I1): 2513// this stub splices nx_syscalls.nx once, and any other file that 2514// also imports "nx_syscalls.nx" directly gets deduped to the same 2515// canonical splice. No duplicate symbols. This fixed the 2516// nxasm_main.nx duplicate-symbol error on first link 2026-05-19. 2517// 2518// Deprecation: when every "syscalls.nx" consumer migrates to the 2519// nx_-prefixed name, delete this stub. bench/nx_import_closure.sh 2520// will catch any straggler before the build ships. 2521 2522 2523 2524 2525// === popcount FAST: dispatches to backend intrinsic ============== 2526 2527func nx_bits_popcount64(x: i64) -> i64 { 2528 return __popcnt64(x) 2529} 2530 2531func nx_bits_popcount32(x: i64) -> i64 { 2532 return __popcnt64(x & 0xFFFFFFFF) 2533} 2534 2535// === clz32 / ctz32 FAST: backend intrinsic ======================= 2536// __clz32(0) and __ctz32(0) both return 32 on both backends (x86 2537// uses a tested fallback to set the result; rv64 Zbb returns 32 by 2538// spec) so the wrapper is a thin pass-through. 2539 2540func nx_bits_clz32(x: i64) -> i64 { 2541 return __clz32(x) 2542} 2543 2544func nx_bits_ctz32(x: i64) -> i64 { 2545 return __ctz32(x) 2546} 2547 2548// 64-bit clz / ctz: composed from two 32-bit intrinsics. Until the 2549// backend grows OP_CLZ64 / OP_CTZ64 these are still ~3-instruction 2550// hot paths vs the legacy 64-iteration loops, so they replace those 2551// substrate-wide. clz(0) = 64; ctz(0) = 64. 2552 2553func nx_bits_clz64(x: i64) -> i64 { 2554 let hi: i64 = (x >> 32) & 0xFFFFFFFF 2555 if hi != 0 { return __clz32(hi) } 2556 return 32 + __clz32(x & 0xFFFFFFFF) 2557} 2558 2559func nx_bits_ctz64(x: i64) -> i64 { 2560 let lo: i64 = x & 0xFFFFFFFF 2561 if lo != 0 { return __ctz32(lo) } 2562 if x == 0 { return 64 } 2563 return 32 + __ctz32((x >> 32) & 0xFFFFFFFF) 2564} 2565 2566// === rotate left / right FAST: backend intrinsic ================ 2567// Hardware native via rolq/rorq (x86_64, 1985) and rol/ror (rv64 2568// Zbb). Mask the count to 0..63 so the substrate exposes 2569// "rotate-mod-64" semantics on both ISAs (x86_64 already masks; rv64 2570// behaviour is identical with the explicit mask). 2571 2572func nx_bits_rotl64(x: i64, n: i64) -> i64 { 2573 return __rotl64(x, n & 63) 2574} 2575 2576func nx_bits_rotr64(x: i64, n: i64) -> i64 { 2577 return __rotr64(x, n & 63) 2578} 2579 2580// 32-bit rotate (no native intrinsic emitted; we pre-mask the value 2581// to its low 32 bits so the i64 arithmetic shift right doesn't 2582// contaminate with sign bits, then mask the result back to 32 bits). 2583// ~3 ops vs 5-7 in inline rotr32/rotl32 callsites scattered across 2584// crypto modules (SHA-256, ChaCha20, MurmurHash, etc.). 2585 2586func nx_bits_rotl32(x: i64, n: i64) -> i64 { 2587 let v: i64 = x & 0xFFFFFFFF 2588 let nn: i64 = n & 31 2589 if nn == 0 { return v } 2590 return ((v << nn) | (v >> (32 - nn))) & 0xFFFFFFFF 2591} 2592 2593func nx_bits_rotr32(x: i64, n: i64) -> i64 { 2594 let v: i64 = x & 0xFFFFFFFF 2595 let nn: i64 = n & 31 2596 if nn == 0 { return v } 2597 return ((v >> nn) | (v << (32 - nn))) & 0xFFFFFFFF 2598} 2599 2600// === byte-reverse FAST: backend intrinsic ========================= 2601// bswapq (x86_64, i486 1989+, universal) and rev8 (rv64 Zbb). 1 2602// cycle vs the 13-op SWAR phrasing. Used by every endian flip, 2603// every network/header parse, SHA-256 big-endian word loads. 2604 2605func nx_bits_bswap64(x: i64) -> i64 { 2606 return __bswap64(x) 2607} 2608 2609// 32-bit byte-reverse: mask to low 32 (zero-extends the i64), bswap 2610// the whole register -- the four low bytes get reversed into the top 2611// half -- then shift down to recover them. Mask after shift to 2612// discard the sign extension on inputs where bit 31 of the bswapped 2613// low half is set (which becomes bit 63 of the 64-bit register). 2614func nx_bits_bswap32(x: i64) -> i64 { 2615 return (__bswap64(x & 0xFFFFFFFF) >> 32) & 0xFFFFFFFF 2616} 2617 2618// === SOFT fallbacks: pure NishiLang, cross-arch portable ========= 2619 2620func nx_bits_popcount64_soft(x: i64) -> i64 { 2621 var v: i64 = x 2622 v = v - ((v >> 1) & 0x5555555555555555) 2623 v = (v & 0x3333333333333333) + ((v >> 2) & 0x3333333333333333) 2624 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0F 2625 return ((v * 0x0101010101010101) >> 56) & 0xFF 2626} 2627 2628func nx_bits_popcount32_soft(x: i64) -> i64 { 2629 var v: i64 = x & 0xFFFFFFFF 2630 v = v - ((v >> 1) & 0x55555555) 2631 v = (v & 0x33333333) + ((v >> 2) & 0x33333333) 2632 v = (v + (v >> 4)) & 0x0F0F0F0F 2633 return ((v * 0x01010101) >> 24) & 0xFF 2634} 2635 2636func nx_bits_clz32_soft(x: i64) -> i64 { 2637 let lo: i64 = x & 0xFFFFFFFF 2638 if lo == 0 { return 32 } 2639 var t: i64 = lo 2640 var n: i64 = 0 2641 if (t & 0xFFFF0000) == 0 { n = n + 16; t = t << 16; t = t & 0xFFFFFFFF } 2642 if (t & 0xFF000000) == 0 { n = n + 8; t = t << 8; t = t & 0xFFFFFFFF } 2643 if (t & 0xF0000000) == 0 { n = n + 4; t = t << 4; t = t & 0xFFFFFFFF } 2644 if (t & 0xC0000000) == 0 { n = n + 2; t = t << 2; t = t & 0xFFFFFFFF } 2645 if (t & 0x80000000) == 0 { n = n + 1 } 2646 return n 2647} 2648 2649// 64-bit rotate soft fallback (pure NishiLang -- shift+or, ~5 ops). 2650// Used by paired correctness oracle and by backends without rotate 2651// opcodes. Note: shifting by 0 is the identity; explicit branch 2652// avoids the undefined-behaviour case of `x >> 64` on some ISAs. 2653 2654// The signed >> arithmetic-shifts sign bits in for negative x, so the 2655// shifted-right half must be masked to the actual m / (64-m) low bits 2656// to discard the sign extension. 2657 2658func nx_bits_rotl64_soft(x: i64, n: i64) -> i64 { 2659 let m: i64 = n & 63 2660 if m == 0 { return x } 2661 let top: i64 = (x >> (64 - m)) & ((1 << m) - 1) 2662 return (x << m) | top 2663} 2664 2665func nx_bits_rotr64_soft(x: i64, n: i64) -> i64 { 2666 let m: i64 = n & 63 2667 if m == 0 { return x } 2668 let low: i64 = (x >> m) & ((1 << (64 - m)) - 1) 2669 return low | (x << (64 - m)) 2670} 2671 2672// bswap SOFT (Hacker's Delight 7-1, 13-op SWAR). Used by paired 2673// oracle and exotic backends. 2674 2675func nx_bits_bswap64_soft(x: i64) -> i64 { 2676 var v: i64 = x 2677 v = ((v & 0x00FF00FF00FF00FF) << 8) | ((v >> 8) & 0x00FF00FF00FF00FF) 2678 v = ((v & 0x0000FFFF0000FFFF) << 16) | ((v >> 16) & 0x0000FFFF0000FFFF) 2679 v = ((v & 0x00000000FFFFFFFF) << 32) | ((v >> 32) & 0x00000000FFFFFFFF) 2680 return v 2681} 2682 2683func nx_bits_bswap32_soft(x: i64) -> i64 { 2684 let v: i64 = x & 0xFFFFFFFF 2685 let b0: i64 = (v >> 24) & 0xFF 2686 let b1: i64 = (v >> 16) & 0xFF 2687 let b2: i64 = (v >> 8) & 0xFF 2688 let b3: i64 = (v ) & 0xFF 2689 return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0 2690} 2691 2692// 32-bit rotate SOFT (identical body to FAST; no separate intrinsic 2693// path) -- kept as the named-soft for the consolidation paired-oracle 2694// convention. 2695func nx_bits_rotl32_soft(x: i64, n: i64) -> i64 { 2696 return nx_bits_rotl32(x, n) 2697} 2698func nx_bits_rotr32_soft(x: i64, n: i64) -> i64 { 2699 return nx_bits_rotr32(x, n) 2700} 2701 2702// 64-bit soft fallbacks (Knuth TAOCP 4A linear-scan). O(64) iterations 2703// in the worst case; used by the paired oracle and by exotic backends. 2704 2705func nx_bits_clz64_soft(x: i64) -> i64 { 2706 if x == 0 { return 64 } 2707 var v: i64 = x 2708 var n: i64 = 0 2709 var mask: i64 = 0x8000000000000000 2710 var done: i64 = 0 2711 while done == 0 { 2712 if (v & mask) != 0 { done = 1 } 2713 if done == 0 { 2714 n = n + 1 2715 mask = mask >> 1 2716 if mask == 0 { done = 1 } 2717 } 2718 } 2719 return n 2720} 2721 2722func nx_bits_ctz64_soft(x: i64) -> i64 { 2723 if x == 0 { return 64 } 2724 var v: i64 = x 2725 var n: i64 = 0 2726 var done: i64 = 0 2727 while done == 0 { 2728 if (v & 1) != 0 { done = 1 } 2729 if done == 0 { 2730 n = n + 1 2731 v = v >> 1 2732 if n >= 64 { done = 1 } 2733 } 2734 } 2735 return n 2736} 2737 2738func nx_bits_ctz32_soft(x: i64) -> i64 { 2739 let lo: i64 = x & 0xFFFFFFFF 2740 if lo == 0 { return 32 } 2741 var t: i64 = lo 2742 var n: i64 = 0 2743 if (t & 0x0000FFFF) == 0 { n = n + 16; t = t >> 16 } 2744 if (t & 0x000000FF) == 0 { n = n + 8; t = t >> 8 } 2745 if (t & 0x0000000F) == 0 { n = n + 4; t = t >> 4 } 2746 if (t & 0x00000003) == 0 { n = n + 2; t = t >> 2 } 2747 if (t & 0x00000001) == 0 { n = n + 1 } 2748 return n 2749} 2750 2751// === isolate lowest set bit (Hacker's Delight 2-1) ================ 2752// 2753// x & -x selects only the lowest 1-bit of x. Useful for iterating 2754// set bits in a bitmap (faster than testing each bit). 2755// for bitmap != 0: 2756// bit = nx_bits_lowest(bitmap) 2757// // process bit 2758// bitmap = bitmap ^ bit // clear it 2759 2760func nx_bits_lowest(x: i64) -> i64 { 2761 return x & (0 - x) 2762} 2763 2764// === reset lowest set bit (Hacker's Delight 2-1) ================== 2765// 2766// x & (x-1) clears the lowest 1-bit. When combined with popcount, 2767// gives O(popcount) bit-traversal loops -- faster than O(width) 2768// when the bitmap is sparse. 2769 2770func nx_bits_clear_lowest(x: i64) -> i64 { 2771 return x & (x - 1) 2772} 2773 2774// === is power of 2 (Hacker's Delight 2-1) ========================= 2775// 2776// x > 0 AND (x & (x-1)) == 0. One subtract + one and + one compare. 2777 2778func nx_bits_is_pow2(x: i64) -> i64 { 2779 if x <= 0 { return 0 } 2780 if (x & (x - 1)) == 0 { return 1 } 2781 return 0 2782} 2783 2784// === next power of 2 (Hacker's Delight 3-2) ======================= 2785// 2786// Round up to next power of 2. For x already pow2, returns x. 2787// For x = 0, returns 1. Standard "smear high bit" pattern. 2788 2789func nx_bits_next_pow2_32(x: i64) -> i64 { 2790 if x <= 1 { return 1 } 2791 var v: i64 = (x - 1) & 0xFFFFFFFF 2792 v = v | (v >> 1) 2793 v = v | (v >> 2) 2794 v = v | (v >> 4) 2795 v = v | (v >> 8) 2796 v = v | (v >> 16) 2797 return (v + 1) & 0xFFFFFFFF 2798} 2799 2800// === parity (Hacker's Delight 5-1) ================================ 2801// 2802// Returns 1 if odd number of set bits, 0 if even. Two-and-XOR 2803// reduction, branchless. 2804 2805func nx_bits_parity64(x: i64) -> i64 { 2806 var v: i64 = x 2807 v = v ^ (v >> 32) 2808 v = v ^ (v >> 16) 2809 v = v ^ (v >> 8) 2810 v = v ^ (v >> 4) 2811 return (0x6996 >> (v & 15)) & 1 2812} 2813 2814// === floor(log2(x)) =============================================== 2815// 2816// Equivalent to (31 - clz(x)) for x > 0. Returns -1 for x <= 0. 2817 2818func nx_bits_floor_log2(x: i64) -> i64 { 2819 if x <= 0 { return -1 } 2820 if x <= 0xFFFFFFFF { 2821 return 31 - nx_bits_clz32(x) 2822 } 2823 // High 32 bits set: 32 + log2(x >> 32) 2824 return 63 - nx_bits_clz32(x >> 32) 2825} 2826 2827// === bit-field extract (BMI BEXTR semantics) ====================== 2828// 2829// Extract `len` bits starting at `start` from x. 2830// Equivalent to (x >> start) & ((1 << len) - 1). 2831 2832func nx_bits_bextr(x: i64, start: i64, len: i64) -> i64 { 2833 if len <= 0 { return 0 } 2834 if len >= 64 { return x >> start } 2835 let mask: i64 = (1 << len) - 1 2836 return (x >> start) & mask 2837} 2838 2839const K_MAGIC_536870912: i64 = 536870912 2840 2841struct Sha256 { 2842 // Hash state H[0..7] as i64 (low 32 bits used). 2843 h0: i64, h1: i64, h2: i64, h3: i64, 2844 h4: i64, h5: i64, h6: i64, h7: i64, 2845 2846 // Legacy byte-packed block fields (retained for struct-size 2847 // compatibility; no longer the active buffer -- see bufptr below). 2848 b0: i64, b1: i64, b2: i64, b3: i64, 2849 b4: i64, b5: i64, b6: i64, b7: i64, 2850 2851 // Byte index into the 64-byte block (0..63) and total bits 2852 // processed (for final padding). 2853 idx: i64, 2854 bit_len: i64, 2855 2856 // Scratch buffers allocated ONCE per context in sha256_init (the perf rewrite, 2857 // 2026-06-10: kills the per-block mmap syscall + the per-round K if-chain + 2858 // the linear-scan byte access). ALL three are indexed only by PUBLIC counters 2859 // (byte position / round number 0..63 / schedule index) -- never by secret data -- 2860 // so constant_time_by_construction is preserved (no secret-indexed table access). 2861 bufptr: i64, // -> 64-byte contiguous block buffer (O(1) byte access) 2862 kptr: i64, // -> 64 round constants, materialized once from sha256_k() 2863 wptr: i64, // -> 64-word message schedule, reused every block 2864 2865 // Hardware SHA-NI scratch (the perf path, 2026-07-02). Allocated once per ctx. 2866 // k32ptr -> 64 CONTIGUOUS i32 round constants (the SHA-NI intrinsic wants packed 32-bit 2867 // K, whereas kptr above is 64 i64 for the software loop). st8ptr -> 8 CONTIGUOUS i32 2868 // working state a..h, marshalled from h0..h7 around each __sha256_ni_block call. ni_ok 2869 // caches the CPUID SHA-feature probe (1=use hardware, 0=software fallback) so cpuid runs 2870 // once per hash, not once per block. All three are indexed only by PUBLIC counters -> 2871 // constant_time_by_construction is preserved. 2872 k32ptr: i64, // -> 64 i32 round constants (packed), for the SHA-NI intrinsic 2873 st8ptr: i64, // -> 8 i32 working state a..h, marshalled around __sha256_ni_block 2874 ni_ok: i64, // 1 = CPU has SHA-NI (cpuid(7,0):EBX bit-29) -> hardware compress; 0 = software 2875} 2876 2877// Mask utilities. 2878const M32: i64 = 0xFFFFFFFF 2879 2880// Delegated to nx_bits_rotr32. SHA-256 round does 6 rotates per 2881// word * 64 rounds = 384 rotates per block. 2882func rotr32(x: i64, n: i64) -> i64 { 2883 return nx_bits_rotr32(x, n) 2884} 2885 2886func shr32(x: i64, n: i64) -> i64 { 2887 return (x >> n) & M32 2888} 2889 2890// SHA-256 round constants K[0..63]. Standard cube-roots-of-primes. 2891// We encode as a simple index -> constant lookup; each returns the 2892// i64 with the 32-bit constant in the low bits. 2893func sha256_k(i: i64) -> i64 { 2894 if i == 0 { return 0x428a2f98 } 2895 if i == 1 { return 0x71374491 } 2896 if i == 2 { return 0xb5c0fbcf } 2897 if i == 3 { return 0xe9b5dba5 } 2898 if i == 4 { return 0x3956c25b } 2899 if i == 5 { return 0x59f111f1 } 2900 if i == 6 { return 0x923f82a4 } 2901 if i == 7 { return 0xab1c5ed5 } 2902 if i == 8 { return 0xd807aa98 } 2903 if i == 9 { return 0x12835b01 } 2904 if i == 10 { return 0x243185be } 2905 if i == 11 { return 0x550c7dc3 } 2906 if i == 12 { return 0x72be5d74 } 2907 if i == 13 { return 0x80deb1fe } 2908 if i == 14 { return 0x9bdc06a7 } 2909 if i == 15 { return 0xc19bf174 } 2910 if i == 16 { return 0xe49b69c1 } 2911 if i == 17 { return 0xefbe4786 } 2912 if i == 18 { return 0x0fc19dc6 } 2913 if i == 19 { return 0x240ca1cc } 2914 if i == 20 { return 0x2de92c6f } 2915 if i == 21 { return 0x4a7484aa } 2916 if i == 22 { return 0x5cb0a9dc } 2917 if i == 23 { return 0x76f988da } 2918 if i == 24 { return 0x983e5152 } 2919 if i == 25 { return 0xa831c66d } 2920 if i == 26 { return 0xb00327c8 } 2921 if i == 27 { return 0xbf597fc7 } 2922 if i == 28 { return 0xc6e00bf3 } 2923 if i == 29 { return 0xd5a79147 } 2924 if i == 30 { return 0x06ca6351 } 2925 if i == 31 { return 0x14292967 } 2926 if i == 32 { return 0x27b70a85 } 2927 if i == 33 { return 0x2e1b2138 } 2928 if i == 34 { return 0x4d2c6dfc } 2929 if i == 35 { return 0x53380d13 } 2930 if i == 36 { return 0x650a7354 } 2931 if i == 37 { return 0x766a0abb } 2932 if i == 38 { return 0x81c2c92e } 2933 if i == 39 { return 0x92722c85 } 2934 if i == 40 { return 0xa2bfe8a1 } 2935 if i == 41 { return 0xa81a664b } 2936 if i == 42 { return 0xc24b8b70 } 2937 if i == 43 { return 0xc76c51a3 } 2938 if i == 44 { return 0xd192e819 } 2939 if i == 45 { return 0xd6990624 } 2940 if i == 46 { return 0xf40e3585 } 2941 if i == 47 { return 0x106aa070 } 2942 if i == 48 { return 0x19a4c116 } 2943 if i == 49 { return 0x1e376c08 } 2944 if i == 50 { return 0x2748774c } 2945 if i == 51 { return 0x34b0bcb5 } 2946 if i == 52 { return 0x391c0cb3 } 2947 if i == 53 { return 0x4ed8aa4a } 2948 if i == 54 { return 0x5b9cca4f } 2949 if i == 55 { return 0x682e6ff3 } 2950 if i == 56 { return 0x748f82ee } 2951 if i == 57 { return 0x78a5636f } 2952 if i == 58 { return 0x84c87814 } 2953 if i == 59 { return 0x8cc70208 } 2954 if i == 60 { return 0x90befffa } 2955 if i == 61 { return 0xa4506ceb } 2956 if i == 62 { return 0xbef9a3f7 } 2957 if i == 63 { return 0xc67178f2 } 2958 return 0 2959} 2960 2961// Access byte n (0..63) of the current block buffer. O(1) -- the buffer is contiguous 2962// (was a linear scan over 8 byte-packed fields per access; n is a public position). 2963func blk_byte(c: *Sha256, n: i64) -> i64 { 2964 let p: *u8 = c.bufptr as *u8 2965 return p[n] as i64 2966} 2967 2968// Set byte n (0..63) of the current block buffer. O(1) contiguous store. 2969func blk_set_byte(c: *Sha256, n: i64, v: i64) -> i64 { 2970 let p: *u8 = c.bufptr as *u8 2971 p[n] = (v & 0xFF) as u8 2972 return 0 2973} 2974 2975// Pack bytes [4*i .. 4*i+4) of the current block into a 32-bit 2976// big-endian word (SHA-256 spec is big-endian). 2977func blk_word(c: *Sha256, i: i64) -> i64 { 2978 let off: i64 = i * 4 2979 let b0: i64 = blk_byte(c, off + 0) 2980 let b1: i64 = blk_byte(c, off + 1) 2981 let b2: i64 = blk_byte(c, off + 2) 2982 let b3: i64 = blk_byte(c, off + 3) 2983 return ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) & M32 2984} 2985 2986// Hardware SHA-NI block compression: marshal the working state h0..h7 into the 8-word i32 2987// buffer, run one full SHA-256 block via the fused __sha256_ni_block intrinsic (which reads 2988// the 64 raw big-endian bytes at bufptr and the packed i32 K table), marshal the updated 2989// state back. Bit-identical to sha256_compress_sw (validated by nx_shani_block_probe against 2990// the software oracle for many blocks + the NIST KAT). ~hardware speed vs the ~40 MB/s soft path. 2991func sha256_compress_ni(c: *Sha256) -> i64 { 2992 let st: *i32 = c.st8ptr as *i32 2993 st[0] = (c.h0 & M32) as i32; st[1] = (c.h1 & M32) as i32 2994 st[2] = (c.h2 & M32) as i32; st[3] = (c.h3 & M32) as i32 2995 st[4] = (c.h4 & M32) as i32; st[5] = (c.h5 & M32) as i32 2996 st[6] = (c.h6 & M32) as i32; st[7] = (c.h7 & M32) as i32 2997 let _r: i64 = __sha256_ni_block(c.st8ptr as *u8, c.bufptr as *u8, c.k32ptr as *u8) 2998 c.h0 = (st[0] as i64) & M32; c.h1 = (st[1] as i64) & M32 2999 c.h2 = (st[2] as i64) & M32; c.h3 = (st[3] as i64) & M32 3000 c.h4 = (st[4] as i64) & M32; c.h5 = (st[5] as i64) & M32 3001 c.h6 = (st[6] as i64) & M32; c.h7 = (st[7] as i64) & M32 3002 return 0 3003} 3004 3005// MULTI-BLOCK SHA-NI (2026-07-02, organ-level, NO new intrinsic): marshal state -> i32 buffer ONCE, 3006// run __sha256_ni_block over `nblk` consecutive 64-byte blocks read DIRECTLY from `blocks` (state 3007// stays resident in st8ptr between calls), marshal back ONCE. Eliminates the per-block marshal AND 3008// the per-byte blk_set_byte buffering of the byte-at-a-time path -> the SHA-NI GB/s lever. Each 3009// __sha256_ni_block is the identical proven compression -> bit-identical to N separate compresses. 3010func sha256_compress_ni_blocks(c: *Sha256, blocks: i64, nblk: i64) -> i64 { 3011 let st: *i32 = c.st8ptr as *i32 3012 st[0] = (c.h0 & M32) as i32; st[1] = (c.h1 & M32) as i32 3013 st[2] = (c.h2 & M32) as i32; st[3] = (c.h3 & M32) as i32 3014 st[4] = (c.h4 & M32) as i32; st[5] = (c.h5 & M32) as i32 3015 st[6] = (c.h6 & M32) as i32; st[7] = (c.h7 & M32) as i32 3016 var b: i64 = 0 3017 while b < nblk { 3018 let blkp: i64 = blocks + b * 64 3019 let _r: i64 = __sha256_ni_block(c.st8ptr as *u8, blkp as *u8, c.k32ptr as *u8) 3020 b = b + 1 3021 } 3022 c.h0 = (st[0] as i64) & M32; c.h1 = (st[1] as i64) & M32 3023 c.h2 = (st[2] as i64) & M32; c.h3 = (st[3] as i64) & M32 3024 c.h4 = (st[4] as i64) & M32; c.h5 = (st[5] as i64) & M32 3025 c.h6 = (st[6] as i64) & M32; c.h7 = (st[7] as i64) & M32 3026 return 0 3027} 3028 3029// One compression function call: process the 64 bytes currently in the block buffer. 3030// Mutates c.h0..c.h7. Routes to hardware SHA-NI when the CPU supports it (probed once in 3031// sha256_init -> c.ni_ok); the pure-integer software path below stays the ORACLE/fallback. 3032func sha256_compress(c: *Sha256) -> i64 { 3033 if c.ni_ok == 1 { return sha256_compress_ni(c) } 3034 // Message schedule W[0..63] + round constants K[0..63] -- both per-ctx scratch 3035 // (allocated once in sha256_init), so no per-block mmap syscall and no K if-chain. 3036 let w: *i64 = c.wptr as *i64 3037 let k: *i64 = c.kptr as *i64 3038 var i: i64 = 0 3039 while i < 16 { 3040 w[i] = blk_word(c, i) 3041 i = i + 1 3042 } 3043 i = 16 3044 while i < 64 { 3045 let x15: i64 = w[i - 15] 3046 let x2: i64 = w[i - 2] 3047 // sigma0/sigma1 with the rotates inlined (was 4 rotr32 calls/iter -> pure arithmetic) 3048 let s0: i64 = (((x15 >> 7) | (x15 << 25)) ^ ((x15 >> 18) | (x15 << 14)) ^ (x15 >> 3)) & M32 3049 let s1: i64 = (((x2 >> 17) | (x2 << 15)) ^ ((x2 >> 19) | (x2 << 13)) ^ (x2 >> 10)) & M32 3050 w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & M32 3051 i = i + 1 3052 } 3053 var a: i64 = c.h0 3054 var b: i64 = c.h1 3055 var cc: i64 = c.h2 3056 var d: i64 = c.h3 3057 var e: i64 = c.h4 3058 var ff: i64 = c.h5 3059 var g: i64 = c.h6 3060 var h: i64 = c.h7 3061 i = 0 3062 while i < 64 { 3063 // Sigma1(e), Sigma0(a) with rotates inlined (was 6 rotr32 calls/round) 3064 let S1: i64 = (((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7))) & M32 3065 let ch: i64 = ((e & ff) ^ ((e ^ M32) & g)) & M32 3066 let t1: i64 = (h + S1 + ch + k[i] + w[i]) & M32 3067 let S0: i64 = (((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10))) & M32 3068 let mj: i64 = ((a & b) ^ (a & cc) ^ (b & cc)) & M32 3069 let t2: i64 = (S0 + mj) & M32 3070 h = g 3071 g = ff 3072 ff = e 3073 e = (d + t1) & M32 3074 d = cc 3075 cc = b 3076 b = a 3077 a = (t1 + t2) & M32 3078 i = i + 1 3079 } 3080 c.h0 = (c.h0 + a) & M32 3081 c.h1 = (c.h1 + b) & M32 3082 c.h2 = (c.h2 + cc) & M32 3083 c.h3 = (c.h3 + d) & M32 3084 c.h4 = (c.h4 + e) & M32 3085 c.h5 = (c.h5 + ff) & M32 3086 c.h6 = (c.h6 + g) & M32 3087 c.h7 = (c.h7 + h) & M32 3088 return 0 3089} 3090 3091// Initialise state. H[0..7] values from FIPS 180-4 section 5.3.3 3092// (first 32 bits of fractional parts of square roots of first 8 3093// primes). 3094// Shared allocation-free initializer: all five scratch pointers are supplied by the owning path. 3095func sha256_seed_allocated(c: *Sha256) -> i64 { 3096 c.h0 = 0x6a09e667; c.h1 = 0xbb67ae85; c.h2 = 0x3c6ef372; c.h3 = 0xa54ff53a 3097 c.h4 = 0x510e527f; c.h5 = 0x9b05688c; c.h6 = 0x1f83d9ab; c.h7 = 0x5be0cd19 3098 // Per-ctx scratch, allocated once (amortized over every block of this hash): 3099 // Materialize the canonical K table once (sha256_k stays the single source of the 3100 // constants -- DRY; the if-chain now runs 64x per HASH, not 64x per BLOCK). 3101 let kp: *i64 = c.kptr as *i64 3102 var i: i64 = 0 3103 while i < 64 { kp[i] = sha256_k(i); i = i + 1 } 3104 let bp: *u8 = c.bufptr as *u8 3105 i = 0 3106 while i < 64 { bp[i] = 0 as u8; i = i + 1 } 3107 c.idx = 0 3108 c.bit_len = 0 3109 3110 // ---- Hardware SHA-NI setup (additive; software path is the oracle/fallback) ---- 3111 // Packed i32 K table for the intrinsic + an 8-word i32 state marshalling buffer. 3112 let k32: *i32 = c.k32ptr as *i32 3113 i = 0 3114 while i < 64 { k32[i] = (sha256_k(i) & M32) as i32; i = i + 1 } 3115 // Probe CPU SHA support ONCE per context: cpuid(leaf=7, subleaf=0):EBX bit-29 = SHA. 3116 // 1<<29 = 0x20000000 = 536870912. Gate the compress path on this; a CPU without SHA-NI 3117 // transparently uses the software compression (byte-identical result, just slower). 3118 if (__cpuid_ebx(7, 0) & K_MAGIC_536870912) != 0 { c.ni_ok = 1 } else { c.ni_ok = 0 } 3119 return 0 3120} 3121 3122func sha256_init(c: *Sha256) -> i64 { 3123 c.bufptr = sys_mmap(64) as i64 3124 c.kptr = sys_mmap(64 * 8) as i64 3125 c.wptr = sys_mmap(64 * 8) as i64 3126 c.k32ptr = sys_mmap(64 * 4) as i64 3127 c.st8ptr = sys_mmap(8 * 4) as i64 3128 return sha256_seed_allocated(c) 3129} 3130 3131// Feed `n` bytes. Buffers partial blocks; compresses full blocks 3132// as soon as they fill. 3133func sha256_update(c: *Sha256, bytes: *u8, n: i64) -> i64 { 3134 var i: i64 = 0 3135 // BULK FAST PATH: when block-aligned (idx==0) and SHA-NI is available, process all full 64-byte 3136 // blocks straight from the input via the resident-state multi-block compress -- skipping both the 3137 // byte-at-a-time blk_set_byte buffering and the per-block state marshalling. Bit-identical. 3138 if c.idx == 0 { 3139 if c.ni_ok == 1 { 3140 let nblk: i64 = n / 64 3141 if nblk > 0 { 3142 sha256_compress_ni_blocks(c, (bytes as i64) + i, nblk) 3143 c.bit_len = c.bit_len + nblk * 512 3144 i = i + nblk * 64 3145 } 3146 } 3147 } 3148 while i < n { 3149 blk_set_byte(c, c.idx, bytes[i]) 3150 c.idx = c.idx + 1 3151 c.bit_len = c.bit_len + 8 3152 if c.idx == 64 { 3153 sha256_compress(c) 3154 c.idx = 0 3155 } 3156 i = i + 1 3157 } 3158 return 0 3159} 3160 3161// Finalise: append 0x80, pad with zeros, append 8-byte bit length, 3162// then do one or two final compressions. Writes 32 bytes to `out`. 3163func sha256_final(c: *Sha256, out: *u8) -> i64 { 3164 // Remember total bit length before padding. 3165 let total_bits: i64 = c.bit_len 3166 // Append 0x80. 3167 blk_set_byte(c, c.idx, 0x80) 3168 c.idx = c.idx + 1 3169 // If not enough room for 8-byte length in this block, pad rest 3170 // with zeros + compress. 3171 if c.idx > 56 { 3172 while c.idx < 64 { 3173 blk_set_byte(c, c.idx, 0) 3174 c.idx = c.idx + 1 3175 } 3176 sha256_compress(c) 3177 c.idx = 0 3178 } 3179 // Pad zeros up to byte 56. 3180 while c.idx < 56 { 3181 blk_set_byte(c, c.idx, 0) 3182 c.idx = c.idx + 1 3183 } 3184 // Write 64-bit big-endian length in bytes 56..63. 3185 blk_set_byte(c, 56, (total_bits >> 56) & 0xFF) 3186 blk_set_byte(c, 57, (total_bits >> 48) & 0xFF) 3187 blk_set_byte(c, 58, (total_bits >> 40) & 0xFF) 3188 blk_set_byte(c, 59, (total_bits >> 32) & 0xFF) 3189 blk_set_byte(c, 60, (total_bits >> 24) & 0xFF) 3190 blk_set_byte(c, 61, (total_bits >> 16) & 0xFF) 3191 blk_set_byte(c, 62, (total_bits >> 8) & 0xFF) 3192 blk_set_byte(c, 63, total_bits & 0xFF) 3193 sha256_compress(c) 3194 // Emit H[0..7] as big-endian 4-byte words. 3195 out[0] = (c.h0 >> 24) & 0xFF 3196 out[1] = (c.h0 >> 16) & 0xFF 3197 out[2] = (c.h0 >> 8) & 0xFF 3198 out[3] = c.h0 & 0xFF 3199 out[4] = (c.h1 >> 24) & 0xFF 3200 out[5] = (c.h1 >> 16) & 0xFF 3201 out[6] = (c.h1 >> 8) & 0xFF 3202 out[7] = c.h1 & 0xFF 3203 out[8] = (c.h2 >> 24) & 0xFF 3204 out[9] = (c.h2 >> 16) & 0xFF 3205 out[10] = (c.h2 >> 8) & 0xFF 3206 out[11] = c.h2 & 0xFF 3207 out[12] = (c.h3 >> 24) & 0xFF 3208 out[13] = (c.h3 >> 16) & 0xFF 3209 out[14] = (c.h3 >> 8) & 0xFF 3210 out[15] = c.h3 & 0xFF 3211 out[16] = (c.h4 >> 24) & 0xFF 3212 out[17] = (c.h4 >> 16) & 0xFF 3213 out[18] = (c.h4 >> 8) & 0xFF 3214 out[19] = c.h4 & 0xFF 3215 out[20] = (c.h5 >> 24) & 0xFF 3216 out[21] = (c.h5 >> 16) & 0xFF 3217 out[22] = (c.h5 >> 8) & 0xFF 3218 out[23] = c.h5 & 0xFF 3219 out[24] = (c.h6 >> 24) & 0xFF 3220 out[25] = (c.h6 >> 16) & 0xFF 3221 out[26] = (c.h6 >> 8) & 0xFF 3222 out[27] = c.h6 & 0xFF 3223 out[28] = (c.h7 >> 24) & 0xFF 3224 out[29] = (c.h7 >> 16) & 0xFF 3225 out[30] = (c.h7 >> 8) & 0xFF 3226 out[31] = c.h7 & 0xFF 3227 return 0 3228} 3229 3230// One-shot: hash `n` bytes, write 32-byte digest to `out`. 3231// Release only scratch owned by this initialized context; the caller owns c. 3232// Reset pointers so explicit cleanup is safe to repeat after completion/failure. 3233func sha256_destroy(c: *Sha256) -> i64 { 3234 if c.bufptr!=0 { sys_munmap(c.bufptr as *u8,64);c.bufptr=0 } 3235 if c.kptr!=0 { sys_munmap(c.kptr as *u8,64*8);c.kptr=0 } 3236 if c.wptr!=0 { sys_munmap(c.wptr as *u8,64*8);c.wptr=0 } 3237 if c.k32ptr!=0 { sys_munmap(c.k32ptr as *u8,64*4);c.k32ptr=0 } 3238 if c.st8ptr!=0 { sys_munmap(c.st8ptr as *u8,8*4);c.st8ptr=0 } 3239 return 0 3240} 3241 3242func sha256_digest(bytes: *u8, n: i64, out: *u8) -> i64 { 3243 let ctx_raw: *u8 = sys_mmap(__size_of(Sha256)) 3244 let ctx: *Sha256 = ctx_raw as *Sha256 3245 sha256_init(ctx) 3246 sha256_update(ctx, bytes, n) 3247 sha256_final(ctx, out) 3248 sha256_destroy(ctx) 3249 sys_munmap(ctx_raw,__size_of(Sha256)) 3250 return 0 3251} 3252 3253// Native Linux x86-64 checked observation path using the existing shared allocator owner. 3254// No cross-backend portability claim: sys_munmap currently uses the native x86-64 release ABI. 3255// Synchronous caller-owned scratch: do not publish it or pass it to forked children. 3256const SHA256_WORD_ALIGN: i64 = 8 3257const SHA256_BLOCK_BYTES: i64 = 64 3258const SHA256_ROUND_WORDS: i64 = 64 3259const SHA256_WIDE_WORD: i64 = 8 3260const SHA256_PACKED_WORD: i64 = 4 3261const SHA256_STATE_WORDS: i64 = 8 3262const SHA256_DIGEST_BYTES: i64 = 32 3263const SHA256_SIGNED_MAX: i64 = 9223372036854775807 3264const SHA256_BITS_PER_BYTE: i64 = 8 3265const SHA256_E_INPUT: i64 = 0-1 3266const SHA256_E_WORKSPACE: i64 = 0-2 3267const SHA256_E_MAPPING: i64 = 0-3 3268const SHA256_E_RELEASE: i64 = 0-4 3269 3270func sha256_context_aligned_bytes() -> i64 { 3271 return ((__size_of(Sha256)+SHA256_WORD_ALIGN-1)/SHA256_WORD_ALIGN)*SHA256_WORD_ALIGN 3272} 3273func sha256_workspace_bytes() -> i64 { 3274 return sha256_context_aligned_bytes()+SHA256_BLOCK_BYTES+2*SHA256_ROUND_WORDS*SHA256_WIDE_WORD+SHA256_ROUND_WORDS*SHA256_PACKED_WORD+SHA256_STATE_WORDS*SHA256_PACKED_WORD 3275} 3276func sha256_checked_input(bytes: *u8, n: i64, out: *u8) -> i64 { 3277 if n < 0 || n > SHA256_SIGNED_MAX/SHA256_BITS_PER_BYTE { return 0 } 3278 let source: i64=bytes as i64; let target: i64=out as i64 3279 if source < 0 || (n > 0 && source == 0) || source > SHA256_SIGNED_MAX-n { return 0 } 3280 if target <= 0 || target > SHA256_SIGNED_MAX-SHA256_DIGEST_BYTES { return 0 } 3281 return 1 3282} 3283func sha256_ranges_overlap(a: i64, an: i64, b: i64, bn: i64) -> i64 { 3284 if an == 0 || bn == 0 { return 0 }; return a < b+bn && b < a+an 3285} 3286// Borrowed scratch. Never call sha256_destroy: the buffers share one allocation. 3287// No allocation/release occurs here. Refused boundary inputs leave output unchanged. 3288// Initialize caller-owned scratch for incremental update/final; never call destroy on it. 3289func sha256_init_workspace(workspace: *u8, capacity: i64) -> i64 { 3290 let base: i64=workspace as i64; let needed: i64=sha256_workspace_bytes() 3291 if base <= 0 || capacity < needed || base > SHA256_SIGNED_MAX-needed || base%SHA256_WORD_ALIGN != 0 { return SHA256_E_WORKSPACE } 3292 let ctx: *Sha256=workspace as *Sha256; var p: i64=base+sha256_context_aligned_bytes() 3293 ctx.bufptr=p; p=p+SHA256_BLOCK_BYTES 3294 ctx.kptr=p; p=p+SHA256_ROUND_WORDS*SHA256_WIDE_WORD 3295 ctx.wptr=p; p=p+SHA256_ROUND_WORDS*SHA256_WIDE_WORD 3296 ctx.k32ptr=p; p=p+SHA256_ROUND_WORDS*SHA256_PACKED_WORD 3297 ctx.st8ptr=p 3298 return sha256_seed_allocated(ctx) 3299} 3300func sha256_digest_workspace(bytes: *u8, n: i64, out: *u8, workspace: *u8, capacity: i64) -> i64 { 3301 if sha256_checked_input(bytes,n,out) != 1 { return SHA256_E_INPUT } 3302 let base: i64=workspace as i64; let needed: i64=sha256_workspace_bytes() 3303 if base <= 0 || capacity < needed || base > SHA256_SIGNED_MAX-needed || base%SHA256_WORD_ALIGN != 0 { return SHA256_E_WORKSPACE } 3304 if sha256_ranges_overlap(base,needed,bytes as i64,n) == 1 || sha256_ranges_overlap(base,needed,out as i64,SHA256_DIGEST_BYTES) == 1 { return SHA256_E_WORKSPACE } 3305 let initialized:i64=sha256_init_workspace(workspace,capacity) 3306 if initialized != 0 { return initialized } 3307 let ctx:*Sha256=workspace as *Sha256 3308 sha256_update(ctx,bytes,n); sha256_final(ctx,out) 3309 return 0 3310} 3311// Takes ownership of an actual whole sys_mmap_shared(workspace_bytes()) result. 3312// A failed mapping leaves output unchanged. A release failure may follow computed output; 3313// callers must accept output only on0. Never supply an arena pointer or undersized mapping. 3314func sha256_digest_mapping_native(bytes: *u8, n: i64, out: *u8, mapping: i64) -> i64 { 3315 if mapping <= 0 { return SHA256_E_MAPPING } 3316 let size: i64=sha256_workspace_bytes() 3317 let result: i64=sha256_digest_workspace(bytes,n,out,mapping as *u8,size) 3318 let released: i64=sys_munmap(mapping as *u8,size) 3319 if result != 0 { return result } 3320 if released != 0 { return SHA256_E_RELEASE } 3321 return 0 3322} 3323func sha256_digest_checked_native(bytes: *u8, n: i64, out: *u8) -> i64 { 3324 if sha256_checked_input(bytes,n,out) != 1 { return SHA256_E_INPUT } 3325 // The existing shared wrapper returns errno; sys_mmap's failure policy is fatal. 3326 let mapping: i64=sys_mmap_shared(sha256_workspace_bytes()) as i64 3327 return sha256_digest_mapping_native(bytes,n,out,mapping) 3328} 3329 3330 3331// Linux syscall ABI results, not admission or retry policy. 3332const FIO_EINTR: i64 = 0 - 4 3333const FIO_EIO: i64 = 0 - 5 3334const FIO_EINVAL: i64 = 0 - 22 3335const FIO_EEXIST: i64 = 0 - 17 3336const FIO_EBADMSG: i64 = 0 - 74 // Linux ABI: artifact digest mismatch. 3337 3338struct NxFileWriteResult { 3339 stage: *u8, 3340 code: i64, 3341 written: i64, 3342 close_code: i64 3343} 3344 3345// Owns fd until close. Preserve the first failure and the independent close 3346// result; never retry close because Linux may already have released the fd. 3347func fio_write_sync_fd(fd: i64, body: *u8, n: i64, result: *NxFileWriteResult) -> i64 { 3348 result.stage = "write" as *u8 3349 result.code = 0 3350 result.written = 0 3351 result.close_code = 0 3352 if n < 0 || ((body as i64) == 0 && n > 0) { 3353 result.stage = "input" as *u8 3354 result.code = FIO_EINVAL 3355 } 3356 while result.code == 0 && result.written < n { 3357 let w: i64 = sys_write(fd, body + result.written, n - result.written) 3358 if w == FIO_EINTR { continue } 3359 if w < 0 { result.code = w; break } 3360 if w == 0 { result.code = FIO_EIO; break } 3361 result.written = result.written + w 3362 } 3363 if result.code == 0 { 3364 result.stage = "fsync" as *u8 3365 var synced: i64 = sys_fsync(fd) 3366 while synced == FIO_EINTR { synced = sys_fsync(fd) } 3367 result.code = synced 3368 } 3369 result.close_code = sys_close(fd) 3370 if result.code == 0 { 3371 result.stage = "close" as *u8 3372 result.code = result.close_code 3373 } 3374 if result.code == 0 { result.stage = "complete" as *u8 } 3375 return result.code 3376} 3377 3378// Persist the directory entry after rename. A failure here occurs after the 3379// visible update: the caller must retain that publication state in its receipt. 3380func fio_sync_parent(path: *u8, result: *NxFileWriteResult) -> i64 { 3381 var length: i64=0 3382 var slash: i64=0-1 3383 while path[length]!=(0 as u8) { if path[length]==(47 as u8) { slash=length }; length=length+1 } 3384 let parent: *u8=sys_mmap(length+2) 3385 if slash<0 { parent[0]=46 as u8; parent[1]=0 as u8 } 3386 else { 3387 var end: i64=slash 3388 if end==0 { end=1 } 3389 var i: i64=0 3390 while i<end { parent[i]=path[i]; i=i+1 } 3391 parent[end]=0 as u8 3392 } 3393 result.stage="directory-open" as *u8 3394 result.close_code=0 3395 let fd: i64=sys_openat_directory(parent) 3396 sys_munmap(parent,length+2) 3397 if fd<0 { result.code=fd; return fd } 3398 result.stage="directory-fsync" as *u8 3399 var synced: i64=sys_fsync(fd) 3400 while synced==FIO_EINTR { synced=sys_fsync(fd) } 3401 result.close_code=sys_close(fd) 3402 result.code=synced 3403 if synced==0 { result.stage="directory-close" as *u8; result.code=result.close_code } 3404 if result.code==0 { result.stage="complete" as *u8 } 3405 return result.code 3406} 3407 3408// delete a file (unlinkat). Returns 0 on success. 3409func fio_unlink(path: *u8) -> i64 { return __syscall(263, 0 - 100, path as i64, 0, 0, 0, 0) } 3410 3411// 1 if `path` exists (fstatat succeeds), else 0. 3412func fio_exists(path: *u8) -> i64 { 3413 let st: *u8 = sys_mmap(160) 3414 if sys_fstatat(path, st) == 0 { return 1 } 3415 return 0 3416} 3417 3418// A caller-owned, single-use read session. Initialize once before open; never 3419// reinitialize an open session. Atomic pathname replacement does not change its fd. 3420struct NxFileReadRegion { 3421 fd: i64, 3422 total: i64, 3423 start: i64, 3424 length: i64, 3425 read_bytes: i64, 3426 last_read: i64, 3427 stage: *u8, 3428 code: i64, 3429 close_code: i64, 3430} 3431func fio_region_init(r: *NxFileReadRegion) -> i64 { 3432 r.fd=0-1;r.total=0;r.start=0;r.length=0;r.read_bytes=0;r.last_read=0 3433 r.stage="initialized";r.code=0;r.close_code=0 3434 return 0 3435} 3436// Linux close consumes ownership even when it reports an error; do not retry it. 3437func fio_region_close(r: *NxFileReadRegion) -> i64 { 3438 if r.fd>=0 { 3439 let fd: i64=r.fd;r.fd=0-1 3440 r.close_code=sys_close(fd) 3441 if r.code==0 && r.close_code<0 { r.code=r.close_code;r.stage="close" } 3442 } 3443 return r.code 3444} 3445func fio_region_fail(r: *NxFileReadRegion,stage: *u8,code: i64) -> i64 { 3446 r.stage=stage;r.code=code 3447 fio_region_close(r) 3448 return code 3449} 3450func fio_region_open(path: *u8,r: *NxFileReadRegion) -> i64 { 3451 if r.fd>=0 { return FIO_EEXIST } 3452 fio_region_init(r) 3453 if (path as i64)==0 { return fio_region_fail(r,"path",FIO_EINVAL) } 3454 if path[0]==(0 as u8) { return fio_region_fail(r,"path",FIO_EINVAL) } 3455 r.stage="open";r.fd=sys_openat_rd(path) 3456 if r.fd<0 { r.code=r.fd;return r.code } 3457 // SEEK_END/SEEK_SET are platform ABI selectors, not transfer-size policy. 3458 let size: i64=sys_lseek(r.fd,0,2) 3459 if size<0 { return fio_region_fail(r,"size-seek",size) } 3460 r.total=size;r.length=size 3461 let back: i64=sys_lseek(r.fd,0,0) 3462 if back!=0 { if back<0 { return fio_region_fail(r,"initial-seek",back) };return fio_region_fail(r,"initial-seek",FIO_EIO) } 3463 r.stage="ready";return 0 3464} 3465// Bounds use subtraction, so start+length can never wrap before validation. 3466func fio_region_select(r: *NxFileReadRegion,start: i64,length: i64) -> i64 { 3467 if r.fd<0 || r.code!=0 || r.read_bytes!=0 { return FIO_EINVAL } 3468 if start<0 || length<0 || start>r.total { return FIO_EINVAL } 3469 if length>r.total-start { return FIO_EINVAL } 3470 let at: i64=sys_lseek(r.fd,start,0) 3471 if at!=start { if at<0 { return fio_region_fail(r,"region-seek",at) };return fio_region_fail(r,"region-seek",FIO_EIO) } 3472 r.start=start;r.length=length;r.stage="ready";return 0 3473} 3474// The caller supplies its reusable transport buffer. No allocation depends on 3475// file size; each read is at most min(buffer capacity, remaining region bytes). 3476func fio_region_next(r: *NxFileReadRegion,out: *u8,cap: i64) -> i64 { 3477 r.last_read=0 3478 if r.code!=0 { return r.code } 3479 if r.fd<0 { if r.read_bytes==r.length { return 0 };return FIO_EINVAL } 3480 if cap<=0 || (out as i64)==0 { return FIO_EINVAL } 3481 let remaining: i64=r.length-r.read_bytes 3482 if remaining==0 { r.stage="complete";return fio_region_close(r) } 3483 var want: i64=remaining;if want>cap { want=cap } 3484 r.stage="read" 3485 while r.last_read<want { 3486 let got: i64=sys_read(r.fd,out+r.last_read,want-r.last_read) 3487 if got==FIO_EINTR { continue } 3488 if got<0 { return fio_region_fail(r,"read",got) } 3489 if got==0 { return fio_region_fail(r,"read-premature-eof",FIO_EIO) } 3490 r.last_read=r.last_read+got;r.read_bytes=r.read_bytes+got 3491 } 3492 if r.read_bytes==r.length { 3493 r.stage="complete" 3494 if fio_region_close(r)<0 { return r.code } 3495 } else { r.stage="ready" } 3496 return r.last_read 3497} 3498 3499 3500// Preparation never replaces a pathname. The caller owns an exclusive candidate 3501// path and keeps it for diagnosis on failure; publication is a separate operation. 3502struct NxFilePrepareResult { 3503 stage: *u8, 3504 code: i64, 3505 copied: i64, 3506 created: i64, 3507 source_close: i64, 3508 destination_close: i64, 3509 durable: i64, 3510} 3511func fio_prepare_copy(source: *u8,candidate: *u8,mode: i64,buffer: *u8,capacity: i64,out: *NxFilePrepareResult) -> i64 { 3512 out.stage="input";out.code=FIO_EINVAL;out.copied=0;out.created=0 3513 out.source_close=0;out.destination_close=0;out.durable=0 3514 if (source as i64)==0 || (candidate as i64)==0 || (buffer as i64)==0 || capacity<=0 { return out.code } 3515 if source[0]==(0 as u8) || candidate[0]==(0 as u8) || mode<0 || mode>0x1ff { return out.code } 3516 let input: *NxFileReadRegion=sys_mmap(__size_of(NxFileReadRegion)) as *NxFileReadRegion 3517 fio_region_init(input) 3518 out.code=fio_region_open(source,input);out.stage="source-open" 3519 var fd: i64=0-1 3520 if out.code==0 { 3521 out.stage="candidate-create" 3522 fd=sys_openat_exclusive(candidate,mode) 3523 if fd<0 { out.code=fd } else { out.created=1 } 3524 } 3525 while out.code==0 && input.read_bytes<input.length { 3526 let n: i64=fio_region_next(input,buffer,capacity) 3527 if n<0 { out.stage="source-read";out.code=n;break } 3528 var sent: i64=0 3529 out.stage="candidate-write" 3530 while sent<n { 3531 let w: i64=sys_write(fd,buffer+sent,n-sent) 3532 if w==FIO_EINTR { continue } 3533 if w<0 { out.code=w;break } 3534 if w==0 { out.code=FIO_EIO;break } 3535 sent=sent+w;out.copied=out.copied+w 3536 } 3537 } 3538 fio_region_close(input);out.source_close=input.close_code 3539 if out.code==0 && input.code!=0 { out.code=input.code;out.stage="source-close" } 3540 sys_munmap(input as *u8,__size_of(NxFileReadRegion)) 3541 if out.code==0 { 3542 out.stage="candidate-mode" 3543 out.code=nx_chmod(candidate,mode) 3544 } 3545 if out.code==0 { 3546 out.stage="candidate-fsync";out.code=sys_fsync(fd) 3547 while out.code==FIO_EINTR { out.code=sys_fsync(fd) } 3548 } 3549 if fd>=0 { 3550 out.destination_close=sys_close(fd) 3551 if out.code==0 && out.destination_close!=0 { out.code=out.destination_close;out.stage="candidate-close" } 3552 } 3553 if out.code==0 { 3554 let sync: *NxFileWriteResult=sys_mmap(__size_of(NxFileWriteResult)) as *NxFileWriteResult 3555 out.code=fio_sync_parent(candidate,sync) 3556 if out.code!=0 { out.stage=sync.stage } 3557 sys_munmap(sync as *u8,__size_of(NxFileWriteResult)) 3558 } 3559 if out.code==0 { out.stage="prepared";out.durable=1 } 3560 return out.code 3561} 3562 3563 3564struct NxFilePublishResult { 3565 stage: *u8, 3566 code: i64, 3567 visible: i64, 3568 durable: i64, 3569} 3570// Caller owns the prepared candidate and target's mutation lock. Rename failure 3571// leaves live intact; sync failure AFTER rename must retain visible=1. 3572func fio_publish_candidate(candidate: *u8,live: *u8,out: *NxFilePublishResult) -> i64 { 3573 out.stage="publish-input";out.code=FIO_EINVAL;out.visible=0;out.durable=0 3574 if (candidate as i64)==0 || (live as i64)==0 { return out.code } 3575 if candidate[0]==(0 as u8) || live[0]==(0 as u8) { return out.code } 3576 out.stage="publish-rename";out.code=sys_renameat(candidate,live) 3577 if out.code!=0 { return out.code } 3578 out.visible=1 3579 let sync: *NxFileWriteResult=sys_mmap(__size_of(NxFileWriteResult)) as *NxFileWriteResult 3580 out.stage="live-directory-sync";out.code=fio_sync_parent(live,sync) 3581 // Both directory entries change if preparation used another directory. 3582 if out.code==0 { out.stage="candidate-directory-sync";out.code=fio_sync_parent(candidate,sync) } 3583 sys_munmap(sync as *u8,__size_of(NxFileWriteResult)) 3584 if out.code==0 { out.stage="published";out.durable=1 } 3585 return out.code 3586} 3587 3588 3589// Stable lock inode: never unlink the lockfile. All cooperating callers must use 3590// the same canonical live pathname in an estate-owned directory. This excludes 3591// arbitrary writers and pathname aliases from the guarantee. 3592struct NxFileTargetLock { 3593 fd: i64, 3594 stage: *u8, 3595 code: i64, 3596 unlock_code: i64, 3597 close_code: i64, 3598} 3599func fio_target_lock_init(lock: *NxFileTargetLock) -> i64 { 3600 lock.fd=0-1;lock.stage="not-started";lock.code=0;lock.unlock_code=0;lock.close_code=0 3601 return 0 3602} 3603func fio_target_lock_release(lock: *NxFileTargetLock) -> i64 { 3604 if lock.fd>=0 { 3605 let fd: i64=lock.fd;lock.fd=0-1 3606 lock.unlock_code=sys_flock(fd,SYS_LOCK_UN) 3607 lock.close_code=sys_close(fd) 3608 if lock.code==0 && lock.unlock_code!=0 { lock.code=lock.unlock_code;lock.stage="target-unlock" } 3609 if lock.code==0 && lock.close_code!=0 { lock.code=lock.close_code;lock.stage="target-lock-close" } 3610 if lock.code==0 { lock.stage="released" } 3611 } 3612 return lock.code 3613} 3614func fio_target_lock_acquire(live: *u8,lock: *NxFileTargetLock) -> i64 { 3615 if lock.fd>=0 { return FIO_EEXIST } 3616 fio_target_lock_init(lock) 3617 lock.stage="target-lock-input";lock.code=FIO_EINVAL 3618 if (live as i64)==0 { return lock.code } 3619 var n: i64=0;while live[n]!=(0 as u8) { n=n+1 } 3620 if n==0 { return lock.code } 3621 let suffix: *u8=".install.lock" 3622 var extra: i64=0;while suffix[extra]!=(0 as u8) { extra=extra+1 } 3623 let bytes: i64=n+extra+1 3624 if bytes<=n { return lock.code } 3625 let path: *u8=sys_mmap(bytes) 3626 if (path as i64)<0 { lock.stage="target-lock-allocation";lock.code=path as i64;return lock.code } 3627 var i: i64=0;while i<n { path[i]=live[i];i=i+1 } 3628 i=0;while i<extra { path[n+i]=suffix[i];i=i+1 };path[n+extra]=0 as u8 3629 lock.stage="target-lock-open";lock.fd=sys_openat_lock(path) 3630 sys_munmap(path,bytes) 3631 if lock.fd<0 { lock.code=lock.fd;return lock.code } 3632 lock.stage="target-lock-acquire";lock.code=sys_flock(lock.fd,SYS_LOCK_EX | SYS_LOCK_NB) 3633 if lock.code!=0 { 3634 let fd: i64=lock.fd;lock.fd=0-1;lock.close_code=sys_close(fd) 3635 return lock.code 3636 } 3637 lock.stage="held";return 0 3638} 3639struct NxFileReplaceResult { 3640 stage: *u8, 3641 code: i64, 3642 candidate: NxFilePrepareResult, 3643 backup: NxFilePrepareResult, 3644 publication: NxFilePublishResult, 3645 lock: NxFileTargetLock, 3646} 3647// Internal locked body. Source remains an immutable artifact; history paths 3648// are exclusive. The public replacement entry points acquire the target lock. 3649func fio_replace_owned(source: *u8,live: *u8,candidate: *u8,backup: *u8,mode: i64,buffer: *u8,capacity: i64,expected_candidate: *u8,expected_live: *u8,out: *NxFileReplaceResult) -> i64 { 3650 out.stage="prepare-candidate" 3651 out.backup.created=0;out.backup.durable=0;out.backup.copied=0;out.backup.code=0 3652 out.backup.stage="not-started";out.backup.source_close=0;out.backup.destination_close=0 3653 out.publication.stage="not-started";out.publication.code=0;out.publication.visible=0;out.publication.durable=0 3654 out.code=fio_prepare_copy(source,candidate,mode,buffer,capacity,&out.candidate) 3655 if out.code!=0 { return out.code } 3656 if (expected_candidate as i64)!=0 { 3657 out.stage="candidate-identity" 3658 out.code=fio_verify_sha256(candidate,expected_candidate,buffer,capacity) 3659 if out.code!=0 { return out.code } 3660 } 3661 out.stage="prepare-backup" 3662 out.code=fio_prepare_copy(live,backup,mode,buffer,capacity,&out.backup) 3663 if out.code!=0 { return out.code } 3664 if (expected_live as i64)!=0 { 3665 out.stage="live-identity" 3666 out.code=fio_verify_sha256(backup,expected_live,buffer,capacity) 3667 if out.code!=0 { return out.code } 3668 } 3669 out.stage="publish" 3670 out.code=fio_publish_candidate(candidate,live,&out.publication) 3671 if out.code==0 { out.stage="complete" } 3672 return out.code 3673} 3674 3675func fio_replace_init(out: *NxFileReplaceResult) -> i64 { 3676 let raw: *u8=out as *u8;var i: i64=0 3677 while i<__size_of(NxFileReplaceResult) { raw[i]=0 as u8;i=i+1 } 3678 out.stage="not-started";out.candidate.stage="not-started" 3679 out.backup.stage="not-started";out.publication.stage="not-started" 3680 fio_target_lock_init(&out.lock);return 0 3681} 3682func fio_replace_core(source: *u8,live: *u8,candidate: *u8,backup: *u8,mode: i64,buffer: *u8,capacity: i64,expected_candidate: *u8,expected_live: *u8,out: *NxFileReplaceResult) -> i64 { 3683 fio_replace_init(out) 3684 out.code=fio_target_lock_acquire(live,&out.lock) 3685 if out.code!=0 { out.stage=out.lock.stage;return out.code } 3686 fio_replace_owned(source,live,candidate,backup,mode,buffer,capacity,expected_candidate,expected_live,out) 3687 let released: i64=fio_target_lock_release(&out.lock) 3688 if out.code==0 && released!=0 { out.code=released;out.stage=out.lock.stage } 3689 return out.code 3690} 3691func fio_replace_with_backup(source: *u8,live: *u8,candidate: *u8,backup: *u8,mode: i64,buffer: *u8,capacity: i64,out: *NxFileReplaceResult) -> i64 { 3692 return fio_replace_core(source,live,candidate,backup,mode,buffer,capacity,0 as *u8,0 as *u8,out) 3693} 3694 3695func fio_replace_verified(source: *u8,live: *u8,candidate: *u8,backup: *u8,mode: i64,buffer: *u8,capacity: i64,expected_candidate: *u8,expected_live: *u8,out: *NxFileReplaceResult) -> i64 { 3696 if (expected_candidate as i64)==0 || (expected_live as i64)==0 { 3697 fio_replace_init(out) 3698 out.stage="identity-input";out.code=FIO_EINVAL 3699 out.candidate.stage="not-started";out.backup.stage="not-started";out.publication.stage="not-started" 3700 return out.code 3701 } 3702 return fio_replace_core(source,live,candidate,backup,mode,buffer,capacity,expected_candidate,expected_live,out) 3703} 3704 3705 3706// Digest comparison is over the prepared bytes, before any live replacement. 3707// Expected points to a SHA-256 digest (32 bytes), not a filename or size. 3708func fio_verify_sha256(path: *u8,expected: *u8,buffer: *u8,capacity: i64) -> i64 { 3709 if (expected as i64)==0 || (buffer as i64)==0 || capacity<=0 { return FIO_EINVAL } 3710 let input: *NxFileReadRegion=sys_mmap(__size_of(NxFileReadRegion)) as *NxFileReadRegion 3711 fio_region_init(input) 3712 var rc: i64=fio_region_open(path,input) 3713 let ctx: *Sha256=sys_mmap(__size_of(Sha256)) as *Sha256 3714 sha256_init(ctx) 3715 while rc==0 && input.read_bytes<input.length { 3716 let n: i64=fio_region_next(input,buffer,capacity) 3717 if n<0 { rc=n;break } 3718 sha256_update(ctx,buffer,n) 3719 } 3720 fio_region_close(input) 3721 if rc==0 { rc=input.code } 3722 if rc==0 { 3723 let actual: *u8=sys_mmap(32) 3724 sha256_final(ctx,actual) 3725 var i: i64=0;var differs: i64=0 3726 while i<32 { differs=differs | ((actual[i] as i64) ^ (expected[i] as i64));i=i+1 } 3727 if differs!=0 { rc=FIO_EBADMSG } 3728 sys_munmap(actual,32) 3729 } 3730 sha256_destroy(ctx);sys_munmap(ctx as *u8,__size_of(Sha256)) 3731 sys_munmap(input as *u8,__size_of(NxFileReadRegion)) 3732 return rc 3733} 3734 3735// nx_itoa_lib.nx -- THE shared integer->decimal emitter. ONE copy, so the corpus stops retyping it. 3736// 3737// LIFTED, NEVER COPIED (2026-07-31, debt 1785557603). ccz_cat_num was already correct, already 3738// MSB-first, already zero-allocation, and already had 10+ callers -- it was simply IMPRISONED inside 3739// nx_crashresume_census_core.nx, a crash-resume census organ. Seven files imported an entire census 3740// just to print an integer. That import cost, NOT ignorance of the primitive, is why ~87 sites 3741// hand-rolled their own. LAW: WHEN A CORRECT PRIMITIVE IS RETYPED, MEASURE ITS IMPORT COST BEFORE 3742// BLAMING DISCOVERABILITY -- people do not retype what is CHEAP to reach. 3743// 3744// THE LEAK WAS NEVER IN THE PRIMITIVE, IT WAS IN THE MISSING WRAPPER. ccz_cat_num allocates nothing. 3745// What every clone hand-rolled was the fd shim around it, e.g. nx_lock_reap_gate.g_putn: 3746// let b: *u8 = sys_mmap(32); let e: i64 = ccz_cat_num(b, 0, v); sys_write(1, b, e); return 0 3747// -- one mmap per call, never freed. nxi_fd below is that shim, written ONCE and always freeing. 3748// 3749// The census now imports THIS file; NishiLang import is transitive (verified: nx_lock_reap_gate 3750// imports only nx_syscalls + nx_lock_reap_core, and resolves ccz_cat_num through the core), so all 3751// existing callers keep resolving with no edit. 3752// 3753// LAYERING: lives in runtime/ so BOTH runtime/ and _hdl_build/ can import it. 3754// license_tier: ORIGINAL No hw writes (Rule 26). 3755 3756// MSB-FIRST (2026-07-31, debt 1785516350): the previous body built digits LEAST-significant first, 3757// which comes out BACKWARDS and therefore needed a sys_mmap(32) scratch buffer to reverse through -- 3758// and never freed it, leaking a page per call across 12+ importers. Emitting MOST-significant first 3759// needs no buffer at all, so this now ALLOCATES NOTHING. Output bytes and the NUL-terminate contract 3760// are unchanged; this is a rewrite of the algorithm, not a sprinkled munmap (rule 3). 3761const CCZ_ASCII_0: i64 = 48 3762const CCZ_MINUS: i64 = 45 3763const CCZ_DEC: i64 = 10 3764func ccz_cat_num(buf: *u8, off: i64, v: i64) -> i64 { 3765 var o: i64 = off 3766 var m: i64 = v 3767 if m == 0 { buf[o] = CCZ_ASCII_0 as u8; o = o + 1; buf[o] = 0 as u8; return o } 3768 if m < 0 { buf[o] = CCZ_MINUS as u8; o = o + 1; m = 0 - m } 3769 // i64 MIN negates to itself and stays negative; clamp rather than loop forever on the digit walk. 3770 if m < 0 { m = 0 } 3771 var pw: i64 = 1 3772 while m / pw >= CCZ_DEC { pw = pw * CCZ_DEC } 3773 while pw > 0 { 3774 buf[o] = (CCZ_ASCII_0 + ((m / pw) % CCZ_DEC)) as u8 3775 o = o + 1 3776 pw = pw / CCZ_DEC 3777 } 3778 buf[o] = 0 as u8 3779 return o 3780} 3781 3782// max i64 is 19 digits + sign + the NUL ccz_cat_num writes; 24 leaves slack, well under one page. 3783const NXI_BUF: i64 = 24 3784const NXI_STDOUT: i64 = 1 3785const NXI_STDERR: i64 = 2 3786 3787// Write v as decimal to fd. ONE buffer, ALWAYS freed -- the balanced shape nx_mmapbal certifies. 3788// This is the drop-in for every hand-rolled putn/gn/wn/pn clone. Returns bytes written. 3789func nxi_fd(fd: i64, v: i64) -> i64 { 3790 let b: *u8 = sys_mmap(NXI_BUF) 3791 let n: i64 = ccz_cat_num(b, 0, v) 3792 sys_write(fd, b, n) 3793 sys_munmap(b, NXI_BUF) 3794 return n 3795} 3796 3797func nxi_out(v: i64) -> i64 { return nxi_fd(NXI_STDOUT, v) } 3798func nxi_err(v: i64) -> i64 { return nxi_fd(NXI_STDERR, v) } 3799 3800// NUL-FREE buffer form (2026-07-31). ccz_cat_num NUL-terminates -- it writes dst[ret]=0 -- which is 3801// right for its own callers but WRONG as a drop-in for the large clone family whose contract is 3802// "append digits, touch nothing else, return the new offset". Pointing those at ccz_cat_num would 3803// write one byte past the returned offset, and a clone that patches a number into the MIDDLE of an 3804// already-built buffer would have the next byte clobbered. nx_office_serve.of_catn alone has 60 3805// call sites, none of them audited for that. 3806// So the lib carries BOTH contracts explicitly rather than making every migrator guess: 3807// ccz_cat_num -> digits + NUL, returns the offset BEFORE the NUL 3808// nxi_buf -> digits only, returns the offset AFTER them, ZERO bytes touched beyond 3809// Both are MSB-first and allocate NOTHING. Constants are the CCZ_ ones lifted with ccz_cat_num. 3810func nxi_buf(dst: *u8, off: i64, v: i64) -> i64 { 3811 var p: i64 = off 3812 var m: i64 = v 3813 if m < 0 { 3814 dst[p] = CCZ_MINUS as u8 3815 p = p + 1 3816 m = 0 - m 3817 } 3818 // i64 MIN negates to ITSELF and stays negative. Clamp to 0 rather than looping forever or 3819 // emitting garbage -- a documented bound, never a silent wrong number. 3820 if m < 0 { m = 0 } 3821 var pw: i64 = 1 3822 while m / pw >= CCZ_DEC { pw = pw * CCZ_DEC } 3823 while pw > 0 { 3824 dst[p] = (CCZ_ASCII_0 + ((m / pw) % CCZ_DEC)) as u8 3825 p = p + 1 3826 pw = pw / CCZ_DEC 3827 } 3828 return p 3829} 3830 3831// nx_vsz_watchdog_core.nx -- importable CORE of the VSZ watchdog (the permanent fix for outage MODE 2: 3832// mmap-per-request daemons never munmap -> VSZ balloons (mgmt hit ~160GB) -> fork() fails -> child-exec 3833// SILENTLY EMPTY while /api/health stays 200; see reference-mgmt-api-outage-tmp-log-rootcause-2026-07-12). 3834// The watchdog DECIDES DEATH ONLY: it kills a conf-listed daemon whose VSZ crossed its threshold; RESPAWN 3835// stays 100% the nx_hostctl guard's job (single responsibility, no dueling supervisors). FAIL-SAFE BY 3836// CONSTRUCTION: no conf file -> INERT; unreadable /proc -> skip; cooldown suppresses kill-storms; pid<=300 3837// and self are never killed. Pure decision funcs here (gate-locked); the /proc walk + kill live in the CLI. 3838// license_tier: ORIGINAL 3839 3840 3841const VW_PROC_PATH_CAP: i64 = 256 // /proc/<pid>/status path buffer 3842const VW_STATUS_BUF: i64 = 8192 // /proc status read buffer 3843const VW_PTR_CELL: i64 = 16 // 2-i64 scratch cell (vw_num_at end-pointer out-param) 3844 3845func vw_slen(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } return n } 3846 3847// substring containment (hostctl's hc_contains idiom; needle has no NUL so cmdline NUL separators are safe). 3848func vw_contains(hay: *u8, hn: i64, needle: *u8, nn: i64) -> i64 { 3849 if nn == 0 { return 0 } 3850 var i: i64 = 0 3851 while i + nn <= hn { 3852 var k: i64 = 0 3853 var ok: i64 = 1 3854 while k < nn { if hay[i+k] != needle[k] { ok = 0; k = nn } k = k + 1 } 3855 if ok == 1 { return 1 } 3856 i = i + 1 3857 } 3858 return 0 3859} 3860 3861// parse leading unsigned decimal from s[off..n): value, or -1 if no digit at off. end offset in endp[0]. 3862func vw_num_at(s: *u8, n: i64, off: i64, endp: *i64) -> i64 { 3863 var v: i64 = 0 3864 var any: i64 = 0 3865 var i: i64 = off 3866 var go: i64 = 1 3867 while go == 1 { 3868 go = 0 3869 if i < n { let c: i64 = s[i] as i64; if c >= 48 { if c <= 57 { v = v*10 + (c-48); any = 1; i = i + 1; go = 1 } } } 3870 } 3871 endp[0] = i 3872 if any == 0 { return 0 - 1 } 3873 return v 3874} 3875 3876// parse one conf line buf[ls..le): "<needle> <max_gb>". Writes NUL after the needle IN PLACE, returns gb 3877// (>=1) with needle start in outp[0], or -1 for comment/blank/malformed (row dropped, fail-safe). 3878func vw_parse_row(buf: *u8, ls: i64, le: i64, outp: *i64) -> i64 { 3879 var i: i64 = ls 3880 var go: i64 = 1 3881 while go == 1 { go = 0; if i < le { let c: i64 = buf[i] as i64; if c == 32 { i = i + 1; go = 1 } else { if c == 9 { i = i + 1; go = 1 } } } } 3882 if i >= le { return 0 - 1 } 3883 if buf[i] == (35 as u8) { return 0 - 1 } // '#' comment 3884 let nstart: i64 = i 3885 go = 1 3886 while go == 1 { go = 0; if i < le { let c: i64 = buf[i] as i64; if c != 32 { if c != 9 { i = i + 1; go = 1 } } } } 3887 if i >= le { return 0 - 1 } // no separator -> malformed 3888 let nend: i64 = i 3889 let ep: *i64 = sys_mmap(VW_PTR_CELL) as *i64 3890 var j: i64 = i 3891 go = 1 3892 while go == 1 { go = 0; if j < le { let c: i64 = buf[j] as i64; if c == 32 { j = j + 1; go = 1 } else { if c == 9 { j = j + 1; go = 1 } } } } 3893 let gb: i64 = vw_num_at(buf, le, j, ep) 3894 sys_munmap(ep as *u8, VW_PTR_CELL) // leak-free: ep (the end-ptr out-param) was leaked per row (the ep-out-param class my leak-checker flagged) 3895 if gb < 1 { return 0 - 1 } // gb<1 -> inert row (never a 0-threshold kill-everything) 3896 buf[nend] = 0 as u8 // NUL-terminate the needle in place 3897 outp[0] = nstart 3898 return gb 3899} 3900 3901// parse the kB value of an arbitrary "<Label>:" row out of a /proc status text. -1 absent/unreadable. 3902// Generalized so VmSize (address space) and VmRSS (resident -- the heap-leak meter VSZ can hide) share ONE 3903// parser (DRY; NEVER kill on parse failure). 3904func vw_status_kb(buf: *u8, n: i64, pat: *u8) -> i64 { 3905 let pl: i64 = vw_slen(pat) 3906 var i: i64 = 0 3907 while i + pl <= n { 3908 var k: i64 = 0 3909 var ok: i64 = 1 3910 while k < pl { if buf[i+k] != pat[k] { ok = 0; k = pl } k = k + 1 } 3911 if ok == 1 { 3912 var j: i64 = i + pl 3913 var go: i64 = 1 3914 while go == 1 { go = 0; if j < n { let c: i64 = buf[j] as i64; if c == 32 { j = j + 1; go = 1 } else { if c == 9 { j = j + 1; go = 1 } } } } 3915 let ep: *i64 = sys_mmap(VW_PTR_CELL) as *i64 3916 let r: i64 = vw_num_at(buf, n, j, ep) 3917 sys_munmap(ep as *u8, VW_PTR_CELL) // leak-free: ep was mmap'd-and-leaked per call (the ep-out-param leak class) 3918 return r 3919 } 3920 i = i + 1 3921 } 3922 return 0 - 1 3923} 3924 3925// THE kill decision. 1 only when: threshold sane (gb>=1) AND vsz known (kb>0) AND over threshold AND the 3926// per-row cooldown expired. Everything else -> 0 (fail-safe). 3927func vw_should_kill(vsz_kb: i64, max_gb: i64, last_kill_s: i64, now_s: i64, cooldown_s: i64) -> i64 { 3928 if max_gb < 1 { return 0 } 3929 if vsz_kb <= 0 { return 0 } 3930 if vsz_kb <= max_gb * 1048576 { return 0 } 3931 if now_s - last_kill_s < cooldown_s { return 0 } 3932 return 1 3933} 3934 3935// bounded whole-file read. -1 absent. 3936func vw_read(path: *u8, buf: *u8, cap: i64) -> i64 { 3937 let fd: i64 = sys_openat_rd(path) 3938 if fd < 0 { return 0 - 1 } 3939 var tot: i64 = 0 3940 var n: i64 = sys_read(fd, buf, cap) 3941 while n > 0 { tot = tot + n; if tot >= cap { n = 0 } else { n = sys_read(fd, (buf as i64 + tot) as *u8, cap - tot) } } 3942 sys_close(fd) 3943 return tot 3944} 3945 3946// monotonic seconds (persists across one-shot runs within a boot -- exactly the cooldown scope we want). 3947func vw_now_s() -> i64 { let ts: *i64 = sys_mmap(16) as *i64; sys_clock_gettime_mono(ts); return ts[0] } 3948 3949// self pid via /proc/self/stat leading digits (no getpid syscall-number risk). 3950func vw_selfpid() -> i64 { 3951 let b: *u8 = sys_mmap(VW_PROC_PATH_CAP) 3952 let n: i64 = vw_read("/proc/self/stat" as *u8, b, VW_PROC_PATH_CAP - 1) 3953 if n <= 0 { sys_munmap(b, VW_PROC_PATH_CAP); return 0 - 1 } 3954 let ep: *i64 = sys_mmap(VW_PTR_CELL) as *i64 3955 let r: i64 = vw_num_at(b, n, 0, ep) 3956 sys_munmap(b, VW_PROC_PATH_CAP); sys_munmap(ep, VW_PTR_CELL) // leak-free (b + ep were leaked per call) 3957 return r 3958} 3959 3960// back-compat: the VmSize row (a sibling gate + vw_status_kb_of call this by name) 3961func vw_vmsize_parse(buf: *u8, n: i64) -> i64 { return vw_status_kb(buf, n, "VmSize:" as *u8) } 3962// kB of an arbitrary "<label>:" status row for a /proc entry named by DIRECTORY STRING (pid or "self"). 3963// -1 unreadable. LEAK-FREE (munmaps path+b on every return). Generalized so VmSize (address space) and 3964// VmRSS (resident heap -- the leak class an arena hides from VSZ) share ONE reader. 3965func vw_status_kb_of(dirname: *u8, label: *u8) -> i64 { 3966 let path: *u8 = sys_mmap(VW_PROC_PATH_CAP) 3967 var o: i64 = 0 3968 let pre: *u8 = "/proc/" as *u8 3969 var a: i64 = 0 3970 while pre[a] != (0 as u8) { path[o] = pre[a]; o = o + 1; a = a + 1 } 3971 a = 0 3972 while dirname[a] != (0 as u8) { path[o] = dirname[a]; o = o + 1; a = a + 1 } 3973 let suf: *u8 = "/status" as *u8 3974 a = 0 3975 while suf[a] != (0 as u8) { path[o] = suf[a]; o = o + 1; a = a + 1 } 3976 path[o] = 0 as u8 3977 let b: *u8 = sys_mmap(VW_STATUS_BUF) 3978 let n: i64 = vw_read(path, b, VW_STATUS_BUF - 1) 3979 if n <= 0 { sys_munmap(path, VW_PROC_PATH_CAP); sys_munmap(b, VW_STATUS_BUF); return 0 - 1 } 3980 let r: i64 = vw_status_kb(b, n, label) 3981 sys_munmap(path, VW_PROC_PATH_CAP) 3982 sys_munmap(b, VW_STATUS_BUF) 3983 return r 3984} 3985// VmSize kB (back-compat; leak_check's memory meter). -1 unreadable. 3986func vw_vmsize_kb_of(dirname: *u8) -> i64 { return vw_status_kb_of(dirname, "VmSize:" as *u8) } 3987// VmRSS kB (resident set -- the heap-leak meter VmSize can hide in an arena). 3988func vw_rss_kb_of(dirname: *u8) -> i64 { return vw_status_kb_of(dirname, "VmRSS:" as *u8) } 3989 3990// nx_os_fs.nx -- OS FILESYSTEM-NAMESPACE SEAM (the write-safety half; sibling of nx_os_proc.nx). 3991// Answers ONE question for the IO layer: is this path in the OS's device/kernel/firmware namespace, 3992// where a file write could touch hardware or kernel state? Rule 26 (never-brick) demands the answer 3993// be BY CONSTRUCTION -- compiled in, not config-disableable -- so the deny lives here, in code, and 3994// callers cannot toggle it off with a conf line. 3995// 3996// LINUX BACKEND (current): the kernel exposes devices/firmware knobs as FILES under /dev, /sys, /proc 3997// (e.g. /sys/firmware/efi/efivars -- an errant write there can brick a board; /dev/sda -- raw disk). 3998// A path is write-forbidden iff it IS or is UNDER one of those roots. 3999// 4000// NISHIOS-NATIVE (target): NishiOS has no ambient device files -- device access is capability-routed 4001// through typed channels, so the ambient-namespace hazard class does not exist; the native backend 4002// returns forbid only for its reserved kernel-object namespace. This file is the SOURCE-SWAP seam 4003// (same contract, swapped backend), exactly like nx_os_proc.nx. license_tier: ORIGINAL 4004 4005 4006const OSF_SLASH: i64 = 47 // '/' -- path separator (namespace-boundary test) 4007 4008// is path EXACTLY root or UNDER root/ ? (blocks "/dev" and "/dev/null", not "/devdata") 4009func osf_under(path: *u8, root: *u8) -> i64 { 4010 var i: i64 = 0 4011 while root[i] != (0 as u8) { 4012 if path[i] != root[i] { return 0 } 4013 i = i + 1 4014 } 4015 if path[i] == (0 as u8) { return 1 } // exactly the root 4016 if path[i] == (OSF_SLASH as u8) { return 1 } // inside the root 4017 return 0 4018} 4019// WRITE-FORBIDDEN check: 1 = the OS device/kernel/firmware namespace, never writable through the IO layer. 4020func osf_write_forbidden(path: *u8) -> i64 { 4021 if osf_under(path, "/dev" as *u8) == 1 { return 1 } 4022 if osf_under(path, "/sys" as *u8) == 1 { return 1 } 4023 if osf_under(path, "/proc" as *u8) == 1 { return 1 } 4024 return 0 4025} 4026 4027// nx_os_proc.nx -- OS PROCESS-INTROSPECTION abstraction (the PORTABILITY SEAM). THE ONE place OS-specific 4028// process access lives, so every tool above it (nx_heal, ...) stays OS-AGNOSTIC + portable. Interop by 4029// construction: ONE source compiles to BOTH backends via the @ifdef target guard -- 4030// LINUX backend = procfs (/proc/<pid>/{stat,cmdline}, getdents on /proc) [current NAS deploy] 4031// NISHIOS backend = native process table (@ifdef TARGET_NISHI seam) -- superior: a direct kernel 4032// query, NO text-parsing of /proc, NO USER_HZ guesswork. FAILS LOUD until wired, 4033// so a NishiOS build never silently inherits Linux assumptions. 4034// LAW (portability): NEVER scatter raw /proc, /sys, /dev, or hardcoded syscall numbers through the LOGIC 4035// layer -- put OS-specifics behind an nx_os_* seam like this one. The sovereign core (seg_store, tool 4036// logic) already only touches nx_syscalls (ABI-abstracted); this extends the same discipline to OS features. 4037// license_tier: ORIGINAL 4038 4039 4040const OSP_HZ_LINUX: i64 = 100 // Linux USER_HZ: /proc/<pid>/stat starttime ticks/sec 4041const OSP_PATH_CAP: i64 = 256 4042const OSP_RD_CAP: i64 = 4096 4043const OSP_STAT_CAP: i64 = 262144 // /proc/stat whole-file read cap (btime scan) 4044const OSP_DENT_BUF: i64 = 65536 // getdents64 batch buffer (proven sizing) 4045const OSP_F_PPID: i64 = 2 // /proc/<pid>/stat field after ')': state=1 ppid=2 ... utime=12 stime=13 ... starttime=20 4046const OSP_F_START: i64 = 20 4047const OSP_F_UTIME: i64 = 12 // user-mode CPU ticks (cumulative) 4048const OSP_F_STIME: i64 = 13 // kernel-mode CPU ticks (cumulative) 4049const OSP_ASCII_0: i64 = 48 4050const OSP_ASCII_9: i64 = 57 4051const OSP_SP: i64 = 32 4052const OSP_NL: i64 = 10 4053const OSP_RP: i64 = 41 // ')' 4054const OSP_SLASH: i64 = 47 4055const OSP_NUL: i64 = 0 4056const OSP_SENTINEL: i64 = 0 - 1 // "not available on this OS backend" 4057 4058func osp_slen(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (OSP_NUL as u8) { n = n + 1 } return n } 4059// pid integer -> decimal string in out; return len 4060func osp_itoa(v: i64, out: *u8) -> i64 { 4061 if v == 0 { out[0] = OSP_ASCII_0 as u8; out[1] = 0 as u8; return 1 } 4062 let t: *u8 = sys_mmap(24); var m: i64 = v; var k: i64 = 0 4063 while m > 0 { t[k] = (OSP_ASCII_0 + (m % 10)) as u8; m = m / 10; k = k + 1 } 4064 var i: i64 = 0 4065 while i < k { out[i] = t[k-1-i]; i = i + 1 } 4066 out[k] = 0 as u8 4067 return k 4068} 4069// parse leading integer at buf[off..]; endp[0] = position of the FIRST non-digit (NOT n) so a caller 4070// walking fields can resume there. BUG-FIX 2026-07-16: the old `i = n` break jumped to end-of-buffer, 4071// so osp_stat_field skipped every field after the first non-numeric one (the state char) and never 4072// reached starttime (field 20) -- diagnose then dropped every real process. 4073func osp_num(buf: *u8, n: i64, off: i64, endp: *i64) -> i64 { 4074 var v: i64 = 0; var i: i64 = off; var any: i64 = 0; var go: i64 = 1 4075 while go == 1 { 4076 go = 0 4077 if i < n { let c: i64 = buf[i] as i64; if c >= OSP_ASCII_0 { if c <= OSP_ASCII_9 { v = v*(10 as i64)+(c-OSP_ASCII_0); any = 1; i = i + 1; go = 1 } } } 4078 } 4079 endp[0] = i 4080 if any == 0 { return OSP_SENTINEL } 4081 return v 4082} 4083// basename (after last '/') of NUL-terminated s 4084func osp_basename(s: *u8) -> *u8 { 4085 var i: i64 = 0; var last: i64 = 0 4086 while s[i] != (OSP_NUL as u8) { if s[i] == (OSP_SLASH as u8) { last = i + 1 } i = i + 1 } 4087 return (s as i64 + last) as *u8 4088} 4089 4090// ============================ LINUX BACKEND (procfs) ============================ 4091// NOTE: the OS-target guard is currently a SOURCE-SWAP seam, not a compile-time @ifdef -- nx_cc's 4092// preprocessor is arch-guard-only today (TARGET_X86_64); a custom TARGET_NISHI compiled BOTH branches 4093// and the stub won (proven 2026-07-16). When nx_cc gains OS-target guards, wrap this in @ifdef 4094// TARGET_LINUX and the NishiOS backend (spec at bottom) in @ifdef TARGET_NISHI. The portability WIN 4095// stands regardless: every raw /proc lives HERE and nowhere else, so swapping the backend is a 4096// single-file change with the whole LOGIC layer (nx_heal) untouched. 4097// bounded read of a whole (small) proc/file into buf; returns len (0 on empty/absent) 4098func osp_bread(path: *u8, buf: *u8, cap: i64) -> i64 { 4099 let fd: i64 = sys_openat_rd(path) 4100 if fd < 0 { return 0 } 4101 var got: i64 = 0; var go: i64 = 1 4102 while go == 1 { let r: i64 = sys_read(fd, (buf as i64 + got) as *u8, cap - got); if r > 0 { got = got + r; if got >= cap { go = 0 } } else { go = 0 } } 4103 sys_close(fd) 4104 return got 4105} 4106// build "/proc/<pid><leaf>" (leaf NUL-terminated, e.g. "/stat") into out 4107func osp_ppath(out: *u8, pid: i64, leaf: *u8) -> i64 { 4108 var o: i64 = 0 4109 let pre: *u8 = "/proc/" as *u8 4110 var i: i64 = 0 4111 while pre[i] != (OSP_NUL as u8) { out[o] = pre[i]; o = o + 1; i = i + 1 } 4112 o = o + osp_itoa(pid, (out as i64 + o) as *u8) 4113 i = 0 4114 while leaf[i] != (OSP_NUL as u8) { out[o] = leaf[i]; o = o + 1; i = i + 1 } 4115 out[o] = 0 as u8 4116 return o 4117} 4118// enumerate live pids into pids[0..cap); returns count 4119func osp_list_pids(pids: *i64, cap: i64) -> i64 { 4120 let fd: i64 = sys_openat_rd("/proc" as *u8) 4121 if fd < 0 { return 0 } 4122 let dbuf: *u8 = sys_mmap(OSP_DENT_BUF) 4123 let ep: *i64 = sys_mmap(16) as *i64 4124 var cnt: i64 = 0; var run: i64 = 1 4125 while run == 1 { 4126 let n: i64 = sys_getdents64(fd, dbuf, OSP_DENT_BUF) 4127 if n <= 0 { run = 0 } else { 4128 var off: i64 = 0 4129 while off < n { 4130 let rec: *u8 = ((dbuf as i64 + off) as *u8) 4131 let reclen: i64 = dirent_reclen(rec) 4132 if reclen <= 0 { off = n } else { 4133 let name: *u8 = dirent_name(rec) 4134 if name[0] >= (OSP_ASCII_0 as u8) { if name[0] <= (OSP_ASCII_9 as u8) { 4135 if cnt < cap { let pid: i64 = osp_num(name, osp_slen(name), 0, ep); if pid > 0 { pids[cnt] = pid; cnt = cnt + 1 } } 4136 } } 4137 off = off + reclen 4138 } 4139 } 4140 } 4141 } 4142 sys_close(fd) 4143 return cnt 4144} 4145// count OPEN FILE DESCRIPTORS of pid = numeric entries in /proc/<pid>/fd. -1 if unreadable (gone/no perm). 4146// The fd METER for anomaly detection: a socket/file-descriptor leak trends up HERE while VmSize can stay 4147// flat (the fd table is not the address space) -- a leak shows in whatever resource disappears. Leak-free. 4148func osp_fd_count_from_fd_result(fd: i64, cause: *i64) -> i64 { 4149 if (cause as i64) != 0 { cause[0]=0 } 4150 let dbuf: *u8=sys_mmap(OSP_DENT_BUF) 4151 var count: i64=0 4152 var running: i64=1 4153 var failure: i64=0 4154 while running == 1 { 4155 let n: i64=sys_getdents64(fd,dbuf,OSP_DENT_BUF) 4156 if n < 0 { failure=n; running=0 } else { 4157 if n == 0 { running=0 } else { 4158 var off: i64=0 4159 while off < n { 4160 let rec: *u8=((dbuf as i64)+off) as *u8 4161 let reclen: i64=dirent_reclen(rec) 4162 if reclen <= 0 { failure=OSP_SENTINEL; running=0; break } 4163 let name: *u8=dirent_name(rec) 4164 if name[0] >= OSP_ASCII_0 as u8 && name[0] <= OSP_ASCII_9 as u8 { count=count+1 } 4165 off=off+reclen 4166 } 4167 } 4168 } 4169 } 4170 sys_munmap(dbuf,OSP_DENT_BUF) 4171 if failure < 0 { if (cause as i64) != 0 { cause[0]=failure }; return OSP_SENTINEL } 4172 return count 4173} 4174func osp_fd_count_from_fd(fd: i64) -> i64 { 4175 return osp_fd_count_from_fd_result(fd,0 as *i64) 4176} 4177func osp_fd_count(pid: i64) -> i64 { 4178 let path: *u8=sys_mmap(OSP_PATH_CAP) 4179 osp_ppath(path,pid,"/fd") 4180 let fd: i64=sys_openat_rd(path) 4181 sys_munmap(path,OSP_PATH_CAP) 4182 if fd < 0 { return OSP_SENTINEL } 4183 let count: i64=osp_fd_count_from_fd(fd) 4184 sys_close(fd) 4185 return count 4186} 4187 4188// field after the last ')' in /proc/<pid>/stat: OSP_F_PPID or OSP_F_START; SENTINEL on fail 4189func osp_stat_field(pid: i64, fidx: i64) -> i64 { 4190 let p: *u8 = sys_mmap(OSP_PATH_CAP) 4191 osp_ppath(p, pid, "/stat" as *u8) 4192 let b: *u8 = sys_mmap(OSP_RD_CAP) 4193 let n: i64 = osp_bread(p, b, OSP_RD_CAP - 1) 4194 if n <= 0 { return OSP_SENTINEL } 4195 var rp: i64 = 0 - 1; var i: i64 = 0 4196 while i < n { if b[i] == (OSP_RP as u8) { rp = i } i = i + 1 } 4197 if rp < 0 { return OSP_SENTINEL } 4198 var f: i64 = 0; i = rp + 1 4199 let ep: *i64 = sys_mmap(16) as *i64 4200 while i < n { 4201 if b[i] == (OSP_SP as u8) { i = i + 1 } else { 4202 f = f + 1 4203 let v: i64 = osp_num(b, n, i, ep) 4204 if f == fidx { return v } 4205 i = ep[0] 4206 var go: i64 = 1 4207 while go == 1 { go = 0; if i < n { if b[i] != (OSP_SP as u8) { i = i + 1; go = 1 } } } 4208 } 4209 } 4210 return OSP_SENTINEL 4211} 4212func osp_ppid(pid: i64) -> i64 { return osp_stat_field(pid, OSP_F_PPID) } 4213func osp_starttime_ticks(pid: i64) -> i64 { return osp_stat_field(pid, OSP_F_START) } 4214// cumulative CPU ticks consumed by pid = utime + stime. The CPU METER for anomaly detection: sampled over 4215// time, its RATE (Theil-Sen slope of the per-interval deltas) = the burn = "power disappearing" (a busy-loop 4216// pegs a core). SENTINEL if unreadable. HZ ticks/sec via osp_hz(). 4217func osp_cpu_ticks(pid: i64) -> i64 { 4218 let u: i64 = osp_stat_field(pid, OSP_F_UTIME) 4219 let s: i64 = osp_stat_field(pid, OSP_F_STIME) 4220 if u == OSP_SENTINEL { return OSP_SENTINEL } 4221 if s == OSP_SENTINEL { return OSP_SENTINEL } 4222 return u + s 4223} 4224// argv0 basename of /proc/<pid>/cmdline into out; return len (0 if none) 4225func osp_cmd_argv0(pid: i64, out: *u8, cap: i64) -> i64 { 4226 let p: *u8 = sys_mmap(OSP_PATH_CAP) 4227 osp_ppath(p, pid, "/cmdline" as *u8) 4228 let cl: *u8 = sys_mmap(cap + 1) 4229 let n: i64 = osp_bread(p, cl, cap) 4230 if n <= 0 { out[0] = 0 as u8; return 0 } 4231 cl[n] = 0 as u8 // argv0 = bytes up to the first NUL (already there) 4232 let bn: *u8 = osp_basename(cl) 4233 var o: i64 = 0 4234 while bn[o] != (OSP_NUL as u8) { out[o] = bn[o]; o = o + 1 } 4235 out[o] = 0 as u8 4236 return o 4237} 4238func osp_hz() -> i64 { return OSP_HZ_LINUX } 4239// where the HOST SUPERVISOR writes its log -- a deployment/OS question, so it lives in the seam. 4240// Linux/NAS deploy: /tmp/supervisor.log (nx_hostctl supervise). NishiOS: its native supervisor journal. 4241func osp_supervisor_log() -> *u8 { return "/tmp/supervisor.log" as *u8 } 4242func osp_uptime_s() -> i64 { let ts: *i64 = sys_mmap(16) as *i64; sys_clock_gettime_mono(ts); return ts[0] } 4243func osp_selfpid() -> i64 { 4244 let b: *u8 = sys_mmap(OSP_RD_CAP) 4245 let n: i64 = osp_bread("/proc/self/stat" as *u8, b, OSP_RD_CAP - 1) 4246 if n <= 0 { return OSP_SENTINEL } 4247 let ep: *i64 = sys_mmap(16) as *i64 4248 return osp_num(b, n, 0, ep) 4249} 4250// wallclock epoch = /proc/stat btime + monotonic-since-boot 4251func osp_boot_epoch() -> i64 { 4252 let b: *u8 = sys_mmap(OSP_STAT_CAP) 4253 let n: i64 = osp_bread("/proc/stat" as *u8, b, OSP_STAT_CAP - 1) 4254 if n <= 0 { return 0 } 4255 let needle: *u8 = "btime " as *u8 4256 var i: i64 = 0 4257 let ep: *i64 = sys_mmap(16) as *i64 4258 while i < n { 4259 var m: i64 = 1; var k: i64 = 0 4260 while needle[k] != (OSP_NUL as u8) { if i+k >= n { m = 0 } else { if b[i+k] != needle[k] { m = 0 } } k = k + 1 } 4261 if m == 1 { return osp_num(b, n, i + k, ep) } 4262 i = i + 1 4263 } 4264 return 0 4265} 4266 4267// ======================= NISHIOS BACKEND SPEC (the swap-in seam) ======================= 4268// When NishiOS's native process API lands, REPLACE the Linux backend above (or @ifdef-branch it once 4269// nx_cc has OS-target guards) with these ~8 functions over NishiOS's DIRECT kernel process table -- 4270// superior to procfs: no /proc text-parsing, no USER_HZ, a real syscall query. The interface the LOGIC 4271// layer depends on (and ALL it depends on) is exactly: 4272// osp_list_pids(pids,cap)->count nishi_proc_enumerate (live pids) 4273// osp_ppid(pid)->ppid nishi_proc_parent 4274// osp_starttime_ticks(pid)->ticks nishi_proc_starttime (osp_hz() ticks/sec) 4275// osp_cmd_argv0(pid,out,cap)->len nishi_proc_argv0 (basename of argv0) 4276// osp_hz()->ticks_per_sec native rate (not the Linux-100 assumption) 4277// osp_uptime_s()->secs sys_clock_gettime_mono (already OS-neutral) 4278// osp_selfpid()->pid nishi_getpid 4279// osp_boot_epoch()->epoch nishi_boot_epoch 4280// Interop: NishiOS ships the superior backend; Linux stays supported for the current NAS deploy; the 4281// LOGIC (nx_heal) compiles unchanged on both. THAT is the point of this file. 4282 4283// Direct-child enumeration does not depend on CONFIG_CHECKPOINT_RESTORE's 4284// optional /proc/<pid>/task/<pid>/children file. The caller owns the output 4285// capacity; overflow is an error, never a plausible partial child set. 4286const OSP_DIRENT_NAME_OFFSET: i64 = 19 // Linux linux_dirent64 ABI 4287func osp_stat_parent(buf: *u8, n: i64) -> i64 { 4288 var last: i64=0-1;var i: i64=0 4289 while i < n { if buf[i] == OSP_RP as u8 { last=i };i=i+1 } 4290 if last < 0 { return 0-5 } 4291 i=last+1 4292 while i < n && buf[i] == OSP_SP as u8 { i=i+1 } 4293 while i < n && buf[i] != OSP_SP as u8 { i=i+1 } 4294 while i < n && buf[i] == OSP_SP as u8 { i=i+1 } 4295 let first: i64=i;var parent: i64=0 4296 while i < n && buf[i] >= OSP_ASCII_0 as u8 && buf[i] <= OSP_ASCII_9 as u8 { 4297 parent=parent*10+(buf[i] as i64)-OSP_ASCII_0;i=i+1 4298 } 4299 if i == first || i == n || buf[i] != OSP_SP as u8 { return 0-5 } 4300 return parent 4301} 4302func osp_children(parent: i64, children: *i64, capacity: i64) -> i64 { 4303 if parent <= 0 || capacity < 0 { return 0-22 } 4304 let directory: i64=sys_openat_directory("/proc") 4305 if directory < 0 { return directory } 4306 let batch: *u8=sys_mmap(OSP_DENT_BUF) 4307 let path: *u8=sys_mmap(OSP_PATH_CAP) 4308 let stat: *u8=sys_mmap(OSP_RD_CAP) 4309 var count: i64=0;var failure: i64=0;var running: i64=1 4310 while running == 1 { 4311 let n: i64=sys_getdents64(directory,batch,OSP_DENT_BUF) 4312 if n == (0-4) { continue } 4313 if n <= 0 { failure=n;break } 4314 var off: i64=0 4315 while off < n { 4316 if n-off <= OSP_DIRENT_NAME_OFFSET { failure=0-5;running=0;break } 4317 let rec: *u8=batch+off 4318 let size: i64=dirent_reclen(rec) 4319 if size <= OSP_DIRENT_NAME_OFFSET || size > n-off { failure=0-5;running=0;break } 4320 var i: i64=OSP_DIRENT_NAME_OFFSET;var pid: i64=0 4321 while i < size && rec[i] >= OSP_ASCII_0 as u8 && rec[i] <= OSP_ASCII_9 as u8 { 4322 pid=pid*10+(rec[i] as i64)-OSP_ASCII_0;i=i+1 4323 } 4324 if pid > 0 && i < size && rec[i] == OSP_NUL as u8 { 4325 osp_ppath(path,pid,"/stat") 4326 let fd: i64=sys_openat_rd(path) 4327 // A process may disappear during enumeration; other failures 4328 // make completeness unproven and must propagate. 4329 if fd < 0 && fd != (0-2) { failure=fd;running=0;break } 4330 if fd >= 0 { 4331 var used: i64=0;var readrc: i64=1 4332 while readrc > 0 && used < OSP_RD_CAP { 4333 readrc=sys_read(fd,stat+used,OSP_RD_CAP-used) 4334 if readrc == (0-4) { readrc=1;continue } 4335 if readrc > 0 { used=used+readrc } 4336 } 4337 let closed: i64=sys_close(fd) 4338 if readrc < 0 && readrc != (0-3) { failure=readrc;running=0;break } 4339 if closed < 0 { failure=closed;running=0;break } 4340 if used == OSP_RD_CAP { failure=0-75;running=0;break } 4341 if used > 0 { 4342 let observed: i64=osp_stat_parent(stat,used) 4343 if observed < 0 { failure=observed;running=0;break } 4344 if observed == parent { 4345 if count >= capacity { failure=0-28;running=0;break } 4346 children[count]=pid;count=count+1 4347 } 4348 } 4349 } 4350 } 4351 off=off+size 4352 } 4353 } 4354 let closed: i64=sys_close(directory) 4355 sys_munmap(batch,OSP_DENT_BUF);sys_munmap(path,OSP_PATH_CAP);sys_munmap(stat,OSP_RD_CAP) 4356 if failure < 0 { return failure } 4357 if closed < 0 { return closed } 4358 return count 4359} 4360 4361const FSX_MAGIC_4095: i64 = 4095 4362 4363const FSX_READ_CAP: i64 = 1048576 // max bytes returned by `read` (truncation is MARKED, never silent) 4364const FSX_DENY_CAP: i64 = 8192 // fs_read_deny.conf read cap 4365const FSX_PATH_CAP: i64 = 1024 // lowercased path work buffer 4366const FSX_DENT_BUF: i64 = 65536 // getdents64 batch buffer (matches the proven vsz/heal sizing) 4367const FSX_LS_CAP: i64 = 200 // scale-law: max ls entries EMITTED; true total ALWAYS declared (65KB-dump fix) 4368const FSX_RC_ABSENT: i64 = 3 // exit: path absent/unreadable (mirrors nx_fileop's exists convention) 4369const FSX_RC_DENIED: i64 = 5 // exit: deny-list refused the read 4370const FSX_UPPER_A: i64 = 65 // 'A' (ASCII lowercasing) 4371const FSX_UPPER_Z: i64 = 90 // 'Z' 4372const FSX_CASE_OFF: i64 = 32 // 'a' - 'A' 4373const FSX_ASCII_0: i64 = 48 // '0' (decimal print) 4374 4375func fsx_puts(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 } 4376// MIGRATED to the shared emitter (debt 1785563586). The old body mmapped a scratch buffer 4377// per call and never freed it. At PAGE granularity that is 4096B leaked PER CALL -- the 4378// defect that took 28.5GB of a 36GB host in nx_ts_lumadiff (2MB input, ~3.66M calls). 4379// nxi_* is MSB-first, allocates NOTHING, and emits identical bytes including the sign. 4380func fsx_putn(v: i64) -> i64 { nxi_out(v); return 0 } 4381// lowercase copy of s into out (bounded), returns length 4382func fsx_lower(s: *u8, out: *u8, cap: i64) -> i64 { 4383 var i: i64 = 0 4384 while s[i] != (0 as u8) { 4385 if i >= cap - 1 { out[i] = 0 as u8; return i } 4386 var c: i64 = s[i] as i64 4387 if c >= FSX_UPPER_A { if c <= FSX_UPPER_Z { c = c + FSX_CASE_OFF } } 4388 out[i] = c as u8 4389 i = i + 1 4390 } 4391 out[i] = 0 as u8 4392 return i 4393} 4394// exact NUL-terminated string equality 4395func fsx_seq(a: *u8, b: *u8) -> i64 { var i: i64 = 0; while a[i] != (0 as u8) { if a[i] != b[i] { return 0 } i = i + 1 } if b[i] != (0 as u8) { return 0 } return 1 } 4396// is `needle` (NUL-terminated, lowercase) contained in lowercase path lp[0..ln)? 4397// ---------- compare-and-swap decision (seq1422/seq1456) ---------- 4398// 4399// PURE, and in the LIB on purpose: the decision used to live inside the CLI's 4400// main(), where a gate cannot reach it -- which is exactly how it shipped 4401// refusing every correct expectation (seq1422). A rule nothing can drive is a 4402// rule nothing can prove. 4403// 4404// tok is the raw argv token (`expect=<n>` / `expect=any` / a bare number); 4405// cur is the file's real size. Returns 1 = ALLOW, 0 = REFUSE. 4406func fsx_cas_val(tok: *u8) -> *u8 { 4407 var i: i64 = 0 4408 while tok[i] != (0 as u8) { 4409 if tok[i] == (61 as u8) { return ((tok as i64) + i + 1) as *u8 } 4410 i = i + 1 4411 } 4412 return tok 4413} 4414func fsx_cas_ok(cur: i64, tok: *u8) -> i64 { 4415 let v: *u8 = fsx_cas_val(tok) 4416 if fsx_seq(v, "any" as *u8) == 1 { return 1 } 4417 var n: i64 = 0 4418 var i: i64 = 0 4419 var got: i64 = 0 4420 while v[i] != (0 as u8) { 4421 let c: i64 = v[i] as i64 4422 if c >= 48 { if c <= 57 { n = n * 10 + (c - 48); got = 1 } } 4423 i = i + 1 4424 } 4425 if got == 0 { return 0 } 4426 if n == cur { return 1 } 4427 return 0 4428} 4429 4430func fsx_deny_hit(lp: *u8, ln: i64, needle: *u8) -> i64 { 4431 let nl: i64 = vw_slen(needle) 4432 if nl == 0 { return 0 } 4433 return vw_contains(lp, ln, needle, nl) 4434} 4435// data-driven deny extras: one lowercase needle per line in `conf`; 1 = some line matches the path. 4436// Factored out so the read deny (fs_read_deny.conf) and write deny (fs_write_deny.conf) share ONE scanner. 4437func fsx_conf_deny(lp: *u8, ln: i64, conf: *u8) -> i64 { 4438 let cb: *u8 = sys_mmap(FSX_DENY_CAP) 4439 let cn: i64 = vw_read(conf, cb, FSX_DENY_CAP - 1) 4440 if cn > 0 { 4441 var ls: i64 = 0 4442 var i: i64 = 0 4443 while i <= cn { 4444 var eol: i64 = 0 4445 if i == cn { eol = 1 } else { if cb[i] == (10 as u8) { eol = 1 } } 4446 if eol == 1 { 4447 if i > ls { 4448 cb[i] = 0 as u8 // terminate the line in place 4449 if fsx_deny_hit(lp, ln, (cb as i64 + ls) as *u8) == 1 { return 1 } 4450 } 4451 ls = i + 1 4452 } 4453 i = i + 1 4454 } 4455 } 4456 return 0 4457} 4458const FSX_SNIFF_CAP: i64 = 4096 4459 4460func fsx_isalnum(c: i64) -> i64 { 4461 if c >= 48 { if c <= 57 { return 1 } } 4462 if c >= 97 { if c <= 122 { return 1 } } 4463 if c >= 65 { if c <= 90 { return 1 } } 4464 return 0 4465} 4466 4467func fsx_ends_with(lp: *u8, ln: i64, suf: *u8) -> i64 { 4468 let sl: i64 = vw_slen(suf) 4469 if sl == 0 { return 0 } 4470 if sl > ln { return 0 } 4471 var i: i64 = 0 4472 while i < sl { 4473 if lp[ln - sl + i] != suf[i] { return 0 } 4474 i = i + 1 4475 } 4476 return 1 4477} 4478 4479func fsx_basename_is(lp: *u8, ln: i64, name: *u8) -> i64 { 4480 let nl: i64 = vw_slen(name) 4481 if nl == 0 { return 0 } 4482 if nl > ln { return 0 } 4483 if fsx_ends_with(lp, ln, name) == 0 { return 0 } 4484 if nl == ln { return 1 } 4485 let c: i64 = lp[ln - nl - 1] as i64 4486 if c == 47 { return 1 } 4487 if c == 92 { return 1 } 4488 return 0 4489} 4490 4491// Whole-word containment: bounded by non-alphanumeric on BOTH sides, so `api_secret.txt` is denied and 4492// `secretary_notes.md` is not. 4493func fsx_word_has(lp: *u8, ln: i64, w: *u8) -> i64 { 4494 let wl: i64 = vw_slen(w) 4495 if wl == 0 { return 0 } 4496 if wl > ln { return 0 } 4497 var i: i64 = 0 4498 while i + wl <= ln { 4499 var eq: i64 = 1 4500 var k: i64 = 0 4501 while k < wl { if lp[i + k] != w[k] { eq = 0; k = wl } else { k = k + 1 } } 4502 if eq == 1 { 4503 var lb: i64 = 1 4504 if i > 0 { if fsx_isalnum(lp[i - 1] as i64) == 1 { lb = 0 } } 4505 var rb: i64 = 1 4506 if i + wl < ln { if fsx_isalnum(lp[i + wl] as i64) == 1 { rb = 0 } } 4507 if lb == 1 { if rb == 1 { return 1 } } 4508 } 4509 i = i + 1 4510 } 4511 return 0 4512} 4513 4514// CONTENT LEG: sniff the leading bytes for what a secret actually IS. This is the half a name-only list 4515// can never do -- it denies a private key no matter what it is called, including `notes.txt`. 4516// A CERTIFICATE is deliberately NOT denied: certs are public by definition, and denying them is the same 4517// category error as denying the tokenizer. 4518func fsx_content_secret(path: *u8) -> i64 { 4519 let fd: i64 = sys_openat_rd(path) 4520 if fd < 0 { return 0 } 4521 let b: *u8 = sys_mmap(FSX_SNIFF_CAP) 4522 let n: i64 = sys_read(fd, b, FSX_SNIFF_CAP - 1) 4523 sys_close(fd) 4524 if n <= 0 { return 0 } 4525 if vw_contains(b, n, "PRIVATE KEY-----" as *u8, 16) == 1 { return 1 } 4526 if vw_contains(b, n, "OPENSSH PRIVATE KEY" as *u8, 19) == 1 { return 1 } 4527 if vw_contains(b, n, "PGP PRIVATE KEY BLOCK" as *u8, 21) == 1 { return 1 } 4528 if vw_contains(b, n, "PuTTY-User-Key-File" as *u8, 19) == 1 { return 1 } 4529 return 0 4530} 4531 4532// DENY check: 1 = refuse this path. SOTA-2026 REWRITE (2026-07-31). 4533// 4534// THE OLD RULE WAS WRONG IN BOTH DIRECTIONS, measured on real paths: 4535// OVER-BLOCKED substring "token" denied runtime/nx_tokenizer.nx -- the compiler's own tokenizer, which 4536// contains no secret -- and blocked BOTH nx_fs read AND nx_fs_write on it, while 4537// nx_shelltool grep returned the same bytes freely. It cost real work and bought nothing. 4538// substring "key" likewise denies monkey / keyword / keyboard. 4539// UNDER-BLOCKED `id_rsa`, the canonical SSH private key filename, contains NONE of 4540// secret/key/token/passw/.pem and sailed straight through. 4541// A denylist that blocks source and passes private keys is not a security control -- it is a rename away 4542// from useless in one direction and a permanent nuisance in the other. 4543// 4544// REPLACEMENT -- two INDEPENDENT legs, either one denies: 4545// (1) PATH leg: real secret-bearing EXTENSIONS and exact BASENAMES, matched at a true suffix/segment 4546// boundary, plus whole-word `secret`/`password`. No substring-anywhere matching survives. 4547// (2) CONTENT leg: PEM/OpenSSH/PGP/PuTTY private-key armour, which catches a secret regardless of name. 4548// Net effect: strictly MORE secrets denied (id_rsa, a renamed key, a key with no extension) and strictly 4549// FEWER ordinary sources blocked. 4550func fsx_denied(path: *u8) -> i64 { 4551 let lp: *u8 = sys_mmap(FSX_PATH_CAP) 4552 let ln: i64 = fsx_lower(path, lp, FSX_PATH_CAP) 4553 4554 if fsx_ends_with(lp, ln, ".pem" as *u8) == 1 { return 1 } 4555 if fsx_ends_with(lp, ln, ".key" as *u8) == 1 { return 1 } 4556 if fsx_ends_with(lp, ln, ".cap" as *u8) == 1 { return 1 } 4557 if fsx_ends_with(lp, ln, ".p12" as *u8) == 1 { return 1 } 4558 if fsx_ends_with(lp, ln, ".pfx" as *u8) == 1 { return 1 } 4559 if fsx_ends_with(lp, ln, ".jks" as *u8) == 1 { return 1 } 4560 if fsx_ends_with(lp, ln, ".ppk" as *u8) == 1 { return 1 } 4561 if fsx_ends_with(lp, ln, "_rsa" as *u8) == 1 { return 1 } 4562 if fsx_ends_with(lp, ln, "_dsa" as *u8) == 1 { return 1 } 4563 if fsx_ends_with(lp, ln, "_ecdsa" as *u8) == 1 { return 1 } 4564 if fsx_ends_with(lp, ln, "_ed25519" as *u8) == 1 { return 1 } 4565 4566 if fsx_basename_is(lp, ln, ".env" as *u8) == 1 { return 1 } 4567 if fsx_basename_is(lp, ln, "credentials" as *u8) == 1 { return 1 } 4568 if fsx_basename_is(lp, ln, "shadow" as *u8) == 1 { return 1 } 4569 if fsx_basename_is(lp, ln, "opaque_keys.bin" as *u8) == 1 { return 1 } 4570 4571 // CALIBRATED BY WORD FREQUENCY, not by one uniform rule -- the gate proved a uniform rule wrong in 4572 // BOTH directions within minutes. `secret` and `passw` are high-signal and essentially absent from 4573 // ordinary source, so SUBSTRING matching is correct for them and catches mysecret_key.bin. `key` and 4574 // `token` are common English fragments (tokenizer, monkey, keyword, keyboard) and must NEVER be 4575 // substring-matched -- that is what denied the compiler's own tokenizer. They are covered instead by 4576 // the extension/suffix rules above and by the content leg below. 4577 if fsx_deny_hit(lp, ln, "secret" as *u8) == 1 { return 1 } 4578 if fsx_deny_hit(lp, ln, "passw" as *u8) == 1 { return 1 } 4579 if fsx_deny_hit(lp, ln, "credential" as *u8) == 1 { return 1 } 4580 4581 if fsx_content_secret(path) == 1 { return 1 } 4582 4583 return fsx_conf_deny(lp, ln, "fs_read_deny.conf" as *u8) 4584} 4585// read: emit up to `cap` bytes of path to stdout. Returns bytes emitted; -1 absent; -2 DENIED. 4586// deniedp/absent are ALSO visible in the CLI exit code. Truncation is marked with a trailing banner. 4587// Failure reporter that KEEPS THE ERRNO. sys_openat_rd returns -errno, and the old message printed 4588// "ABSENT" for every negative -- so EACCES (-13, EXISTS but unopenable) read as "missing", which are 4589// OPPOSITE remedies. Cost a real hour on 2026-08-01: knowledge/foundation existed with mode 0100 and 4590// every instrument in the stack called it absent (the mkdirp read-back that printed the errno cracked 4591// the case in one call). rc>=0 means a probe re-open SUCCEEDED: the earlier read failed for a 4592// non-open reason (an empty file), so say THAT. Always returns -1 (callers' contract unchanged; 4593// the -2 DENIED sentinel stays distinct). 4594func fsx_fail(path: *u8, rc: i64) -> i64 { 4595 if rc >= 0 { sys_close(rc); fsx_puts("NX-FS EMPTY: 0 bytes: " as *u8); fsx_puts(path); fsx_puts("\n" as *u8); return 0 - 1 } 4596 if rc == 0 - 13 { 4597 fsx_puts("NX-FS PERMISSION (EACCES): exists but this process may not open it: " as *u8) 4598 fsx_puts(path); fsx_puts("\n" as *u8) 4599 return 0 - 1 4600 } 4601 if rc == 0 - 2 { fsx_puts("NX-FS ABSENT: " as *u8); fsx_puts(path); fsx_puts("\n" as *u8); return 0 - 1 } 4602 fsx_puts("NX-FS ERROR rc=" as *u8); fsx_putn(rc) 4603 fsx_puts(": " as *u8); fsx_puts(path); fsx_puts("\n" as *u8) 4604 return 0 - 1 4605} 4606 4607const FSX_SEEK_END: i64 = 2 // lseek whence: EOF offset = size, WITHOUT reading a single byte 4608 4609// TRUE SIZE -- the one thing no other read verb in this lib can give you (2026-08-07, debt 1786054029). 4610// read/lines/outline all report BYTES THEY READ against FSX_READ_CAP/FSX_LINES_SCAN, and they DO honestly 4611// declare the cap -- but an honest floor is still not a measurement: "bytes=1048576 (covers first 1048576 4612// bytes only)" is the IDENTICAL answer for a 1.05MB file and a 30MB one. 4613// MEASURED COST OF NOT HAVING IT: bounding ONE 1.38MB journal took TWELVE probe reads at hand-chosen 4614// offsets, because the only way to learn a big file size was to binary-search EOF by hand. 4615// lseek(SEEK_END) reads ZERO bytes, so the answer is exact at ANY size for one syscall. 4616// Deny-list still applies: consistency with every other verb beats a special case for a metadata read. 4617// CONTRACT DIFFERS FROM fsx_read ON PURPOSE: an EMPTY file returns 0, never -1. Size is the one caller for 4618// which "absent" and "zero bytes" are DIFFERENT FACTS, so fsx_fail -- which folds both to -1 -- is not used 4619// here. (Same distinction lt_read_tail needed: -1 ABSENT vs 0 EMPTY. A reader that conflates them cannot 4620// tell a lane that never wrote from a lane whose file vanished.) 4621// A DECLARED FLOOR IS HONEST BUT IT IS NOT A MEASUREMENT -- IF THE NUMBER IS CHEAP, EMIT THE NUMBER. 4622func fsx_size(path: *u8) -> i64 { 4623 if fsx_denied(path) == 1 { 4624 fsx_puts("NX-FS-SIZE DENIED: path matches the secret deny-list. WHY: this tool never returns key material.\n" as *u8) 4625 return 0 - (2 as i64) 4626 } 4627 let fd: i64 = sys_openat_rd(path) 4628 if fd < 0 { 4629 fsx_puts("NX-FS-SIZE ABSENT: cannot open " as *u8); fsx_puts(path) 4630 fsx_puts(" . FIX: confirm the path with `nx_fs ls <dir>`.\n" as *u8) 4631 return 0 - 1 4632 } 4633 let sz: i64 = sys_lseek(fd, 0, FSX_SEEK_END) 4634 sys_close(fd) 4635 if sz < 0 { 4636 fsx_puts("NX-FS-SIZE UNSEEKABLE: " as *u8); fsx_puts(path) 4637 fsx_puts(" (a pipe/char device has no size; this is NOT a zero-byte file)\n" as *u8) 4638 return 0 - 1 4639 } 4640 fsx_puts("NX-FS-SIZE " as *u8); fsx_puts(path) 4641 fsx_puts(" bytes=" as *u8); fsx_putn(sz) 4642 fsx_puts(" exact=1 read_bytes=0\n" as *u8) 4643 return sz 4644} 4645 4646func fsx_read(path: *u8, cap: i64) -> i64 { 4647 if fsx_denied(path) == 1 { 4648 fsx_puts("NX-FS DENIED: path matches the secret deny-list (defaults + fs_read_deny.conf)\n" as *u8) 4649 return 0 - (2 as i64) // DENIED sentinel (distinct from -1 absent) 4650 } 4651 var want: i64 = cap 4652 if want <= 0 { want = FSX_READ_CAP } 4653 if want > FSX_READ_CAP { want = FSX_READ_CAP } 4654 let buf: *u8 = sys_mmap(want + 1) 4655 let n: i64 = vw_read(path, buf, want) 4656 // vw_read flattens the errno (-1 for every failure); re-probe the open ONLY on the failure path 4657 // so the message can distinguish absent / permission / empty. Zero cost on success. 4658 if n <= 0 { return fsx_fail(path, sys_openat_rd(path)) } 4659 sys_write(1, buf, n) 4660 if n == want { 4661 fsx_puts("\n[NX-FS TRUNCATED at " as *u8); fsx_putn(n); fsx_puts(" bytes]\n" as *u8) 4662 } 4663 return n 4664} 4665// WINDOWED read (eats debt seq222: the tools-call transport caps ~64KB, so files past the cap were 4666// unreadable over MCP): emit up to `cap` bytes starting at byte `off`. Same deny-list as fsx_read. 4667// A separate function (NOT an fsx_read arity change) so every existing caller keeps its exact contract. 4668func fsx_read_at(path: *u8, cap: i64, off: i64) -> i64 { 4669 if fsx_denied(path) == 1 { 4670 fsx_puts("NX-FS DENIED: path matches the secret deny-list (defaults + fs_read_deny.conf)\n" as *u8) 4671 return 0 - (2 as i64) 4672 } 4673 var want: i64 = cap 4674 if want <= 0 { want = FSX_READ_CAP } 4675 if want > FSX_READ_CAP { want = FSX_READ_CAP } 4676 let fd: i64 = sys_openat_rd(path) 4677 if fd < 0 { return fsx_fail(path, fd) } 4678 if off > 0 { if sys_lseek(fd, off, 0) < 0 { sys_close(fd); fsx_puts("NX-FS ABSENT: seek failed " as *u8); fsx_puts(path); fsx_puts("\n" as *u8); return 0 - 1 } } 4679 let buf: *u8 = sys_mmap(want + 1) 4680 var got: i64 = 0 4681 var sc: i64 = 1 4682 while sc == 1 { 4683 let r: i64 = sys_read(fd, ((buf as i64 + got) as *u8), want - got) 4684 if r <= 0 { sc = 0 } else { got = got + r; if got >= want { sc = 0 } } 4685 } 4686 sys_close(fd) 4687 if got <= 0 { fsx_puts("NX-FS EOF: no bytes at offset " as *u8); fsx_putn(off); fsx_puts(" in " as *u8); fsx_puts(path); fsx_puts("\n" as *u8); return 0 - 1 } 4688 sys_write(1, buf, got) 4689 if got == want { 4690 fsx_puts("\n[NX-FS WINDOW off=" as *u8); fsx_putn(off); fsx_puts(" n=" as *u8); fsx_putn(got); fsx_puts(" -- more remains]\n" as *u8) 4691 } 4692 return got 4693} 4694const FSX_LINES_SCAN: i64 = 1048576 // line-addressing scan window (matches the proven read cap) 4695const FSX_LINES_MAXOUT: i64 = 262144 // max bytes emitted by one `lines` call (transport-friendly) 4696const FSX_LINES_DEFN: i64 = 40 // default line count when the caller omits it 4697const FSX_LINES_MAXN: i64 = 400 // max lines per call 4698 4699// LINE-ADDRESSED read -- THE MISSING PRIMITIVE (measured 2026-07-20): `grep` reports file:LINE but `read` 4700// takes BYTES, so the two did NOT compose -- locating one function in a remote file meant hand 4701// binary-searching byte offsets (cost one subagent 70K tokens + 22 calls for a single extraction). 4702// Emits lines [start, start+count) 1-based, then a DECLARED envelope banner (scale-law: a caller can 4703// NEVER be silently windowed -- scanned bytes, scan cap, over-window and clip flags are all stated). 4704// Same deny-list as fsx_read. Returns bytes emitted; -1 absent; -2 DENIED. 4705func fsx_read_lines(path: *u8, start: i64, count: i64) -> i64 { 4706 if fsx_denied(path) == 1 { 4707 fsx_puts("NX-FS DENIED: path matches the secret deny-list (defaults + fs_read_deny.conf)\n" as *u8) 4708 return 0 - (2 as i64) 4709 } 4710 var s: i64 = start 4711 if s < 1 { s = 1 } 4712 var c: i64 = count 4713 if c <= 0 { c = FSX_LINES_DEFN } 4714 if c > FSX_LINES_MAXN { c = FSX_LINES_MAXN } 4715 let buf: *u8 = sys_mmap(FSX_LINES_SCAN + 1) 4716 let n: i64 = vw_read(path, buf, FSX_LINES_SCAN) 4717 if n <= 0 { return fsx_fail(path, sys_openat_rd(path)) } 4718 // walk to the first byte of line `s`; cur > s afterwards means we ran off the end (fail-loud, not empty) 4719 var i: i64 = 0 4720 var cur: i64 = 1 4721 while cur < s { 4722 if i >= n { cur = s + 1 } else { 4723 if buf[i] == (10 as u8) { cur = cur + 1 } 4724 i = i + 1 4725 } 4726 } 4727 if cur > s { 4728 fsx_puts("NX-FS LINES: start line " as *u8); fsx_putn(s) 4729 fsx_puts(" is beyond EOF (scanned " as *u8); fsx_putn(n); fsx_puts(" bytes)\n" as *u8) 4730 return 0 4731 } 4732 let from: i64 = i 4733 var lines_out: i64 = 0 4734 var j: i64 = i 4735 var go: i64 = 1 4736 while go == 1 { 4737 if j >= n { go = 0 } else { 4738 if buf[j] == (10 as u8) { 4739 lines_out = lines_out + 1 4740 j = j + 1 4741 if lines_out >= c { go = 0 } 4742 } else { j = j + 1 } 4743 } 4744 } 4745 var outn: i64 = j - from 4746 var clipped: i64 = 0 4747 if outn > FSX_LINES_MAXOUT { outn = FSX_LINES_MAXOUT; clipped = 1 } 4748 if outn > 0 { sys_write(1, ((buf as i64 + from) as *u8), outn) } 4749 fsx_puts("\n[NX-FS LINES start=" as *u8); fsx_putn(s) 4750 fsx_puts(" lines=" as *u8); fsx_putn(lines_out) 4751 fsx_puts(" next=" as *u8); fsx_putn(s + lines_out) 4752 fsx_puts(" bytes=" as *u8); fsx_putn(outn) 4753 fsx_puts(" scanned=" as *u8); fsx_putn(n) 4754 fsx_puts(" scan_cap=" as *u8); fsx_putn(FSX_LINES_SCAN) 4755 if n >= FSX_LINES_SCAN { fsx_puts(" FILE-EXCEEDS-SCAN-WINDOW" as *u8) } 4756 if clipped == 1 { fsx_puts(" BYTE-CLIPPED" as *u8) } 4757 fsx_puts("]\n" as *u8) 4758 return outn 4759} 4760// ==== WRITE/EDIT half (cap class: write; tools-api name nx_fs_write) ========================= 4761// ★ONE DEFINITION, TWO NAMES: this const KEEPS its name so no caller changes, but its VALUE now comes 4762// from the shim's MODE_0644 instead of a second literal. This line already called itself "the ecosystem's 4763// file-create mode idiom" -- and it was right, which is why adding MODE_0644 to nx_syscalls without 4764// finding it created a 64th copy rather than a single ruler. 4765// ★★★SEARCHING BY NAME FINDS ONLY WHAT SHARES YOUR NAMING CONVENTION. TO FIND A DUPLICATE CONSTANT YOU 4766// MUST SEARCH BY VALUE: a grep for `_MODE_0644` returned 10, a grep for `= 0x1a4` returned 66. 4767const FSX_MODE_RW: i64 = MODE_0644 // 0644 -- the ecosystem's file-create mode idiom 4768const FSX_DEC: i64 = 10 // decimal base (pid rendering in the tmp suffix) 4769const FSX_EDIT_OUT: i64 = 2097152 // edit output buffer (2x read cap: bounded replacement growth) 4770const FSX_TMP_ROOM: i64 = 32 // reserved room for ".nxw" + pid digits + NUL in the tmp name 4771const FSX_RC_IO: i64 = 4 // exit: io failure (open/short-write/rename) 4772const FSX_RC_NOMATCH: i64 = 6 // exit: edit found 0 occurrences (file UNCHANGED) 4773const FSX_RC_AMBIG: i64 = 7 // exit: edit found >1 occurrences without `all` (file UNCHANGED) 4774 4775// write-DENY: read deny (never clobber key material) + OS device/firmware namespace (rule 26, seam, 4776// BY CONSTRUCTION) + registry-escalation needle + fs_write_deny.conf extras (data-driven). 4777// TAIL -- the "WHERE DOES THIS FILE END" primitive, answered from the file's own end in ONE call. 4778// The documented recipe was `size`, then `read <path> <n> <size-n>`: two calls and an offset the caller 4779// carries by hand. What actually happened (measured 2026-09-03): a caller chose a `lines` start from an 4780// EARLIER run's size, read a window that landed mid-file, and published the window's last line as the 4781// file's last line -- while the envelope on that very read said next=212. Two false mechanisms and a 4782// false scope claim followed. ★A WINDOW READ IS NOT A TAIL READ. This verb cannot be pointed at the 4783// middle: it seeks to the end, walks BACKWARD for the last `count` line starts, and declares its window. 4784// Same deny-list as every read verb. Returns bytes emitted; 0 for an empty file (banner, never silence); 4785// -1 absent/unseekable; -2 DENIED. 4786func fsx_tail(path: *u8, count: i64) -> i64 { 4787 if fsx_denied(path) == 1 { 4788 fsx_puts("NX-FS DENIED: path matches the secret deny-list (defaults + fs_read_deny.conf)\n" as *u8) 4789 return 0 - (2 as i64) 4790 } 4791 var c: i64 = count 4792 if c <= 0 { c = FSX_LINES_DEFN } 4793 if c > FSX_LINES_MAXN { c = FSX_LINES_MAXN } 4794 let fd: i64 = sys_openat_rd(path) 4795 if fd < 0 { return fsx_fail(path, fd) } 4796 let sz: i64 = sys_lseek(fd, 0, FSX_SEEK_END) 4797 if sz < 0 { 4798 sys_close(fd) 4799 fsx_puts("NX-FS TAIL UNSEEKABLE: " as *u8); fsx_puts(path) 4800 fsx_puts(" (a pipe/char device has no end to seek to)\n" as *u8) 4801 return 0 - 1 4802 } 4803 if sz == 0 { 4804 sys_close(fd) 4805 fsx_puts("[NX-FS TAIL lines=0 total_bytes=0 window_off=0 scanned=0 EMPTY-FILE]\n" as *u8) 4806 return 0 4807 } 4808 // read the LAST scan-window of the file, never the first: a log past the window still yields its end 4809 var off: i64 = 0 4810 if sz > FSX_LINES_SCAN { off = sz - FSX_LINES_SCAN } 4811 if sys_lseek(fd, off, 0) < 0 { 4812 sys_close(fd) 4813 fsx_puts("NX-FS ABSENT: seek failed " as *u8); fsx_puts(path); fsx_puts("\n" as *u8) 4814 return 0 - 1 4815 } 4816 let buf: *u8 = sys_mmap(FSX_LINES_SCAN + 1) 4817 var n: i64 = 0 4818 var sc: i64 = 1 4819 while sc == 1 { 4820 let r: i64 = sys_read(fd, ((buf as i64 + n) as *u8), FSX_LINES_SCAN - n) 4821 if r <= 0 { sc = 0 } else { n = n + r; if n >= FSX_LINES_SCAN { sc = 0 } } 4822 } 4823 sys_close(fd) 4824 if n <= 0 { return fsx_fail(path, 0 - 1) } 4825 // a single trailing newline terminates the last line; it is not an empty extra line 4826 var lim: i64 = n 4827 var terminated: i64 = 0 4828 if buf[n - 1] == (10 as u8) { lim = n - 1; terminated = 1 } 4829 // walk backward for `c` line starts 4830 var p: i64 = lim 4831 var seen: i64 = 0 4832 var start: i64 = 0 4833 var go: i64 = 1 4834 while go == 1 { 4835 if p <= 0 { start = 0; go = 0 } else { 4836 p = p - 1 4837 if buf[p] == (10 as u8) { 4838 seen = seen + 1 4839 if seen >= c { start = p + 1; go = 0 } 4840 } 4841 } 4842 } 4843 var lines_out: i64 = seen + 1 4844 if seen >= c { lines_out = c } 4845 // count the window's lines once so a caller can address the whole file with `lines` afterwards 4846 var wl: i64 = 0 4847 var q: i64 = 0 4848 while q < lim { if buf[q] == (10 as u8) { wl = wl + 1 } q = q + 1 } 4849 wl = wl + 1 4850 let outn: i64 = n - start 4851 if outn > 0 { sys_write(1, ((buf as i64 + start) as *u8), outn) } 4852 if terminated == 0 { fsx_puts("\n" as *u8) } 4853 fsx_puts("[NX-FS TAIL lines=" as *u8); fsx_putn(lines_out) 4854 fsx_puts(" bytes=" as *u8); fsx_putn(outn) 4855 fsx_puts(" total_bytes=" as *u8); fsx_putn(sz) 4856 fsx_puts(" window_off=" as *u8); fsx_putn(off) 4857 fsx_puts(" scanned=" as *u8); fsx_putn(n) 4858 fsx_puts(" window_lines=" as *u8); fsx_putn(wl) 4859 fsx_puts(" last_line_terminated=" as *u8); fsx_putn(terminated) 4860 if off > 0 { fsx_puts(" WINDOW-IS-TAIL-OF-FILE" as *u8) } 4861 if off > 0 { if start == 0 { fsx_puts(" FIRST-LINE-MAY-BE-PARTIAL" as *u8) } } 4862 fsx_puts("]\n" as *u8) 4863 return outn 4864} 4865 4866func fsx_write_denied(path: *u8) -> i64 { 4867 if fsx_denied(path) == 1 { return 1 } 4868 if osf_write_forbidden(path) == 1 { return 1 } 4869 let lp: *u8 = sys_mmap(FSX_PATH_CAP) 4870 let ln: i64 = fsx_lower(path, lp, FSX_PATH_CAP) 4871 if fsx_deny_hit(lp, ln, "allowlist" as *u8) == 1 { return 1 } 4872 return fsx_conf_deny(lp, ln, "fs_write_deny.conf" as *u8) 4873} 4874// ---------- APPEND-ONLY write for journals and boards (2026-09-02) ---------- 4875// ONE O_APPEND write under an exclusive flock: the row lands whole and AFTER every row already there, and 4876// there is no read-modify-write window for a sibling seat to lose it in. MEASURED the same day: a `log|` 4877// row appended to lang.plan by anchored CAS edit (receipt OK bytes=51180) was gone minutes later -- a 4878// sibling's whole-file write had rebuilt the file from its own stale read. A BOARD IS A JOURNAL; JOURNALS 4879// ARE APPENDED, NEVER REWRITTEN. The write deny-list applies unchanged (a new write path must never become 4880// a way into the secret or device namespace). 4881// CONTRACT: body must end in '\n' (a row that does not terminate glues itself to the next seat's row -> 4882// FSX_APP_NONL, file unchanged); an empty body is refused (FSX_APP_EMPTY); when the file's LAST byte is not 4883// a newline (a rewrite left an unterminated tail) one newline is prepended INSIDE the same locked write, so 4884// the caller sees bytes-written == blen + 1 and can announce the heal. Returns bytes written; -2 DENIED; 4885// -3 io (open/lock/short write). 4886const FSX_NL: i64 = 10 // '\n' -- the row terminator this verb requires and heals 4887const FSX_APP_EMPTY: i64 = 0 - 4 // append refused: nothing to append 4888const FSX_APP_NONL: i64 = 0 - 5 // append refused: body does not end in a newline 4889const FSX_SEEK_SET: i64 = 0 // lseek whence: absolute offset (the tail probe) 4890// 1 = the file exists, is non-empty and its last byte is NOT a newline (an unterminated tail); else 0. 4891func fsx_tail_unterminated(path: *u8) -> i64 { 4892 let fd: i64 = sys_openat_rd(path) 4893 if fd < 0 { return 0 } 4894 let sz: i64 = sys_lseek(fd, 0, FSX_SEEK_END) 4895 var unterminated: i64 = 0 4896 if sz > 0 { 4897 if sys_lseek(fd, sz - 1, FSX_SEEK_SET) == sz - 1 { 4898 let lb: *u8 = sys_mmap(16) 4899 if sys_read(fd, lb, 1) == 1 { if lb[0] != (FSX_NL as u8) { unterminated = 1 } } 4900 } 4901 } 4902 sys_close(fd) 4903 return unterminated 4904} 4905func fsx_append(path: *u8, body: *u8, blen: i64) -> i64 { 4906 if fsx_write_denied(path) == 1 { 4907 fsx_puts("NX-FS DENIED: append refused (secret/device-namespace/allowlist deny)\n" as *u8) 4908 return 0 - (2 as i64) 4909 } 4910 if blen <= 0 { return FSX_APP_EMPTY } 4911 if body[blen - 1] != (FSX_NL as u8) { return FSX_APP_NONL } 4912 let heal: i64 = fsx_tail_unterminated(path) 4913 let fd: i64 = sys_openat_append(path, FSX_MODE_RW) 4914 if fd < 0 { return 0 - (3 as i64) } 4915 sys_flock(fd, SYS_LOCK_EX) 4916 let total: i64 = blen + heal 4917 let buf: *u8 = sys_mmap(total + 1) 4918 var i: i64 = 0 4919 if heal == 1 { buf[0] = FSX_NL as u8; i = 1 } 4920 var j: i64 = 0 4921 while j < blen { buf[i] = body[j]; i = i + 1; j = j + 1 } 4922 var off: i64 = 0 4923 while off < total { 4924 let w: i64 = sys_write(fd, ((buf as i64 + off) as *u8), total - off) 4925 if w <= 0 { sys_flock(fd, SYS_LOCK_UN); sys_close(fd); return 0 - (3 as i64) } 4926 off = off + w 4927 } 4928 sys_fsync(fd) 4929 sys_flock(fd, SYS_LOCK_UN) 4930 sys_close(fd) 4931 return total 4932} 4933// ATOMIC full-file write: content lands via <path>.nxw<pid> + fsync + rename, so a reader NEVER sees a 4934// torn file and concurrent writers each land whole (last rename wins; pid suffix = no shared tmp). 4935// Returns bytes written; -2 DENIED; -3 io error (path too long / open / short write / rename). 4936func fsx_write(path: *u8, body: *u8, blen: i64) -> i64 { 4937 if fsx_write_denied(path) == 1 { 4938 fsx_puts("NX-FS DENIED: write refused (secret/device-namespace/allowlist deny)\n" as *u8) 4939 return 0 - (2 as i64) 4940 } 4941 let plen: i64 = vw_slen(path) 4942 if plen + FSX_TMP_ROOM >= FSX_PATH_CAP { return 0 - (3 as i64) } 4943 let tmp: *u8 = sys_mmap(FSX_PATH_CAP) 4944 var i: i64 = 0 4945 while i < plen { tmp[i] = path[i]; i = i + 1 } 4946 let suf: *u8 = ".nxw" as *u8 4947 var s: i64 = 0 4948 while suf[s] != (0 as u8) { tmp[i] = suf[s]; i = i + 1; s = s + 1 } 4949 var pid: i64 = osp_selfpid() 4950 if pid < 0 { pid = 0 } 4951 if pid == 0 { tmp[i] = FSX_ASCII_0 as u8; i = i + 1 } else { 4952 let ds: *u8 = sys_mmap(FSX_TMP_ROOM) 4953 var k: i64 = 0 4954 while pid > 0 { ds[k] = (FSX_ASCII_0 + (pid % FSX_DEC)) as u8; pid = pid / FSX_DEC; k = k + 1 } 4955 while k > 0 { tmp[i] = ds[k-1]; i = i + 1; k = k - 1 } 4956 } 4957 tmp[i] = 0 as u8 4958 let fd: i64 = sys_openat_wr(tmp, FSX_MODE_RW) 4959 if fd < 0 { return 0 - (3 as i64) } 4960 let saved: *NxFileWriteResult = sys_mmap(__size_of(NxFileWriteResult)) as *NxFileWriteResult 4961 if (saved as i64) < 0 { sys_close(fd); sys_unlinkat(tmp); return 0 - (3 as i64) } 4962 let write_rc: i64 = fio_write_sync_fd(fd, body, blen, saved) 4963 if write_rc < 0 { 4964 fsx_puts("NX-FS WRITE-FAILED stage="); fsx_puts(saved.stage) 4965 fsx_puts(" code="); fsx_putn(saved.code) 4966 fsx_puts(" written="); fsx_putn(saved.written) 4967 fsx_puts(" close_code="); fsx_putn(saved.close_code) 4968 fsx_puts(" path="); fsx_puts(path) 4969 fsx_puts(" publication=not-attempted\n") 4970 sys_munmap(saved as *u8, __size_of(NxFileWriteResult)) 4971 sys_unlinkat(tmp) 4972 return 0 - (3 as i64) 4973 } 4974 sys_munmap(saved as *u8, __size_of(NxFileWriteResult)) 4975 // PRESERVE the original file's mode across tmp+rename (debt eaten 2026-07-18: an edit of an 4976 // executable script used to land 0644 -- the exec bit vanished and the cron runner broke with 4977 // rc=126). st_mode = u32 at stat offset 24; keep the permission bits (low 12) only. 4978 let sb: *u8 = sys_mmap(160) 4979 if sys_fstatat(path, sb) == 0 { 4980 let m0: i64 = sb[24] as i64 4981 let m1: i64 = sb[25] as i64 4982 let om: i64 = (m0 + (m1 * 256)) & FSX_MAGIC_4095 4983 if om != FSX_MODE_RW { nx_chmod(tmp, om) } 4984 } 4985 // The same law at the last possible failure: if the rename cannot complete, the tmp is not a 4986 // partial result anyone wants -- it is litter wearing the shape of a real file. Take it with us. 4987 if sys_renameat(tmp, path) < 0 { sys_unlinkat(tmp); return 0 - (3 as i64) } 4988 return blen 4989} 4990// count non-overlapping occurrences of nee[0..nl) in hay[0..hn) 4991func fsx_count_occ(hay: *u8, hn: i64, nee: *u8, nl: i64) -> i64 { 4992 if nl <= 0 { return 0 } 4993 var c: i64 = 0 4994 var i: i64 = 0 4995 while i + nl <= hn { 4996 var m: i64 = 1 4997 var j: i64 = 0 4998 while j < nl { if hay[i+j] != nee[j] { m = 0; j = nl } else { j = j + 1 } } 4999 if m == 1 { c = c + 1; i = i + nl } else { i = i + 1 } 5000 } 5001 return c 5002} 5003// replace occurrences of nee with rep into out (allf=0: first only; 1: all). Returns new length; -1 overflow. 5004func fsx_replace(hay: *u8, hn: i64, nee: *u8, nl: i64, rep: *u8, rl: i64, out: *u8, ocap: i64, allf: i64) -> i64 { 5005 var o: i64 = 0 5006 var i: i64 = 0 5007 var used: i64 = 0 5008 while i < hn { 5009 var m: i64 = 0 5010 if i + nl <= hn { if nl > 0 { 5011 var ok: i64 = 1 5012 if allf == 0 { if used == 1 { ok = 0 } } 5013 if ok == 1 { 5014 m = 1 5015 var j: i64 = 0 5016 while j < nl { if hay[i+j] != nee[j] { m = 0; j = nl } else { j = j + 1 } } 5017 } 5018 } } 5019 if m == 1 { 5020 if o + rl > ocap { return 0 - 1 } 5021 var k: i64 = 0 5022 while k < rl { out[o] = rep[k]; o = o + 1; k = k + 1 } 5023 i = i + nl 5024 used = 1 5025 } else { 5026 if o + 1 > ocap { return 0 - 1 } 5027 out[o] = hay[i] 5028 o = o + 1 5029 i = i + 1 5030 } 5031 } 5032 return o 5033} 5034// EDIT: exact-string replace with the UNIQUENESS contract (the Claude-Edit SOTA semantic): 5035// 0 matches -> -6 NOMATCH (file untouched); >1 without allf -> -7 AMBIGUOUS (file untouched); 5036// otherwise replace (allf=1: every occurrence) and land ATOMICALLY via fsx_write. 5037// Returns new byte length; -1 absent; -2 DENIED; -3 io/overflow; -6 nomatch; -7 ambiguous. 5038func fsx_edit(path: *u8, olds: *u8, news: *u8, allf: i64) -> i64 { 5039 if fsx_write_denied(path) == 1 { 5040 fsx_puts("NX-FS DENIED: edit refused (secret/device-namespace/allowlist deny)\n" as *u8) 5041 return 0 - 2 5042 } 5043 let region: *NxFileReadRegion = sys_mmap(__size_of(NxFileReadRegion)) as *NxFileReadRegion 5044 if (region as i64) <= 0 { return 0 - 3 } 5045 fio_region_init(region) 5046 if fio_region_open(path, region) != 0 { 5047 sys_munmap(region as *u8, __size_of(NxFileReadRegion)) 5048 return 0 - 1 5049 } 5050 let n: i64 = region.total 5051 if n <= 0 { 5052 fio_region_close(region) 5053 sys_munmap(region as *u8, __size_of(NxFileReadRegion)) 5054 return 0 - 1 5055 } 5056 let buf: *u8 = sys_mmap(n) 5057 if (buf as i64) <= 0 { 5058 fio_region_close(region) 5059 sys_munmap(region as *u8, __size_of(NxFileReadRegion)) 5060 return 0 - 3 5061 } 5062 let readn: i64 = fio_region_next(region, buf, n) 5063 sys_munmap(region as *u8, __size_of(NxFileReadRegion)) 5064 if readn != n { sys_munmap(buf,n); return 0 - 3 } 5065 let ol: i64 = vw_slen(olds) 5066 let rl: i64 = vw_slen(news) 5067 let cnt: i64 = fsx_count_occ(buf,n,olds,ol) 5068 if cnt == 0 { sys_munmap(buf,n); return 0 - FSX_RC_NOMATCH } 5069 if cnt > 1 && allf == 0 { sys_munmap(buf,n); return 0 - FSX_RC_AMBIG } 5070 // Derive exact output extent from measured input and replacement count. 5071 // The numeric bound is the signed length representation, not a file-size policy. 5072 let delta: i64 = rl - ol 5073 if delta > 0 { 5074 if cnt > (9223372036854775807 - n) / delta { 5075 sys_munmap(buf,n); return 0 - 3 5076 } 5077 } 5078 let expected: i64 = n + cnt * delta 5079 var capacity: i64 = expected 5080 if capacity == 0 { capacity = 1 } 5081 let out: *u8 = sys_mmap(capacity) 5082 if (out as i64) <= 0 { sys_munmap(buf,n); return 0 - 3 } 5083 let nn: i64 = fsx_replace(buf,n,olds,ol,news,rl,out,capacity,allf) 5084 var result: i64 = 0 - 3 5085 if nn == expected { result = fsx_write(path,out,nn) } 5086 sys_munmap(out,capacity) 5087 sys_munmap(buf,n) 5088 return result 5089} 5090 5091// SELF-ANCHORED EDIT PREDICATE (pure, no I/O). Does the replacement CONTAIN its own anchor? 5092// UNIQUENESS IS TESTED AGAINST THE PRE-IMAGE; THE RETRY GUARANTEE IS A CLAIM ABOUT THE POST-IMAGE. 5093// They coincide ONLY when the replacement destroys its anchor. When `news` contains `olds` the anchor 5094// SURVIVES the apply and is STILL UNIQUE, so a retry returns OK whether or not the first call landed -- 5095// the three-state table (OK=had-not-landed / NOMATCH=had-landed) collapses to ONE state and OK carries 5096// ZERO discriminating information. 5097// MEASURED 2026-09-04 over 12,806 edit calls in this laptop's transcripts: 8,308 true replaces, 4,343 5098// self-anchored (339 permil), 155 identity, sum reconciles. Seats re-issue the unsafe shape at 95 permil 5099// against a 99 permil control on the safe shape -- i.e. the retry doctrine is applied UNIFORMLY AND 5100// BLINDLY because nothing in the tool discriminated by shape. Three double-applies are confirmed in the 5101// record, plus the 2026-09-04 incident that produced two definitions of ba_confirmed and broke the gate 5102// that admits every build on this estate. 5103// The law was already banked on 2026-08-20 in nx_atomic_publish as CALLER advice keyed on a SELF-DECLARED 5104// kind=. A caller can get that declaration wrong, and one did. The primitive holds BOTH strings, so the 5105// kind is DERIVABLE rather than declarable -- and deriving it here is what makes writer and reader unable 5106// to disagree, instead of asking them to agree by discipline. 5107// Returns 1 self-anchored (retry UNSAFE) | 0 true replace (retry exact-safe). 5108// An empty anchor is NOT self-anchored: fsx_edit never reaches the apply with ol==0. 5109func fsx_edit_self_anchored(olds: *u8, news: *u8) -> i64 { 5110 let ol: i64 = vw_slen(olds) 5111 if ol == 0 { return 0 } 5112 if fsx_count_occ(news, vw_slen(news), olds, ol) > 0 { return 1 } 5113 return 0 5114} 5115 5116// ls (declared below the self-anchored-edit predicate): one entry per line "<t> <name>" (t: d=dir f=file l=link o=other; . and .. skipped). 5117// Returns entry count; -1 if the dir cannot be opened. 5118// PAGING (2026-08-05). The cap was always honest -- it declared total= and truncated=1 -- but an 5119// honest refusal is not access: knowledge/status/ holds 1027 entries, so 827 of them were simply 5120// UNREACHABLE through this tool, and a worker that listed it reported "queue empty" over a job that 5121// was sitting right there. u2605u2605u2605u2605u2605DECLARING A TRUNCATION IS NOT THE SAME AS OFFERING A WAY PAST IT -- 5122// a loud cap with no next page is still a wall. `skip` is that way past. 5123// Contract preserved exactly (rule 19): fsx_ls(dir) keeps its old signature and behaviour. 5124func fsx_ls(dir: *u8) -> i64 { return fsx_ls_from(dir, 0) } 5125 5126func fsx_ls_from(dir: *u8, skip: i64) -> i64 { 5127 let fd: i64 = sys_openat_rd(dir) 5128 if fd < 0 { return fsx_fail(dir, fd) } 5129 let dbuf: *u8 = sys_mmap(FSX_DENT_BUF) 5130 var cnt: i64 = 0 5131 var shown: i64 = 0 5132 var run: i64 = 1 5133 while run == 1 { 5134 let n: i64 = sys_getdents64(fd, dbuf, FSX_DENT_BUF) 5135 if n <= 0 { run = 0 } else { 5136 var off: i64 = 0 5137 while off < n { 5138 let rec: *u8 = ((dbuf as i64 + off) as *u8) 5139 let reclen: i64 = dirent_reclen(rec) 5140 if reclen <= 0 { off = n } else { 5141 let name: *u8 = dirent_name(rec) 5142 // skip "." and ".." 5143 var isdot: i64 = 0 5144 if fsx_seq(name, "." as *u8) == 1 { isdot = 1 } 5145 if fsx_seq(name, ".." as *u8) == 1 { isdot = 1 } 5146 if isdot == 0 { 5147 if cnt >= skip { if shown < FSX_LS_CAP { 5148 let t: i64 = dirent_type(rec) 5149 if t == DT_DIR { fsx_puts("d " as *u8) } else { 5150 if t == DT_REG { fsx_puts("f " as *u8) } else { 5151 if t == DT_LNK { fsx_puts("l " as *u8) } else { fsx_puts("o " as *u8) } } } 5152 fsx_puts(name) 5153 fsx_puts("\n" as *u8) 5154 shown = shown + 1 5155 } } 5156 cnt = cnt + 1 5157 } 5158 off = off + reclen 5159 } 5160 } 5161 } 5162 } 5163 sys_close(fd) 5164 // SCALE-LAW: cap the emitted list but ALWAYS declare the true total; truncation is LOUD not silent 5165 fsx_puts("NX-FS-LS skip=" as *u8) 5166 fsx_putn(skip) 5167 fsx_puts(" shown=" as *u8) 5168 fsx_putn(shown) 5169 fsx_puts(" total=" as *u8) 5170 fsx_putn(cnt) 5171 // u26a0THE OLD PREDICATE (cnt > shown) BECOMES A LIE THE MOMENT skip EXISTS: the LAST page would 5172 // still report truncated=1 forever, so a caller paging until truncated=0 would never stop. 5173 // What actually remains is everything past the window just emitted. 5174 if cnt > skip + shown { fsx_puts(" truncated=1 (more remain -- next page: ls <dir> " as *u8); fsx_putn(skip + shown); fsx_puts(")\n" as *u8) } else { fsx_puts(" truncated=0\n" as *u8) } 5175 return cnt 5176} 5177 5178// ==== THE CLAIM-OR-OUT VERB (ES26, 2026-09-06) ==== 5179// The most common ritual in the estate's action journal is two reads of the job lane -- the terminal marker 5180// (.claim) and then the output (.out): 120,106 adjacent pairs and 87,785 triples measured by nx_actlog steps. 5181// ONE call answers both. The marker decides the state and only a DONE marker earns the read of the output, so a 5182// running job never reads as dead, a never-claimed id never reads as running, and an empty output never reads as 5183// still working. States are NAMED, never guessed: a marker with no state token this reader knows is UNPARSED and 5184// printed verbatim as data. The id is digits only, so the verb cannot be aimed outside the directory it is given. 5185// fsx_job_at takes the directory so the gate drives it on a /tmp fixture; fsx_job is the production binding. 5186const FSX_JOB_DIR: *u8 = "_jobs/" 5187const FSX_JOB_PFX: *u8 = "job_" 5188const FSX_JOB_CLAIM: *u8 = ".claim" 5189const FSX_JOB_OUT: *u8 = ".out" 5190const FSX_JOB_IDMAX: i64 = 24 // a job id is an epoch-shaped integer; longer than this is not an id 5191const FSX_JOB_NOSUCH: i64 = 1 // no marker: the id was never claimed (unknown id, or the lane has not claimed it yet) 5192const FSX_JOB_RUNNING: i64 = 2 // marker reads state=CLAIMED 5193const FSX_JOB_DONE: i64 = 3 // marker reads state=DONE with bytes>0: the output was printed 5194const FSX_JOB_DONE_EMPTY: i64 = 4 // marker reads state=DONE with bytes=0: the tool produced NOTHING 5195const FSX_JOB_UNPARSED: i64 = 5 // marker present, no state token this reader knows: printed verbatim 5196const FSX_JOB_REFUSED: i64 = 6 // id is not digits-only 5197const FSX_JOB_OUT_ABSENT: i64 = 7 // marker says DONE with bytes>0 but the output file is unreadable 5198const FSX_RC_JOB_RUNNING: i64 = 8 // CLI exit for RUNNING, distinct from every other fs exit code 5199const FSX_ASCII_9: i64 = 57 // '9' (decimal parse upper bound) 5200// first offset of needle in buf[0..n), -1 when absent (flag-terminated compare, the cursor is never the sentinel) 5201func fsx_find(buf: *u8, n: i64, needle: *u8) -> i64 { 5202 var m: i64 = 0 5203 while needle[m] != (0 as u8) { m = m + 1 } 5204 if m == 0 { return 0 - 1 } 5205 var i: i64 = 0 5206 while i + m <= n { 5207 var j: i64 = 0 5208 var same: i64 = 1 5209 while j < m { if buf[i + j] != needle[j] { same = 0 } j = j + 1 } 5210 if same == 1 { return i } 5211 i = i + 1 5212 } 5213 return 0 - 1 5214} 5215// the integer right after `key` in buf[0..n); -1 when the key is absent or carries no digits 5216func fsx_kv_int(buf: *u8, n: i64, key: *u8) -> i64 { 5217 let at: i64 = fsx_find(buf, n, key) 5218 if at < 0 { return 0 - 1 } 5219 var kl: i64 = 0 5220 while key[kl] != (0 as u8) { kl = kl + 1 } 5221 var f: i64 = at + kl 5222 var v: i64 = 0 5223 var nd: i64 = 0 5224 var scan: i64 = 1 5225 while scan == 1 { 5226 if f >= n { scan = 0 } else { 5227 let c: i64 = buf[f] as i64 5228 if c < FSX_ASCII_0 { scan = 0 } else { if c > FSX_ASCII_9 { scan = 0 } else { v = v * (10 as i64) + (c - FSX_ASCII_0); nd = nd + 1; f = f + 1 } } 5229 } 5230 } 5231 if nd == 0 { return 0 - 1 } 5232 return v 5233} 5234func fsx_job_id_ok(id: *u8) -> i64 { 5235 var i: i64 = 0 5236 while id[i] != (0 as u8) { 5237 let c: i64 = id[i] as i64 5238 if c < FSX_ASCII_0 { return 0 } 5239 if c > FSX_ASCII_9 { return 0 } 5240 i = i + 1 5241 } 5242 if i == 0 { return 0 } 5243 if i > FSX_JOB_IDMAX { return 0 } 5244 return 1 5245} 5246// <dir><pfx><id><sfx> into out; returns the length 5247func fsx_job_path(dir: *u8, id: *u8, sfx: *u8, out: *u8) -> i64 { 5248 let pfx: *u8 = FSX_JOB_PFX 5249 var o: i64 = 0 5250 var i: i64 = 0 5251 while dir[i] != (0 as u8) { out[o] = dir[i]; o = o + 1; i = i + 1 } 5252 i = 0 5253 while pfx[i] != (0 as u8) { out[o] = pfx[i]; o = o + 1; i = i + 1 } 5254 i = 0 5255 while id[i] != (0 as u8) { out[o] = id[i]; o = o + 1; i = i + 1 } 5256 i = 0 5257 while sfx[i] != (0 as u8) { out[o] = sfx[i]; o = o + 1; i = i + 1 } 5258 out[o] = 0 as u8 5259 return o 5260} 5261// returns the FSX_JOB_* state; prints the marker verbatim and, on DONE with bytes>0, the output through fsx_read 5262// (truncation marked, deny-list inherited) 5263func fsx_job_at(dir: *u8, id: *u8) -> i64 { 5264 if fsx_job_id_ok(id) == 0 { 5265 fsx_puts("NX-FS-JOB REFUSED: the id must be digits only (a job number), got: " as *u8); fsx_puts(id); fsx_puts("\n" as *u8) 5266 return FSX_JOB_REFUSED 5267 } 5268 let cp: *u8 = sys_mmap(FSX_PATH_CAP) 5269 let op: *u8 = sys_mmap(FSX_PATH_CAP) 5270 fsx_job_path(dir, id, FSX_JOB_CLAIM, cp) 5271 fsx_job_path(dir, id, FSX_JOB_OUT, op) 5272 let cb: *u8 = sys_mmap(FSX_MAGIC_4095 + 1) 5273 let cn: i64 = vw_read(cp, cb, FSX_MAGIC_4095) 5274 fsx_puts("NX-FS-JOB id=" as *u8); fsx_puts(id) 5275 if cn <= 0 { 5276 fsx_puts(" NOSUCH: no marker at " as *u8); fsx_puts(cp) 5277 fsx_puts(" -- the id was never claimed by the lane (unknown id, or not claimed yet); a claimed job carries state=CLAIMED\n" as *u8) 5278 return FSX_JOB_NOSUCH 5279 } 5280 fsx_puts(" marker=" as *u8) 5281 var cl: i64 = cn 5282 var strip: i64 = 1 5283 while strip == 1 { if cl <= 0 { strip = 0 } else { if cb[cl - 1] == (FSX_NL as u8) { cl = cl - 1 } else { strip = 0 } } } 5284 sys_write(1, cb, cl) 5285 if fsx_find(cb, cn, "state=DONE" as *u8) >= 0 { 5286 let b: i64 = fsx_kv_int(cb, cn, "bytes=" as *u8) 5287 if b == 0 { 5288 fsx_puts(" DONE-EMPTY: the tool produced NOTHING (bytes=0); it is not still working\n" as *u8) 5289 return FSX_JOB_DONE_EMPTY 5290 } 5291 fsx_puts(" DONE: output follows\n" as *u8) 5292 let r: i64 = fsx_read(op, 0) 5293 if r > 0 { return FSX_JOB_DONE } 5294 return FSX_JOB_OUT_ABSENT 5295 } 5296 if fsx_find(cb, cn, "state=CLAIMED" as *u8) >= 0 { 5297 fsx_puts(" RUNNING: claimed, no terminal state yet -- the lane rewrites this marker atomically when the job ends\n" as *u8) 5298 return FSX_JOB_RUNNING 5299 } 5300 fsx_puts(" UNPARSED: no state token this reader knows -- the marker above is data, decide from it\n" as *u8) 5301 return FSX_JOB_UNPARSED 5302} 5303func fsx_job(id: *u8) -> i64 { return fsx_job_at(FSX_JOB_DIR, id) } 5304 5305// Exclusive artifact creation for the current Linux x86-64 host backend. 5306// Complete bytes are fsynced before RENAME_NOREPLACE. Unsupported filesystems fail closed. 5307// This is not a portable-ISA claim; the rename ABI matches the existing host syscall seam. 5308 5309const FXC_OPEN_EXCLUSIVE: i64 = 0xc1 // O_WRONLY | O_CREAT | O_EXCL 5310const FXC_RENAMEAT2_X86: i64 = 316 5311const FXC_RENAME_NOREPLACE: i64 = 1 5312const FXC_EXISTS: i64 = 0 - 17 5313const FXC_IO: i64 = 0 - 3 5314func fxc_create(path: *u8, body: *u8, n: i64) -> i64 { 5315 if fsx_write_denied(path) == 1 { return 0 - 2 } 5316 let plen: i64 = vw_slen(path) 5317 if plen + FSX_TMP_ROOM >= FSX_PATH_CAP { return FXC_IO } 5318 let tmp: *u8 = sys_mmap(FSX_PATH_CAP) 5319 var i: i64 = 0 5320 while i < plen { tmp[i] = path[i]; i = i + 1 } 5321 let suffix: *u8 = ".nxc" as *u8 5322 var j: i64 = 0 5323 while j < 4 { tmp[i] = suffix[j]; i = i+1; j = j+1 } 5324 i = nxi_buf(tmp,i,osp_selfpid()); tmp[i] = 0 as u8 5325 let fd: i64 = __syscall(SYS_OPENAT,AT_FDCWD,tmp,FXC_OPEN_EXCLUSIVE,MODE_0644,0,0) 5326 if fd < 0 { return FXC_IO } 5327 var off: i64 = 0 5328 while off < n { 5329 let w: i64 = sys_write(fd,((body as i64)+off) as *u8,n-off) 5330 if w <= 0 { sys_close(fd);sys_unlinkat(tmp);return FXC_IO } 5331 off = off+w 5332 } 5333 let sync: i64 = sys_fsync(fd) 5334 sys_close(fd) 5335 if sync < 0 { sys_unlinkat(tmp);return FXC_IO } 5336 let installed: i64 = __syscall(FXC_RENAMEAT2_X86,AT_FDCWD,tmp,AT_FDCWD,path,FXC_RENAME_NOREPLACE,0) 5337 if installed != 0 { 5338 // This process created tmp with O_EXCL; only its own uncommitted scratch is removed. 5339 sys_unlinkat(tmp) 5340 return installed 5341 } 5342 return n 5343} 5344 5345 5346 5347 5348const GPA_HEADER_BYTES: i64 = 8 5349 5350struct GpaWasmCursor { 5351 data: *u8, 5352 size: i64, 5353 pos: i64, 5354} 5355struct GpaMemory { 5356 minimum: i64, 5357 maximum: i64, 5358 count: i64, 5359} 5360// WebAssembly u32 LEB128: at most five bytes, with only four payload bits in the last. 5361func gpa_u32(c: *GpaWasmCursor) -> i64 { 5362 var value: i64 = 0 5363 var shift: i64 = 0 5364 while shift < 35 { 5365 if c.pos >= c.size { return -1 } 5366 let b: i64 = c.data[c.pos] as i64 5367 c.pos = c.pos+1 5368 if shift == 28 { if b > 15 { return -1 } } 5369 value = value | ((b & 127) << shift) 5370 if (b & 128) == 0 { return value } 5371 shift = shift+7 5372 } 5373 return -1 5374} 5375func gpa_wasm_header(data: *u8,n: i64) -> i64 { 5376 if n < GPA_HEADER_BYTES { return 0 } 5377 let header: *u8 = "\x00asm\x01\x00\x00\x00" as *u8 5378 return gpa_same(data,GPA_HEADER_BYTES,header,GPA_HEADER_BYTES) 5379} 5380func gpa_wasm_name(c: *GpaWasmCursor,name: *u8) -> i64 { 5381 let n: i64 = gpa_u32(c) 5382 if n < 0 || n > c.size-c.pos { return 0 } 5383 let ok: i64 = gpa_same((c.data as i64+c.pos) as *u8,n,name,vw_slen(name)) 5384 c.pos = c.pos+n 5385 return ok 5386} 5387// This packager supports the compiler's one-memory, no-other-import twin contract. 5388// Other valid Wasm layouts require a separate supported contract, never silent guessing. 5389func gpa_memory_section(data: *u8,n: i64,shared: i64,m: *GpaMemory) -> i64 { 5390 let c: *GpaWasmCursor = sys_mmap(__size_of(GpaWasmCursor)) as *GpaWasmCursor 5391 c.data=data; c.size=n; c.pos=0 5392 var ok: i64 = 1 5393 if gpa_u32(c) != 1 { ok=0 } 5394 if shared == 1 { 5395 if gpa_wasm_name(c,"env") != 1 { ok=0 } 5396 if gpa_wasm_name(c,"memory") != 1 { ok=0 } 5397 if gpa_u32(c) != 2 { ok=0 } 5398 } 5399 let flags: i64 = gpa_u32(c) 5400 if shared == 1 { if flags != 3 { ok=0 } } else { if flags != 0 && flags != 1 { ok=0 } } 5401 let minimum: i64 = gpa_u32(c) 5402 var maximum: i64 = minimum 5403 if (flags & 1) == 1 { maximum=gpa_u32(c) } 5404 // 2^16 pages is the wasm32 address-space ceiling, not a workload budget. 5405 if minimum <= 0 || maximum < minimum || maximum > 65536 { ok=0 } 5406 if c.pos != n { ok=0 } 5407 if m.count != 0 { ok=0 } 5408 if ok == 1 { m.minimum=minimum; m.maximum=maximum; m.count=1 } 5409 sys_munmap(c as *u8,__size_of(GpaWasmCursor)) 5410 return ok 5411} 5412func gpa_body_section(c: *GpaWa