From 89de2df49b8fca5954b0c68c25eb180083851716 Mon Sep 17 00:00:00 2001 From: x_ror <16686943+x-ror@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:50:03 +0200 Subject: [PATCH 1/3] =?UTF-8?q?build(fmt):=20format=20Odin=20and=20C/C++?= =?UTF-8?q?=20to=20one=20style=20=E2=80=94=20tabs,=20120=20columns?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - odinfmt.json: tabs (width 4), 120 columns, sorted imports. Applied to cmd/lava, pkg/jsc, pkg/runtime and pkg/std/sqlite. - .clang-format: the owner's C/C++ style with tabs (width 4) and 120 columns. Applied to pkg/jsc/jsc_init_windows.cpp; vendored picohttpparser opts out. - `make fmt` runs odinfmt (when ODINFMT points at it — it ships with the OLS extension), strip-semicolon, then clang-format. - CLAUDE.md §4: the formatters, and the declaration order (imports, constants, types, procedures), which no formatter enforces. The same configuration Larva adopted in x-ror/larva#71. Formatting only. Checked: `make check` (all three targets), `make build`, a `lava eval` touching timers, microtasks, URL and require; every mutation-manifest `find` still matches exactly once. No tests run: paused for this phase. Co-Authored-By: Claude Opus 5.5 --- .clang-format | 22 +++ CLAUDE.md | 9 +- Makefile | 12 +- cmd/lava/buffer_reentrancy_test.odin | 5 +- cmd/lava/dns_alloc_test.odin | 2 +- cmd/lava/eval_report_hook_test.odin | 2 +- cmd/lava/fs_write_payload_test.odin | 4 +- cmd/lava/global_surface_test.odin | 16 +- cmd/lava/host_native_registry_test.odin | 31 +--- cmd/lava/lazy_builtins_test.odin | 49 +++++- cmd/lava/module_cache_alloc_test.odin | 2 +- cmd/lava/net_teardown_stress_test.odin | 6 +- cmd/lava/nocopy_bytes_alloc_test.odin | 2 +- cmd/lava/pool_cancel_hooks_test.odin | 2 +- cmd/lava/primordials_test.odin | 1 - cmd/lava/regexp_pollution_test.odin | 2 +- cmd/lava/timer_binding_alloc_test.odin | 7 +- odinfmt.json | 8 + pkg/jsc/bindings.odin | 6 +- pkg/jsc/host_function.odin | 69 ++++++-- pkg/jsc/jsc_init.odin | 14 +- pkg/jsc/jsc_init_windows.cpp | 39 ++--- pkg/jsc/private_string.odin | 48 ++++-- pkg/jsc/private_value.odin | 9 +- pkg/jsc/private_view.odin | 44 +++-- pkg/runtime/buffer.odin | 16 +- pkg/runtime/buffer_simd.odin | 23 ++- pkg/runtime/dns.odin | 36 ++-- pkg/runtime/environment.odin | 51 +----- pkg/runtime/errors.odin | 11 +- .../eventloop_close_running_test.odin | 8 +- .../eventloop/eventloop_close_test.odin | 9 +- .../eventloop_close_wakeup_test.odin | 7 +- .../eventloop/eventloop_fd_lifetime_test.odin | 13 +- .../eventloop/eventloop_proactor_test.odin | 23 ++- pkg/runtime/eventloop/eventloop_test.odin | 24 +-- pkg/runtime/eventloop/loop.odin | 51 ++---- pkg/runtime/eventloop/loop_linux.odin | 102 ++++------- pkg/runtime/eventloop/loop_windows.odin | 21 +-- pkg/runtime/fetch.odin | 98 +++++------ pkg/runtime/fetch_darwin.odin | 21 ++- pkg/runtime/fetch_linux.odin | 21 +-- pkg/runtime/fetch_tls.odin | 15 +- pkg/runtime/fetch_transport.odin | 9 +- pkg/runtime/fetch_windows.odin | 22 +-- pkg/runtime/fs.odin | 139 +++++++++------ pkg/runtime/fs_fd_posix.odin | 10 +- pkg/runtime/fs_fd_windows.odin | 10 +- pkg/runtime/globals.odin | 104 +++-------- pkg/runtime/host_natives.odin | 32 ++-- pkg/runtime/http.odin | 8 +- pkg/runtime/module_resolution.odin | 5 +- pkg/runtime/net.odin | 99 ++--------- pkg/runtime/os_linux.odin | 6 +- pkg/runtime/os_windows.odin | 17 +- pkg/runtime/picohttpparser/.clang-format | 4 + .../picohttpparser/picohttpparser.odin | 10 +- pkg/runtime/require.odin | 7 +- pkg/runtime/runtime.odin | 162 +++++++++--------- pkg/runtime/sqlite.odin | 20 +-- pkg/runtime/tls.odin | 3 +- pkg/runtime/tls_darwin.odin | 6 +- pkg/runtime/typed_array.odin | 9 +- pkg/runtime/workers.odin | 8 +- pkg/runtime/workers_linux.odin | 4 +- pkg/runtime/workers_test.odin | 20 ++- pkg/std/sqlite/sqlite.odin | 8 +- 67 files changed, 783 insertions(+), 900 deletions(-) create mode 100644 .clang-format create mode 100644 odinfmt.json create mode 100644 pkg/runtime/picohttpparser/.clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..18efa895 --- /dev/null +++ b/.clang-format @@ -0,0 +1,22 @@ +# C/C++ style for the code we own (pkg/jsc): tabs (width 4, as the Odin code), +# attached braces, 120 columns, `T *p`. Editors that format on save pick this up; `make fmt` applies it. +BasedOnStyle: LLVM +Language: Cpp +Standard: c++17 +IndentWidth: 4 +UseTab: Always +TabWidth: 4 +ColumnLimit: 120 +BreakBeforeBraces: Attach +NamespaceIndentation: All +PointerAlignment: Right +ReferenceAlignment: Right +AccessModifierOffset: -4 +AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +IncludeBlocks: Preserve +# #includes sorted within each blank-line-separated block. clang-format cannot reorder +# declarations; the types-before-functions order is a convention (CLAUDE.md §4). +SortIncludes: CaseSensitive diff --git a/CLAUDE.md b/CLAUDE.md index 137081c5..0a91b6c1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -149,7 +149,14 @@ appears in CI, read the code or shrink the CPU set; do not just re-run. wrappers exist only for **measured** hot natives; cold natives use the generic `host_native_create` path. The UTF-16→UTF-8 bridge belongs in `pkg/jsc`, not `environment.odin`. -- `make fmt` (`odin strip-semicolon`) before committing Odin. +- `make fmt` before committing: odinfmt (`odinfmt.json`: tabs, 120 columns, sorted + imports) and `odin strip-semicolon` for Odin, clang-format (`.clang-format`: tabs, + 120 columns) for C/C++. odinfmt ships with the OLS extension; pass + `ODINFMT=/path/to/odinfmt` when it is not on PATH. +- **Declaration order in a file**, Odin and C alike: imports/includes (sorted), then + constants, then types, then procedures — public ones first, private helpers last. + The formatters sort imports and includes; nothing reorders declarations, so this is + on the author. Do not retrofit existing files for it alone. ### Contract comments diff --git a/Makefile b/Makefile index 9b7ade42..dd804376 100644 --- a/Makefile +++ b/Makefile @@ -51,7 +51,7 @@ help: @printf '%s\n' ' make check-primordials Prototype-pollution ratchet (UPDATE=1 to lower; RAISE=--allow-raise)' @printf '%s\n' ' make check-jsc Locate JavaScriptCore dev files with install hints' @printf '%s\n' ' make check-native Verify native build dependencies via pkg-config' - @printf '%s\n' ' make fmt Strip optional semicolons in Odin sources' + @printf '%s\n' ' make fmt Format Odin (odinfmt, strip-semicolon) and C/C++ (clang-format)' @printf '%s\n' '' @printf '%s\n' 'Test' @printf '%s\n' ' make test Odin unit tests + oracle suites (alias of test-all on Unix)' @@ -360,9 +360,19 @@ test-lava-nohostfn: build # "lava:pkg/runtime", so without it strip-semicolon cannot parse the package and # the target exits non-zero. CI's "Format (Odin)" step runs this and requires a # clean diff afterwards. +ODINFMT ?= odinfmt + +# Odin: odinfmt with odinfmt.json (tabs, 120 columns, sorted imports), then +# strip-semicolon. odinfmt ships with the OLS editor extension and is not on PATH by +# default; point ODINFMT at it. C/C++: clang-format with .clang-format; vendored +# picohttpparser opts out (its own .clang-format). fmt: + @if command -v $(ODINFMT) >/dev/null 2>&1; then \ + for d in cmd/lava pkg/jsc pkg/runtime pkg/std/sqlite; do $(ODINFMT) -w $$d >/dev/null; done; \ + else echo 'make fmt: odinfmt not found; set ODINFMT=/path/to/odinfmt'; fi $(ODIN) strip-semicolon cmd/lava -collection:lava=. $(ODIN) strip-semicolon pkg/jsc -no-entry-point + clang-format -i pkg/jsc/*.cpp # `rm` isn't a Windows command and can't take the $(RUNSCRIPT) prefix (bash would treat # `rm` as a script), so invoke the shell explicitly: $(SHELL) is Git Bash on Windows and diff --git a/cmd/lava/buffer_reentrancy_test.odin b/cmd/lava/buffer_reentrancy_test.odin index 84b33fca..ca365880 100644 --- a/cmd/lava/buffer_reentrancy_test.odin +++ b/cmd/lava/buffer_reentrancy_test.odin @@ -112,10 +112,7 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { // bytes; the call must be a no-op (undefined return, no write). { view, _ := reentrancy_setup(ctx) - evil2 := reentrancy_eval( - ctx, - "({ valueOf: function () { globalThis.__ab.transfer(); return 2; } })", - ) + evil2 := reentrancy_eval(ctx, "({ valueOf: function () { globalThis.__ab.transfer(); return 2; } })") args := [2]jsc.JSValueRef{view, evil2} r := lava.buffer_swap_cb(ctx, nil, nil, 2, raw_data(args[:]), &exc) testing.expect(t, jsc.JSValueIsUndefined(ctx, r), "swapInPlace must no-op on a detached target") diff --git a/cmd/lava/dns_alloc_test.odin b/cmd/lava/dns_alloc_test.odin index 9d9e18a8..ac8c4efa 100644 --- a/cmd/lava/dns_alloc_test.odin +++ b/cmd/lava/dns_alloc_test.odin @@ -5,8 +5,8 @@ import "base:runtime" import "core:mem" import "core:sync" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Guards the localized dns/fetch allocator fix (Dns_Lookup_Request.allocator). The // hostname is cloned inside the native dns lookup callback (a `proc "c"` where context diff --git a/cmd/lava/eval_report_hook_test.odin b/cmd/lava/eval_report_hook_test.odin index 2b342c54..77032d8e 100644 --- a/cmd/lava/eval_report_hook_test.odin +++ b/cmd/lava/eval_report_hook_test.odin @@ -3,8 +3,8 @@ package main import "core:strings" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Pins eval's `report` hook (runtime.odin, Result_Hook): it fires exactly once per eval, // with the Result eval returns, and BEFORE eval's deferred teardown — the loop is not diff --git a/cmd/lava/fs_write_payload_test.odin b/cmd/lava/fs_write_payload_test.odin index bafbe368..eae0ea4b 100644 --- a/cmd/lava/fs_write_payload_test.odin +++ b/cmd/lava/fs_write_payload_test.odin @@ -85,9 +85,7 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. // The buffer is 8 bytes live by the time the pointer is taken. Anything longer is // memory past the allocation — which is what shipped, at 4096. - live := int( - jsc.JSValueToNumber(ctx, payload_eval(ctx, "globalThis.__ab.byteLength"), nil), - ) + live := int(jsc.JSValueToNumber(ctx, payload_eval(ctx, "globalThis.__ab.byteLength"), nil)) testing.expectf(t, live == 8, "the getter should have resized the backing to 8, got %d", live) testing.expectf( t, diff --git a/cmd/lava/global_surface_test.odin b/cmd/lava/global_surface_test.odin index 2cad5a5c..f3104d72 100644 --- a/cmd/lava/global_surface_test.odin +++ b/cmd/lava/global_surface_test.odin @@ -269,14 +269,7 @@ if (present.length !== 0) throw new Error('web surface still has: ' + present.jo @(test) global_surface_alternates_on_one_thread :: proc(t: ^testing.T) { expect_ok :: proc(t: ^testing.T, what: string, result: lava.Result) { - testing.expectf( - t, - result.status == .Ok, - "%s: status=%v message=%q", - what, - result.status, - result.message, - ) + testing.expectf(t, result.status == .Ok, "%s: status=%v message=%q", what, result.status, result.message) } first := lava.eval(NODE_NAMES_PRESENT, "", nil) @@ -306,7 +299,12 @@ global_surface_web_skips_stdio :: proc(t: ^testing.T) { node_init, node_events := surface_events_compiles(t, .Node) web_init, web_events := surface_events_compiles(t, .Web) - testing.expectf(t, node_events == 0, "node: resolving events compiled %d factories (want 0: stdio loaded it)", node_events) + testing.expectf( + t, + node_events == 0, + "node: resolving events compiled %d factories (want 0: stdio loaded it)", + node_events, + ) testing.expectf(t, web_events > 0, "web: resolving events compiled nothing — stdio was instantiated at init") testing.expectf( t, diff --git a/cmd/lava/host_native_registry_test.odin b/cmd/lava/host_native_registry_test.odin index 7767e4ca..41b9fdf6 100644 --- a/cmd/lava/host_native_registry_test.odin +++ b/cmd/lava/host_native_registry_test.odin @@ -94,11 +94,7 @@ destroy_context :: proc(c: Context) { // regression test is the failure mode this whole area keeps hitting. host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { if jsc.host_calls_active(ctx) do return true - testing.expect( - t, - false, - "private-ABI host-call path inactive — this test cannot observe what it pins", - ) + testing.expect(t, false, "private-ABI host-call path inactive — this test cannot observe what it pins") return false } @@ -142,12 +138,7 @@ host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { lava.destroy_runtime_state(a.ctx, state_a) after, ok_after := eval_text(b.ctx, "String(probe())") - testing.expectf( - t, - ok_after && after == "42", - "tearing down context A broke context B's registry: %q", - after, - ) + testing.expectf(t, ok_after && after == "42", "tearing down context A broke context B's registry: %q", after) } // The cache exists so per-instance injections (the fs.Stats methods) reuse one @@ -181,11 +172,7 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { testing.expect(t, renamed != nil && renamed != first, "a different name reused the same cell") different := lava.host_native_create(c.ctx, "probe", other_cb) - testing.expect( - t, - different != nil && different != first, - "a different callback reused the same cell", - ) + testing.expect(t, different != nil && different != first, "a different callback reused the same cell") } // Pins the host path's construct-result divergence require.odin documents: @@ -209,10 +196,7 @@ host_native_construct_returns_call_result :: proc(t: ^testing.T) { defer lava.destroy_runtime_state(c.ctx, state) lava.inject_native_function(c.ctx, jsc.JSContextGetGlobalObject(c.ctx), "probe", answer_cb) - text, ok_eval := eval_text( - c.ctx, - "(function(){ var r = new probe(); return typeof r + ':' + String(r); })()", - ) + text, ok_eval := eval_text(c.ctx, "(function(){ var r = new probe(); return typeof r + ':' + String(r); })()") testing.expectf(t, ok_eval && text == "number:42", "host-path construct result changed: %q", text) } @@ -317,12 +301,7 @@ host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { // The binding still has to work — an OOM in our cache is not an OOM in JSC. lava.inject_native_function(c.ctx, jsc.JSContextGetGlobalObject(c.ctx), "probe", answer_cb) text, ok_eval := eval_text(c.ctx, "String(probe())") - testing.expectf( - t, - ok_eval && text == "42", - "binding broke when the registry could not cache it: %q", - text, - ) + testing.expectf(t, ok_eval && text == "42", "binding broke when the registry could not cache it: %q", text) } // host_throw's contract is that its RETURN says whether the exception was really diff --git a/cmd/lava/lazy_builtins_test.odin b/cmd/lava/lazy_builtins_test.odin index f038cdef..9b3849f1 100644 --- a/cmd/lava/lazy_builtins_test.odin +++ b/cmd/lava/lazy_builtins_test.odin @@ -104,7 +104,54 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { // The static eager set, sorted. Must equal eagerModules() — asserted by // scripts/check-js-graph.test.mjs, which parses this literal. @(private = "file") -STATIC_EAGER :: [?]string{"internal/abort", "internal/blob", "internal/buffer", "internal/crypto/hash", "internal/crypto/hkdf", "internal/crypto/pbkdf2", "internal/crypto/random", "internal/crypto/scrypt", "internal/crypto/util", "internal/encoding", "internal/errors", "internal/fetch", "internal/fetch/body", "internal/fetch/headers", "internal/fetch/request", "internal/fetch/response", "internal/file", "internal/idna", "internal/primordials", "internal/punycode", "internal/stdio", "internal/streams/add-abort-signal", "internal/streams/destroy", "internal/streams/duplex", "internal/streams/end-of-stream", "internal/streams/legacy", "internal/streams/passthrough", "internal/streams/pipeline", "internal/streams/readable", "internal/streams/transform", "internal/streams/utils", "internal/streams/writable", "internal/structured_clone", "internal/url", "internal/webstreams/queuingstrategies", "internal/webstreams/readablestream", "internal/webstreams/transformstream", "internal/webstreams/util", "internal/webstreams/writablestream", "node/buffer", "node/crypto", "node/events", "node/stream", "node/stream/web", "node/string_decoder", "node/url"} +STATIC_EAGER :: [?]string { + "internal/abort", + "internal/blob", + "internal/buffer", + "internal/crypto/hash", + "internal/crypto/hkdf", + "internal/crypto/pbkdf2", + "internal/crypto/random", + "internal/crypto/scrypt", + "internal/crypto/util", + "internal/encoding", + "internal/errors", + "internal/fetch", + "internal/fetch/body", + "internal/fetch/headers", + "internal/fetch/request", + "internal/fetch/response", + "internal/file", + "internal/idna", + "internal/primordials", + "internal/punycode", + "internal/stdio", + "internal/streams/add-abort-signal", + "internal/streams/destroy", + "internal/streams/duplex", + "internal/streams/end-of-stream", + "internal/streams/legacy", + "internal/streams/passthrough", + "internal/streams/pipeline", + "internal/streams/readable", + "internal/streams/transform", + "internal/streams/utils", + "internal/streams/writable", + "internal/structured_clone", + "internal/url", + "internal/webstreams/queuingstrategies", + "internal/webstreams/readablestream", + "internal/webstreams/transformstream", + "internal/webstreams/util", + "internal/webstreams/writablestream", + "node/buffer", + "node/crypto", + "node/events", + "node/stream", + "node/stream/web", + "node/string_decoder", + "node/url", +} @(private = "file") run_bool :: proc(ctx: jsc.JSContextRef, src: string) -> bool { diff --git a/cmd/lava/module_cache_alloc_test.odin b/cmd/lava/module_cache_alloc_test.odin index c36c7ec2..666070c9 100644 --- a/cmd/lava/module_cache_alloc_test.odin +++ b/cmd/lava/module_cache_alloc_test.odin @@ -3,8 +3,8 @@ package main import "core:mem" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Guards the module_cache key-allocator fix. Cache keys are cloned inside the native // require callback (a `proc "c"` where context resets to runtime.default_context — the diff --git a/cmd/lava/net_teardown_stress_test.odin b/cmd/lava/net_teardown_stress_test.odin index 12af187c..3e9b30f5 100644 --- a/cmd/lava/net_teardown_stress_test.odin +++ b/cmd/lava/net_teardown_stress_test.odin @@ -6,8 +6,8 @@ package main import "core:log" import "core:os" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // The same define core:testing's runner reads for its thread count // (runner.odin:34). Re-declared here because `testing.TEST_THREADS` is not @@ -80,9 +80,7 @@ eval_fd_delta :: proc(src: string) -> (delta: int, ok: bool) { @(test) eval_teardown_with_live_net_connections :: proc(t: ^testing.T) { when RUNNER_THREADS != 1 { - log.info( - "skipped: the /proc/self/fd census needs -define:ODIN_TEST_THREADS=1 (make test-odin-serial)", - ) + log.info("skipped: the /proc/self/fd census needs -define:ODIN_TEST_THREADS=1 (make test-odin-serial)") return } diff --git a/cmd/lava/nocopy_bytes_alloc_test.odin b/cmd/lava/nocopy_bytes_alloc_test.odin index 6d5adab8..c0e01ebc 100644 --- a/cmd/lava/nocopy_bytes_alloc_test.odin +++ b/cmd/lava/nocopy_bytes_alloc_test.odin @@ -5,8 +5,8 @@ package main import "core:mem" import "core:strings" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // A loopback round trip: the server echoes what the client writes, so both ends // receive bytes through net's read path, each chunk copied into a NoCopy diff --git a/cmd/lava/pool_cancel_hooks_test.odin b/cmd/lava/pool_cancel_hooks_test.odin index 295cd2b4..d906636b 100644 --- a/cmd/lava/pool_cancel_hooks_test.odin +++ b/cmd/lava/pool_cancel_hooks_test.odin @@ -12,8 +12,8 @@ import "core:sys/posix" import "core:testing" import "core:thread" import "core:time" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Pins the Pool_Cancel hooks fs.readFile, fs.writeFile and dns.lookup register with the // loop's pool (#34, ported from larva#49). eventloop.close_begin must release the JS diff --git a/cmd/lava/primordials_test.odin b/cmd/lava/primordials_test.odin index c46cfda0..5e7ef9e2 100644 --- a/cmd/lava/primordials_test.odin +++ b/cmd/lava/primordials_test.odin @@ -271,4 +271,3 @@ primordials_hidden_from_user_require :: proc(t: ^testing.T) { ) testing.expectf(t, result.exit_code == 0, "eval exit code=%d (want 0)", result.exit_code) } - diff --git a/cmd/lava/regexp_pollution_test.odin b/cmd/lava/regexp_pollution_test.odin index b32fb496..7110d2ce 100644 --- a/cmd/lava/regexp_pollution_test.odin +++ b/cmd/lava/regexp_pollution_test.odin @@ -20,8 +20,8 @@ package main // actually check: the script simply has to finish. import "core:testing" -import "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import "lava:pkg/runtime/eventloop" REGEXP_POLLUTION_SCRIPT :: ` const real = RegExp.prototype.exec; diff --git a/cmd/lava/timer_binding_alloc_test.odin b/cmd/lava/timer_binding_alloc_test.odin index f9f71168..9d8bee2e 100644 --- a/cmd/lava/timer_binding_alloc_test.odin +++ b/cmd/lava/timer_binding_alloc_test.odin @@ -90,7 +90,12 @@ timer_binding_frees_through_its_own_allocator :: proc(t: ^testing.T) { bindings := counter.hits - before - baseline run(t, TIMER_PENDING_SRC, .Execution_Error) - testing.expectf(t, len(track.bad_free_array) == 0, "%d timer binding(s) freed into the wrong allocator", len(track.bad_free_array)) + testing.expectf( + t, + len(track.bad_free_array) == 0, + "%d timer binding(s) freed into the wrong allocator", + len(track.bad_free_array), + ) testing.expectf( t, bindings == TIMER_BINDINGS, diff --git a/odinfmt.json b/odinfmt.json new file mode 100644 index 00000000..50a45192 --- /dev/null +++ b/odinfmt.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/odinfmt.schema.json", + "character_width": 120, + "tabs": true, + "tabs_width": 4, + "sort_imports": true, + "newline_limit": 2 +} diff --git a/pkg/jsc/bindings.odin b/pkg/jsc/bindings.odin index ff6862b9..d97aeee4 100644 --- a/pkg/jsc/bindings.odin +++ b/pkg/jsc/bindings.odin @@ -75,11 +75,7 @@ JSClassDefinition :: struct { static_functions: ^JSStaticFunction, initialize: proc "c" (ctx: JSContextRef, object: JSObjectRef), finalize: proc "c" (object: JSObjectRef), - has_property: proc "c" ( - ctx: JSContextRef, - object: JSObjectRef, - property_name: JSStringRef, - ) -> b32, + has_property: proc "c" (ctx: JSContextRef, object: JSObjectRef, property_name: JSStringRef) -> b32, get_property: proc "c" ( ctx: JSContextRef, object: JSObjectRef, diff --git a/pkg/jsc/host_function.odin b/pkg/jsc/host_function.odin index 6cad1617..52efdd1a 100644 --- a/pkg/jsc/host_function.odin +++ b/pkg/jsc/host_function.odin @@ -93,14 +93,22 @@ when ODIN_OS == .Linux { // calling thread's (thread-confined) context, and g_probe_seen/g_probe_callee // are written by that probe callback on the same thread. Per-thread state // keeps concurrent worker startups from clobbering each other's probe. - @(private = "file", thread_local) g_host_checked: bool - @(private = "file", thread_local) g_host_ok: bool - @(private = "file", thread_local) g_host_create: Create_Host_Fn_Proc - @(private = "file", thread_local) g_host_lock_ctor: Lock_Ctor_Proc - @(private = "file", thread_local) g_host_lock_dtor: Lock_Dtor_Proc - @(private = "file", thread_local) g_vm_throw: Vm_Throw_Proc - @(private = "file", thread_local) g_probe_seen: bool - @(private = "file", thread_local) g_probe_callee: rawptr + @(private = "file", thread_local) + g_host_checked: bool + @(private = "file", thread_local) + g_host_ok: bool + @(private = "file", thread_local) + g_host_create: Create_Host_Fn_Proc + @(private = "file", thread_local) + g_host_lock_ctor: Lock_Ctor_Proc + @(private = "file", thread_local) + g_host_lock_dtor: Lock_Dtor_Proc + @(private = "file", thread_local) + g_vm_throw: Vm_Throw_Proc + @(private = "file", thread_local) + g_probe_seen: bool + @(private = "file", thread_local) + g_probe_callee: rawptr // debug_log reports probe outcomes on stderr when LAVA_HOSTFN_DEBUG is set — // the fallback is silent by design, so this is the diagnostic switch. @@ -120,8 +128,7 @@ when ODIN_OS == .Linux { if argc == 3 && rawptr(uintptr(cf[CALL_FRAME_CALLEE_SLOT])) == g_probe_callee { a0 := JSValueRef(uintptr(cf[CALL_FRAME_FIRST_ARG_SLOT])) a1 := JSValueRef(uintptr(cf[CALL_FRAME_FIRST_ARG_SLOT + 1])) - if JSValueIsNumber(ctx, a0) && JSValueIsString(ctx, a1) && - JSValueToNumber(ctx, a0, nil) == 42 { + if JSValueIsNumber(ctx, a0) && JSValueIsString(ctx, a1) && JSValueToNumber(ctx, a0, nil) == 42 { s := JSValueToStringCopy(ctx, a1, nil) if s != nil { equal := JSStringIsEqualToUTF8CString(s, "ab") @@ -143,7 +150,17 @@ when ODIN_OS == .Linux { g_host_lock_ctor(&holder, rawptr(ctx)) // The same fn doubles as the constructor slot: our natives are never // `new`ed, and a non-null pointer can never null-deref if one is. - fptr := g_host_create(vm, rawptr(ctx), c.uint(arity), &impl, transmute(rawptr)fn, 0, 0, transmute(rawptr)fn, nil) + fptr := g_host_create( + vm, + rawptr(ctx), + c.uint(arity), + &impl, + transmute(rawptr)fn, + 0, + 0, + transmute(rawptr)fn, + nil, + ) g_host_lock_dtor(&holder) return JSObjectRef(fptr) } @@ -180,7 +197,10 @@ when ODIN_OS == .Linux { // Resolved once even across a transient retry: dlsym is the expensive half // and its answer is definitive either way. if g_host_create == nil { - pc := host_dlsym(nil, "_ZN3JSC10JSFunction6createERNS_2VMEPNS_14JSGlobalObjectEjRKN3WTF6StringENS5_11FunctionPtrILNS5_6PtrTagE1EFlS4_PNS_9CallFrameEELNS5_18FunctionAttributesE2EEENS_24ImplementationVisibilityENS_9IntrinsicESF_PKNS_6DOMJIT9SignatureE") + pc := host_dlsym( + nil, + "_ZN3JSC10JSFunction6createERNS_2VMEPNS_14JSGlobalObjectEjRKN3WTF6StringENS5_11FunctionPtrILNS5_6PtrTagE1EFlS4_PNS_9CallFrameEELNS5_18FunctionAttributesE2EEENS_24ImplementationVisibilityENS_9IntrinsicESF_PKNS_6DOMJIT9SignatureE", + ) pl := host_dlsym(nil, "_ZN3JSC12JSLockHolderC1EPNS_14JSGlobalObjectE") pd := host_dlsym(nil, "_ZN3JSC12JSLockHolderD1Ev") pt := host_dlsym(nil, "_ZN3JSC2VM14throwExceptionEPNS_14JSGlobalObjectENS_7JSValueE") @@ -229,10 +249,7 @@ when ODIN_OS == .Linux { // result is permanent whichever way it goes. g_host_checked = true - args := [2]JSValueRef{ - JSValueMakeNumber(ctx, 42), - js_probe_string(ctx), - } + args := [2]JSValueRef{JSValueMakeNumber(ctx, 42), js_probe_string(ctx)} g_probe_callee = rawptr(fn) g_probe_seen = false res := JSObjectCallAsFunction(ctx, fn, nil, 2, &args[0], nil) @@ -259,7 +276,15 @@ when ODIN_OS == .Linux { // The returned object is an ordinary JS function value (attach it with // JSObjectSetProperty). ok=false whenever the private path is unavailable — // callers must fall back to JSObjectMakeFunctionWithCallback. - host_function_create :: proc(ctx: JSContextRef, name: string, fn: Host_Function_Proc, arity: int) -> (function: JSObjectRef, ok: bool) { + host_function_create :: proc( + ctx: JSContextRef, + name: string, + fn: Host_Function_Proc, + arity: int, + ) -> ( + function: JSObjectRef, + ok: bool, + ) { ensure_host(ctx) if !g_host_ok do return nil, false function = create_raw(ctx, name, fn, arity) @@ -300,7 +325,15 @@ when ODIN_OS == .Linux { return true } } else { - host_function_create :: proc(_: JSContextRef, _: string, _: Host_Function_Proc, _: int) -> (function: JSObjectRef, ok: bool) { + host_function_create :: proc( + _: JSContextRef, + _: string, + _: Host_Function_Proc, + _: int, + ) -> ( + function: JSObjectRef, + ok: bool, + ) { return nil, false } diff --git a/pkg/jsc/jsc_init.odin b/pkg/jsc/jsc_init.odin index 8459c57b..f68eb067 100644 --- a/pkg/jsc/jsc_init.odin +++ b/pkg/jsc/jsc_init.odin @@ -26,13 +26,23 @@ when ODIN_OS == .Windows { lava_make_uint8_nocopy :: proc(ctx: JSContextRef, bytes: rawptr, length: c.size_t, dealloc: proc "c" (bytes: rawptr, deallocator_context: rawptr)) -> JSObjectRef --- } - make_uint8_nocopy_locked :: proc(ctx: JSContextRef, bytes: rawptr, length: c.size_t, dealloc: proc "c" (bytes: rawptr, deallocator_context: rawptr)) -> JSObjectRef { + make_uint8_nocopy_locked :: proc( + ctx: JSContextRef, + bytes: rawptr, + length: c.size_t, + dealloc: proc "c" (bytes: rawptr, deallocator_context: rawptr), + ) -> JSObjectRef { return lava_make_uint8_nocopy(ctx, bytes, length, dealloc) } } else { lava_jsc_init :: proc() {} - make_uint8_nocopy_locked :: proc(ctx: JSContextRef, bytes: rawptr, length: c.size_t, dealloc: proc "c" (bytes: rawptr, deallocator_context: rawptr)) -> JSObjectRef { + make_uint8_nocopy_locked :: proc( + ctx: JSContextRef, + bytes: rawptr, + length: c.size_t, + dealloc: proc "c" (bytes: rawptr, deallocator_context: rawptr), + ) -> JSObjectRef { return JSObjectMakeTypedArrayWithBytesNoCopy(ctx, .Uint8Array, bytes, length, dealloc, nil, nil) } } diff --git a/pkg/jsc/jsc_init_windows.cpp b/pkg/jsc/jsc_init_windows.cpp index 7846dca5..b8c4eb0d 100644 --- a/pkg/jsc/jsc_init_windows.cpp +++ b/pkg/jsc/jsc_init_windows.cpp @@ -36,11 +36,11 @@ #include namespace WTF { -void initializeMainThread(); + void initializeMainThread(); } namespace JSC { -void initialize(); + void initialize(); } extern "C" void lava_jsc_init(void) { @@ -90,27 +90,26 @@ typedef const struct OpaqueJSContext *JSContextRef; typedef const struct OpaqueJSValue *JSValueRef; typedef struct OpaqueJSValue *JSObjectRef; typedef void (*JSTypedArrayBytesDeallocator)(void *bytes, void *deallocatorContext); -JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy( - JSContextRef ctx, int arrayType, void *bytes, size_t byteLength, - JSTypedArrayBytesDeallocator bytesDeallocator, void *deallocatorContext, - JSValueRef *exception); +JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy(JSContextRef ctx, int arrayType, void *bytes, size_t byteLength, + JSTypedArrayBytesDeallocator bytesDeallocator, + void *deallocatorContext, JSValueRef *exception); } namespace JSC { -class JSGlobalObject; -class JSLockHolder { -public: - JSLockHolder(JSGlobalObject *); - ~JSLockHolder(); -private: - void *m_vm; // RefPtr — single pointer -}; + class JSGlobalObject; + class JSLockHolder { + public: + JSLockHolder(JSGlobalObject *); + ~JSLockHolder(); + + private: + void *m_vm; // RefPtr — single pointer + }; } // namespace JSC -extern "C" JSObjectRef lava_make_uint8_nocopy( - JSContextRef ctx, void *bytes, size_t length, JSTypedArrayBytesDeallocator dealloc) { - JSC::JSLockHolder lock( - reinterpret_cast(const_cast(ctx))); - return JSObjectMakeTypedArrayWithBytesNoCopy( - ctx, 3 /* kJSTypedArrayTypeUint8Array */, bytes, length, dealloc, nullptr, nullptr); +extern "C" JSObjectRef lava_make_uint8_nocopy(JSContextRef ctx, void *bytes, size_t length, + JSTypedArrayBytesDeallocator dealloc) { + JSC::JSLockHolder lock(reinterpret_cast(const_cast(ctx))); + return JSObjectMakeTypedArrayWithBytesNoCopy(ctx, 3 /* kJSTypedArrayTypeUint8Array */, bytes, length, dealloc, + nullptr, nullptr); } diff --git a/pkg/jsc/private_string.odin b/pkg/jsc/private_string.odin index 5d307dbe..1ae91bfe 100644 --- a/pkg/jsc/private_string.odin +++ b/pkg/jsc/private_string.odin @@ -66,11 +66,16 @@ when ODIN_OS == .Linux { // re-derives the (build-global) symbol pointers and layout facts once per // worker thread — cheap, and race-free when workers start concurrently, // versus a shared latch that could be observed half-published. - @(private = "file", thread_local) g_checked: bool - @(private = "file", thread_local) g_ok: bool - @(private = "file", thread_local) g_create8: Create_Uninit8_Proc - @(private = "file", thread_local) g_create16: Create_Uninit16_Proc - @(private = "file", thread_local) g_try_create: Try_Create_Proc + @(private = "file", thread_local) + g_checked: bool + @(private = "file", thread_local) + g_ok: bool + @(private = "file", thread_local) + g_create8: Create_Uninit8_Proc + @(private = "file", thread_local) + g_create16: Create_Uninit16_Proc + @(private = "file", thread_local) + g_try_create: Try_Create_Proc // Read-side layout facts, established by probe_read_layout. StringImplShape // has been {u32 refCount; u32 length; T* data; atomic hashAndFlags} and @@ -80,14 +85,21 @@ when ODIN_OS == .Linux { // and widths are known exactly (we created them), plus positive/negative // functional checks through the public C API. Any mismatch leaves the read // path disabled while the write path keeps working. - @(private = "file", thread_local) g_read_ok: bool - @(private = "file", thread_local) g_flag_mask: u32 - @(private = "file", thread_local) g_flag_val8: u32 + @(private = "file", thread_local) + g_read_ok: bool + @(private = "file", thread_local) + g_flag_mask: u32 + @(private = "file", thread_local) + g_flag_val8: u32 - @(private = "file") IMPL_LENGTH_OFFSET :: 4 - @(private = "file") IMPL_DATA_OFFSET :: 8 - @(private = "file") IMPL_FLAGS_OFFSET :: 16 - @(private = "file") OPAQUE_STRING_IMPL_OFFSET :: 8 + @(private = "file") + IMPL_LENGTH_OFFSET :: 4 + @(private = "file") + IMPL_DATA_OFFSET :: 8 + @(private = "file") + IMPL_FLAGS_OFFSET :: 16 + @(private = "file") + OPAQUE_STRING_IMPL_OFFSET :: 8 @(private = "file") ensure_resolved :: proc() { @@ -237,10 +249,14 @@ when ODIN_OS == .Linux { // pointer inside cells built from strings we constructed, and verified on a // second cell of the other storage width. - @(private = "file", thread_local) g_val_checked: bool - @(private = "file", thread_local) g_val_ok: bool - @(private = "file", thread_local) g_string_type: u8 - @(private = "file", thread_local) g_fiber_off: uintptr + @(private = "file", thread_local) + g_val_checked: bool + @(private = "file", thread_local) + g_val_ok: bool + @(private = "file", thread_local) + g_string_type: u8 + @(private = "file", thread_local) + g_fiber_off: uintptr @(private = "file") ensure_value_reads :: proc(ctx: JSContextRef) { diff --git a/pkg/jsc/private_value.odin b/pkg/jsc/private_value.odin index 08bd3494..c37cc5e0 100644 --- a/pkg/jsc/private_value.odin +++ b/pkg/jsc/private_value.odin @@ -14,9 +14,12 @@ when ODIN_OS == .Linux { // (thread-confined) context exactly once. The NaN-box tag is a // build-global fact, but re-deriving it per thread is cheap and avoids any // cross-thread read of a half-published latch when workers start together. - @(private = "file", thread_local) g_i32_checked: bool - @(private = "file", thread_local) g_i32_ok: bool - @(private = "file", thread_local) g_i32_tag: u64 + @(private = "file", thread_local) + g_i32_checked: bool + @(private = "file", thread_local) + g_i32_ok: bool + @(private = "file", thread_local) + g_i32_tag: u64 @(private = "file") ensure_int32 :: proc(ctx: JSContextRef) { diff --git a/pkg/jsc/private_view.odin b/pkg/jsc/private_view.odin index 31a9ad52..80b7d4b5 100644 --- a/pkg/jsc/private_view.odin +++ b/pkg/jsc/private_view.odin @@ -50,27 +50,39 @@ when ODIN_OS == .Linux { // later be read, and the cell offsets — though a build-global fact — are // re-derived once per worker thread to avoid a shared latch being seen // half-published during concurrent worker startup. - @(private = "file", thread_local) g_view_checked: bool - @(private = "file", thread_local) g_view_ok: bool - @(private = "file", thread_local) g_view_type: u8 - @(private = "file", thread_local) g_vec_off: uintptr - @(private = "file", thread_local) g_len_off: uintptr - @(private = "file", thread_local) g_len_u64: bool + @(private = "file", thread_local) + g_view_checked: bool + @(private = "file", thread_local) + g_view_ok: bool + @(private = "file", thread_local) + g_view_type: u8 + @(private = "file", thread_local) + g_vec_off: uintptr + @(private = "file", thread_local) + g_len_off: uintptr + @(private = "file", thread_local) + g_len_u64: bool // m_mode byte offset and the three values it takes on a fixed-length view // over a non-resizable buffer (JSC: Fast, Oversize, Wasteful). Values are // recorded from probe views rather than hardcoded, like the offsets above. - @(private = "file", thread_local) g_mode_off: uintptr - @(private = "file", thread_local) g_mode_fixed: [3]u8 + @(private = "file", thread_local) + g_mode_off: uintptr + @(private = "file", thread_local) + g_mode_fixed: [3]u8 // Immortal backing stores for the probe views (nil deallocator): distinct // addresses and lengths so field offsets are identified by value. The `_off` // view (backed by g_probe_d, viewed at a non-zero byteOffset) disambiguates a // genuine 64-bit length from a 32-bit length whose adjacent (zero) field the // wide read would otherwise fold in — see ensure_view. - @(private = "file", thread_local) g_probe_a: [40]byte - @(private = "file", thread_local) g_probe_b: [24]byte - @(private = "file", thread_local) g_probe_c: [56]byte - @(private = "file", thread_local) g_probe_d: [64]byte + @(private = "file", thread_local) + g_probe_a: [40]byte + @(private = "file", thread_local) + g_probe_b: [24]byte + @(private = "file", thread_local) + g_probe_c: [56]byte + @(private = "file", thread_local) + g_probe_d: [64]byte @(private = "file") ensure_view :: proc(ctx: JSContextRef) { @@ -169,11 +181,7 @@ when ODIN_OS == .Linux { g_view_checked = true return } - args := [3]JSValueRef { - JSValueRef(ab), - JSValueMakeNumber(ctx, f64(OFF)), - JSValueMakeNumber(ctx, f64(LEN)), - } + args := [3]JSValueRef{JSValueRef(ab), JSValueMakeNumber(ctx, f64(OFF)), JSValueMakeNumber(ctx, f64(LEN))} ov := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 3, &args[0], nil) if ov == nil do return // soft JSValueProtect(ctx, JSValueRef(ov)) @@ -223,7 +231,7 @@ when ODIN_OS == .Linux { @(private = "file") Mode_Probe :: enum u8 { Found, - Soft, // an allocation or constructor call failed; retry on a later call + Soft, // an allocation or constructor call failed; retry on a later call Mismatch, // layout did not discriminate; latch the fast path closed } diff --git a/pkg/runtime/buffer.odin b/pkg/runtime/buffer.odin index d98467e7..c9c1bba8 100644 --- a/pkg/runtime/buffer.odin +++ b/pkg/runtime/buffer.odin @@ -801,10 +801,22 @@ make_buffer_bindings :: proc(ctx: jsc.JSContextRef) -> jsc.JSObjectRef { inject_native_function(ctx, bindings, "latin1Encode", buffer_latin1_encode_cb, buffer_latin1_encode_host) inject_native_function(ctx, bindings, "latin1Decode", buffer_latin1_decode_cb, buffer_latin1_decode_host) inject_native_function(ctx, bindings, "asciiDecode", buffer_ascii_decode_cb, buffer_ascii_decode_host) - inject_native_function(ctx, bindings, "latin1WriteInto", buffer_latin1_write_into_cb, buffer_latin1_write_into_host) + inject_native_function( + ctx, + bindings, + "latin1WriteInto", + buffer_latin1_write_into_cb, + buffer_latin1_write_into_host, + ) inject_native_function(ctx, bindings, "utf16leEncode", buffer_utf16le_encode_cb, buffer_utf16le_encode_host) inject_native_function(ctx, bindings, "utf16leDecode", buffer_utf16le_decode_cb, buffer_utf16le_decode_host) - inject_native_function(ctx, bindings, "utf16leWriteInto", buffer_utf16le_write_into_cb, buffer_utf16le_write_into_host) + inject_native_function( + ctx, + bindings, + "utf16leWriteInto", + buffer_utf16le_write_into_cb, + buffer_utf16le_write_into_host, + ) inject_native_function(ctx, bindings, "utf8WriteInto", buffer_utf8_write_into_cb, buffer_utf8_write_into_host) // Cold natives: generic host trampoline (no dedicated *_host wrapper). inject_native_function(ctx, bindings, "utf8ByteLength", buffer_utf8_byte_length_cb) diff --git a/pkg/runtime/buffer_simd.odin b/pkg/runtime/buffer_simd.odin index 68e60797..d2148b6f 100644 --- a/pkg/runtime/buffer_simd.odin +++ b/pkg/runtime/buffer_simd.odin @@ -11,11 +11,16 @@ import "core:simd" // Codec lookup tables. Encoders index the alphabet strings directly; the decode // tables map a byte to its value, 0xFF = not in the alphabet. -@(private) HEX_DIGITS := "0123456789abcdef" -@(private) B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -@(private) B64URL_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" -@(private) g_hex_val: [256]u8 -@(private) g_b64_val: [256]u8 +@(private) +HEX_DIGITS := "0123456789abcdef" +@(private) +B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +@(private) +B64URL_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" +@(private) +g_hex_val: [256]u8 +@(private) +g_b64_val: [256]u8 @(init, private) buffer_codec_tables_init :: proc "contextless" () { @@ -195,8 +200,12 @@ base64_parse :: proc(out: []byte, chars: []$T) -> (n: int, ok: bool) { pad3 := s[3] == '=' d2 := pad2 ? 0 : g_b64_val[s[2]] d3 := pad3 ? 0 : g_b64_val[s[3]] - if d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || d3 == 0xFF || - (pad2 && !pad3) || ((pad2 || pad3) && g != groups - 1) { + if d0 == 0xFF || + d1 == 0xFF || + d2 == 0xFF || + d3 == 0xFF || + (pad2 && !pad3) || + ((pad2 || pad3) && g != groups - 1) { return 0, false } v := u32(d0) << 18 | u32(d1) << 12 | u32(d2) << 6 | u32(d3) diff --git a/pkg/runtime/dns.odin b/pkg/runtime/dns.odin index 0660a2f2..2b15b43a 100644 --- a/pkg/runtime/dns.odin +++ b/pkg/runtime/dns.odin @@ -53,13 +53,13 @@ Dns_Lookup_Request :: struct { // worker's, the heap — so plain delete() frees it correctly.) allocator: runtime.Allocator, hostname: string, // owned clone (the worker reads it off-loop) - family: int, // 0 (any) | 4 | 6 - order: int, // ORDER_* (which family to prefer / how to concatenate) - all: bool, - results: [dynamic]Dns_Lookup_Result, // heap (default allocator); full address list - last_err: net.DNS_Error, // worst resolver error seen, to distinguish NXDOMAIN from transient - ok: bool, - err_code: string, // static literal, e.g. "ENOTFOUND" / "EAI_AGAIN" + family: int, // 0 (any) | 4 | 6 + order: int, // ORDER_* (which family to prefer / how to concatenate) + all: bool, + results: [dynamic]Dns_Lookup_Result, // heap (default allocator); full address list + last_err: net.DNS_Error, // worst resolver error seen, to distinguish NXDOMAIN from transient + ok: bool, + err_code: string, // static literal, e.g. "ENOTFOUND" / "EAI_AGAIN" } // make_dns_bindings builds the `native` object handed to js/node/dns.js. @@ -145,9 +145,21 @@ dns_query_family :: proc(req: ^Dns_Lookup_Request, type: net.DNS_Record_Type, fa err: net.DNS_Error is_mdns := ODIN_OS != .Windows && strings.has_suffix(req.hostname, ".local") if is_mdns && type == .IP4 { - recs, err = net.get_dns_records_from_nameservers(req.hostname, .IP4, {net.IP4_mDNS_Broadcast}, nil, context.temp_allocator) + recs, err = net.get_dns_records_from_nameservers( + req.hostname, + .IP4, + {net.IP4_mDNS_Broadcast}, + nil, + context.temp_allocator, + ) } else if is_mdns { - recs, err = net.get_dns_records_from_nameservers(req.hostname, .IP6, {net.IP6_mDNS_Broadcast}, nil, context.temp_allocator) + recs, err = net.get_dns_records_from_nameservers( + req.hostname, + .IP6, + {net.IP6_mDNS_Broadcast}, + nil, + context.temp_allocator, + ) } else { recs, err = net.get_dns_records_from_os(req.hostname, type, context.temp_allocator) } @@ -226,11 +238,7 @@ dns_work :: proc(user_data: rawptr) { // Node's EAI_AGAIN for that case needs a resolver that surfaces the timeout. dns_error_to_code :: proc(e: net.DNS_Error) -> string { #partial switch e { - case .Connection_Error, - .Server_Error, - .System_Error, - .Invalid_Resolv_Config_Error, - .Invalid_Hosts_Config_Error: + case .Connection_Error, .Server_Error, .System_Error, .Invalid_Resolv_Config_Error, .Invalid_Hosts_Config_Error: return "EAI_AGAIN" } return "ENOTFOUND" diff --git a/pkg/runtime/environment.odin b/pkg/runtime/environment.odin index 1d0f1cbc..491271e6 100644 --- a/pkg/runtime/environment.odin +++ b/pkg/runtime/environment.odin @@ -72,14 +72,7 @@ setup_module_environment :: proc( child_len_name := jsc.JSStringCreateWithUTF8CString("length") defer jsc.JSStringRelease(child_len_name) - jsc.JSObjectSetProperty( - ctx, - children_arr, - child_len_name, - jsc.JSValueMakeNumber(ctx, 1), - {}, - nil, - ) + jsc.JSObjectSetProperty(ctx, children_arr, child_len_name, jsc.JSValueMakeNumber(ctx, 1), {}, nil) module_name := jsc.JSStringCreateWithUTF8CString("module") children_name := jsc.JSStringCreateWithUTF8CString("children") @@ -89,14 +82,7 @@ setup_module_environment :: proc( defer jsc.JSStringRelease(exports_name) // Виправлено: додано касти до JSValueRef для властивостей об'єкта - jsc.JSObjectSetProperty( - ctx, - module_obj, - children_name, - cast(jsc.JSValueRef)children_arr, - {}, - nil, - ) + jsc.JSObjectSetProperty(ctx, module_obj, children_name, cast(jsc.JSValueRef)children_arr, {}, nil) // Initialize module.exports = {} (and the `exports` alias) so the entry can do // `module.exports.foo = …` / `exports.foo = …` without first reassigning @@ -105,24 +91,10 @@ setup_module_environment :: proc( // the entry and the partial-exports cache (register_entry_module) has nothing // to register. exports_obj := jsc.JSObjectMake(ctx, nil, nil) - jsc.JSObjectSetProperty( - ctx, - module_obj, - exports_name, - cast(jsc.JSValueRef)exports_obj, - {}, - nil, - ) + jsc.JSObjectSetProperty(ctx, module_obj, exports_name, cast(jsc.JSValueRef)exports_obj, {}, nil) jsc.JSObjectSetProperty(ctx, global_obj, module_name, cast(jsc.JSValueRef)module_obj, {}, nil) - jsc.JSObjectSetProperty( - ctx, - global_obj, - exports_name, - cast(jsc.JSValueRef)exports_obj, - {}, - nil, - ) + jsc.JSObjectSetProperty(ctx, global_obj, exports_name, cast(jsc.JSValueRef)exports_obj, {}, nil) } // WEB_REMOVED_GLOBALS are the Node globals install_globals puts on every context and @@ -150,12 +122,7 @@ remove_node_globals :: proc(ctx: jsc.JSContextRef, global_obj: jsc.JSObjectRef) } } -inject_global_string :: proc( - ctx: jsc.JSContextRef, - global_obj: jsc.JSObjectRef, - name: string, - value: string, -) { +inject_global_string :: proc(ctx: jsc.JSContextRef, global_obj: jsc.JSObjectRef, name: string, value: string) { c_name, c_name_err := strings.clone_to_cstring(name, context.temp_allocator) if c_name_err != nil do return c_value, c_value_err := strings.clone_to_cstring(value, context.temp_allocator) @@ -471,13 +438,7 @@ utf16_to_utf8_owned :: proc(chars: [^]jsc.JSChar, length: int) -> (string, bool) // jsc_value_to_string_or_default converts a JS value to an owned UTF-8 Odin string // (caller's allocator). Returns ("", false) for empty / non-convertible values — // callers treat false as "empty string, no free". Exact UTF-8 size (no 3n+1). -jsc_value_to_string_or_default :: proc( - ctx: jsc.JSContextRef, - value: jsc.JSValueRef, -) -> ( - string, - bool, -) { +jsc_value_to_string_or_default :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> (string, bool) { // Flat string values resolve with no C-API call; everything else (ropes, // non-strings needing coercion) goes through JSValueToStringCopy. if s8, ok := jsc.value_chars8(ctx, value); ok { diff --git a/pkg/runtime/errors.odin b/pkg/runtime/errors.odin index 6b1e889e..c6c6469a 100644 --- a/pkg/runtime/errors.odin +++ b/pkg/runtime/errors.odin @@ -38,9 +38,7 @@ capture_error_intrinsics :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { global := jsc.JSContextGetGlobalObject(ctx) for name in ERROR_INTRINSIC_NAMES { ctor := get_named(ctx, global, name) - if ctor != nil && - jsc.JSValueIsObject(ctx, ctor) && - jsc.JSObjectIsConstructor(ctx, cast(jsc.JSObjectRef)ctor) { + if ctor != nil && jsc.JSValueIsObject(ctx, ctor) && jsc.JSObjectIsConstructor(ctx, cast(jsc.JSObjectRef)ctor) { jsc.JSValueProtect(ctx, ctor) state.error_intrinsics[name] = ctor } @@ -123,12 +121,7 @@ make_js_named_error :: proc(ctx: jsc.JSContextRef, name, message: string) -> jsc // describes the expectation (e.g. "an integer", ">= 0 and <= 255"); `received` // is the offending value rendered for display (e.g. "NaN", "-1"). err_out_of_range :: proc(ctx: jsc.JSContextRef, name, range, received: string) -> jsc.JSValueRef { - msg := fmt.tprintf( - "The value of \"%s\" is out of range. It must be %s. Received %s", - name, - range, - received, - ) + msg := fmt.tprintf("The value of \"%s\" is out of range. It must be %s. Received %s", name, range, received) return make_native_error(ctx, "RangeError", msg, "ERR_OUT_OF_RANGE") } diff --git a/pkg/runtime/eventloop/eventloop_close_running_test.odin b/pkg/runtime/eventloop/eventloop_close_running_test.odin index 1d31399e..36e44330 100644 --- a/pkg/runtime/eventloop/eventloop_close_running_test.odin +++ b/pkg/runtime/eventloop/eventloop_close_running_test.odin @@ -70,7 +70,13 @@ close_begin_never_disposes_a_job_its_worker_is_running :: proc(t: ^testing.T) { disposed := sync.atomic_load(&job.dispose) if disposed != 0 || !busy { // Leave the worker blocked: see the file comment. - testing.expectf(t, false, "close_begin disposed a job its worker is still running (dispose %d, busy %v)", disposed, busy) + testing.expectf( + t, + false, + "close_begin disposed a job its worker is still running (dispose %d, busy %v)", + disposed, + busy, + ) return } testing.expect_value(t, sync.atomic_load(&job.cancel), 1) diff --git a/pkg/runtime/eventloop/eventloop_close_test.odin b/pkg/runtime/eventloop/eventloop_close_test.odin index 88858cd3..09eb565c 100644 --- a/pkg/runtime/eventloop/eventloop_close_test.odin +++ b/pkg/runtime/eventloop/eventloop_close_test.odin @@ -154,7 +154,14 @@ close_detach_leaves_the_loop_to_its_last_worker :: proc(t: ^testing.T) { testing.expect(t, detached, "close_detach finished a loop whose worker is still blocked") // The loop belongs to its workers now: nothing below reads it. still := fd_link(int(pipe_fd)) - testing.expectf(t, still == pipe_link, "wakeup pipe fd %d changed from %q to %q while its worker was blocked", pipe_fd, pipe_link, still) + testing.expectf( + t, + still == pipe_link, + "wakeup pipe fd %d changed from %q to %q while its worker was blocked", + pipe_fd, + pipe_link, + still, + ) delete(still) sync.atomic_store(&rel.stop, true) diff --git a/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin b/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin index adfd7990..0cf0eb30 100644 --- a/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin +++ b/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin @@ -63,7 +63,12 @@ close_ready_is_announced_on_the_wakeup_pipe :: proc(t: ^testing.T) { // The last worker writes the pipe just after its count moves; allow it a second. fds := [1]linux.Poll_Fd{{fd = pipe_fd, events = {.IN}}} n, _ := linux.poll(fds[:], 1000) - testing.expectf(t, n == 1 && .IN in fds[0].revents, "the wakeup pipe was not written as the workers exited (poll %d)", n) + testing.expectf( + t, + n == 1 && .IN in fds[0].revents, + "the wakeup pipe was not written as the workers exited (poll %d)", + n, + ) close_finish(&loop) } diff --git a/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin b/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin index 140bfbb7..d4f90aeb 100644 --- a/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin +++ b/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin @@ -63,11 +63,7 @@ failed_platform_init_does_not_double_close :: proc(t: ^testing.T) { // Restore before anything else — the runner itself needs descriptors. linux.setrlimit(.NOFILE, &saved) - testing.expect( - t, - loop.backend == .Unavailable, - "platform_init was supposed to fail under the tightened limit", - ) + testing.expect(t, loop.backend == .Unavailable, "platform_init was supposed to fail under the tightened limit") // Takes the number pipe2 just released. If platform_init left that number in // wakeup_pipe, destroy is about to close THIS descriptor. @@ -89,11 +85,6 @@ failed_platform_init_does_not_double_close :: proc(t: ^testing.T) { st: linux.Stat fstat_err := linux.fstat(canary, &st) - testing.expectf( - t, - fstat_err == nil, - "destroy closed an unrelated descriptor: fstat(canary) -> %v", - fstat_err, - ) + testing.expectf(t, fstat_err == nil, "destroy closed an unrelated descriptor: fstat(canary) -> %v", fstat_err) if fstat_err == nil do linux.close(canary) } diff --git a/pkg/runtime/eventloop/eventloop_proactor_test.odin b/pkg/runtime/eventloop/eventloop_proactor_test.odin index ef2f83ee..79b307ba 100644 --- a/pkg/runtime/eventloop/eventloop_proactor_test.odin +++ b/pkg/runtime/eventloop/eventloop_proactor_test.odin @@ -70,8 +70,16 @@ proactor_recv_send_roundtrip :: proc(t: ^testing.T) { rec := Proactor_Rec{} msg := [5]u8{'h', 'e', 'l', 'l', 'o'} - testing.expect(t, submit_recv(&loop, uintptr(sv[0]), rec.recv_buf[:], proactor_on_recv, nil, &rec) != OP_ID_INVALID, "recv submit") - testing.expect(t, submit_send(&loop, uintptr(sv[1]), msg[:], proactor_on_send, nil, &rec) != OP_ID_INVALID, "send submit") + testing.expect( + t, + submit_recv(&loop, uintptr(sv[0]), rec.recv_buf[:], proactor_on_recv, nil, &rec) != OP_ID_INVALID, + "recv submit", + ) + testing.expect( + t, + submit_send(&loop, uintptr(sv[1]), msg[:], proactor_on_send, nil, &rec) != OP_ID_INVALID, + "send submit", + ) arm_watchdog(&loop) for i in 0 ..< 5 { @@ -100,7 +108,10 @@ proactor_recv_short_read :: proc(t: ^testing.T) { rec := Proactor_Rec{} three := [3]u8{'a', 'b', 'c'} - testing.expect(t, submit_recv(&loop, uintptr(sv[0]), rec.recv_buf[:], proactor_on_recv, nil, &rec) != OP_ID_INVALID) + testing.expect( + t, + submit_recv(&loop, uintptr(sv[0]), rec.recv_buf[:], proactor_on_recv, nil, &rec) != OP_ID_INVALID, + ) testing.expect(t, submit_send(&loop, uintptr(sv[1]), three[:], proactor_on_send, nil, &rec) != OP_ID_INVALID) arm_watchdog(&loop) for i in 0 ..< 5 { @@ -219,7 +230,11 @@ proactor_token_encoding :: proc(t: ^testing.T) { testing.expect(t, tok & URING_OP_DOMAIN != 0, "op token must carry the domain bit") testing.expect_value(t, uring_op_token_index(tok), c[0]) testing.expect_value(t, uring_op_token_generation(tok), c[1]) - testing.expect(t, tok != URING_WAKEUP_USER_DATA && tok != URING_CANCEL_USER_DATA, "op token collides with a sentinel") + testing.expect( + t, + tok != URING_WAKEUP_USER_DATA && tok != URING_CANCEL_USER_DATA, + "op token collides with a sentinel", + ) } // A poll-watcher token (no domain bit) is distinguishable from an op token. watcher_tok := uring_encode_token(3, 9) diff --git a/pkg/runtime/eventloop/eventloop_test.odin b/pkg/runtime/eventloop/eventloop_test.odin index 5497b22d..1aad0a7c 100644 --- a/pkg/runtime/eventloop/eventloop_test.odin +++ b/pkg/runtime/eventloop/eventloop_test.odin @@ -329,13 +329,7 @@ interval_cleared_from_own_callback_disposes_binding :: proc(t: ^testing.T) { // Fires twice, then clears itself: it fired (so it was not freed on fire, // unlike a one-shot) and is not re-armed, so it is disposed exactly once. - rec.interval_id = set_interval( - &loop, - record_interval_and_clear_after_two_ticks, - 5, - &rec, - count_dispose, - ) + rec.interval_id = set_interval(&loop, record_interval_and_clear_after_two_ticks, 5, &rec, count_dispose) testing.expect(t, run_until_idle(&loop)) expect_events(t, rec.events[:], []int{1, 1}) testing.expect_value(t, rec.dispose_count, 1) @@ -645,7 +639,9 @@ threadpool_runs_work_offloop_and_completes_on_loop :: proc(t: ^testing.T) { jobs: [3]Pool_Test_Job for i in 0 ..< len(jobs) { - jobs[i] = Pool_Test_Job{rec = &rec} + jobs[i] = Pool_Test_Job { + rec = &rec, + } testing.expect(t, pool_submit(&loop, pool_test_work, pool_test_done, &jobs[i])) } // Each submit pins the loop alive (active_async) until its completion posts. @@ -692,7 +688,9 @@ threadpool_shutdown_disposes_undelivered_jobs :: proc(t: ^testing.T) { N :: 16 jobs: [N]Pool_Dispose_Job for i in 0 ..< N { - jobs[i] = Pool_Dispose_Job{disposed = &disposed} + jobs[i] = Pool_Dispose_Job { + disposed = &disposed, + } testing.expect(t, pool_submit(&loop, pool_test_noop_work, nil, &jobs[i], pool_test_dispose)) } destroy(&loop) // no loop run → no completion delivered → all N jobs disposed @@ -915,9 +913,7 @@ watch_fd_fires_on_readable_socket :: proc(t: ^testing.T) { bound, berr := net.bound_endpoint(listener) if !testing.expect_value(t, berr, nil) do return - client, cerr := net.dial_tcp_from_endpoint( - net.Endpoint{address = net.IP4_Loopback, port = bound.port}, - ) + client, cerr := net.dial_tcp_from_endpoint(net.Endpoint{address = net.IP4_Loopback, port = bound.port}) if !testing.expect_value(t, cerr, nil) do return defer net.close(client) @@ -967,9 +963,7 @@ connect_loopback_pair :: proc(t: ^testing.T) -> (client, server: net.TCP_Socket, bound, berr := net.bound_endpoint(listener) if !testing.expect_value(t, berr, nil) do return - dialed, cerr := net.dial_tcp_from_endpoint( - net.Endpoint{address = net.IP4_Loopback, port = bound.port}, - ) + dialed, cerr := net.dial_tcp_from_endpoint(net.Endpoint{address = net.IP4_Loopback, port = bound.port}) if !testing.expect_value(t, cerr, nil) do return accepted, _, aerr := net.accept_tcp(listener) diff --git a/pkg/runtime/eventloop/loop.odin b/pkg/runtime/eventloop/loop.odin index 3d3a609e..a955dd1e 100644 --- a/pkg/runtime/eventloop/loop.odin +++ b/pkg/runtime/eventloop/loop.odin @@ -148,17 +148,17 @@ Poll_Mode :: enum { // fd is platform-agnostic here; cast to the right type in platform code IO_Watcher :: struct { - fd: uintptr, - mode: Poll_Mode, - callback: Callback, - user_data: rawptr, + fd: uintptr, + mode: Poll_Mode, + callback: Callback, + user_data: rawptr, // watched tracks whether this watcher is currently in the loop's registered set. // It is the single source of truth for active_io_count accounting: the watch/ // unwatch wrappers count off this flag, not the platform syscall result, so no // backend can desync the count (io_uring's logical-only unwatch, an EPOLL_CTL_DEL // that fails because the fd is already closed, a duplicate watch). Owned by the // wrappers; callers must zero-initialize the watcher (a fresh IO_Watcher literal). - watched: bool, + watched: bool, // backend_slot is io_uring-only scratch: the index of this watcher's entry in // Platform_Loop.watch_slots while watched, so unwatch_fd reaches its slot in O(1) // instead of scanning the table. Set by platform_watch_fd, read by @@ -536,20 +536,14 @@ queue_next_tick :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil if callback == nil { return } - append( - &loop.next_ticks, - Task{callback = callback, user_data = user_data, seq = next_sequence(loop)}, - ) + append(&loop.next_ticks, Task{callback = callback, user_data = user_data, seq = next_sequence(loop)}) } queue_microtask :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil) { if callback == nil { return } - append( - &loop.microtasks, - Task{callback = callback, user_data = user_data, seq = next_sequence(loop)}, - ) + append(&loop.microtasks, Task{callback = callback, user_data = user_data, seq = next_sequence(loop)}) } set_timeout :: proc( @@ -572,25 +566,14 @@ set_interval :: proc( return set_timer(loop, callback, interval_ms, interval_ms, true, user_data, dispose) } -set_immediate :: proc( - loop: ^Loop, - callback: Callback, - user_data: rawptr = nil, - dispose: Dispose = nil, -) -> Timer_ID { +set_immediate :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil, dispose: Dispose = nil) -> Timer_ID { if callback == nil { return 0 } id := next_handle_id(loop) append( &loop.immediates, - Task { - id = id, - callback = callback, - user_data = user_data, - dispose = dispose, - seq = next_sequence(loop), - }, + Task{id = id, callback = callback, user_data = user_data, dispose = dispose, seq = next_sequence(loop)}, ) return id } @@ -610,13 +593,7 @@ queue_io_callback :: proc( id := next_handle_id(loop) append( &loop.io_callbacks, - Task { - id = id, - callback = callback, - user_data = user_data, - dispose = dispose, - seq = next_sequence(loop), - }, + Task{id = id, callback = callback, user_data = user_data, dispose = dispose, seq = next_sequence(loop)}, ) return id } @@ -628,10 +605,7 @@ queue_close_callback :: proc(loop: ^Loop, callback: Callback, user_data: rawptr return } id := next_handle_id(loop) - append( - &loop.close_callbacks, - Task{id = id, callback = callback, user_data = user_data, seq = next_sequence(loop)}, - ) + append(&loop.close_callbacks, Task{id = id, callback = callback, user_data = user_data, seq = next_sequence(loop)}) } // timer_ref marks a timer as ref'd (default). Ref'd timers keep the loop alive. O(1) via @@ -1277,8 +1251,7 @@ timer_heap_sift_down :: proc(loop: ^Loop, start: int) { // timer. Cancelled timers were already disposed and uncounted at cancel time, so // no further bookkeeping is needed here. timer_heap_clean_root :: proc(loop: ^Loop) { - for len(loop.timers) > 0 && - (loop.timers[0].cancelled || is_cancel_requested(loop, loop.timers[0].id)) { + for len(loop.timers) > 0 && (loop.timers[0].cancelled || is_cancel_requested(loop, loop.timers[0].id)) { timer_heap_pop_min(loop) } } diff --git a/pkg/runtime/eventloop/loop_linux.odin b/pkg/runtime/eventloop/loop_linux.odin index c5cf30f6..0501222e 100644 --- a/pkg/runtime/eventloop/loop_linux.odin +++ b/pkg/runtime/eventloop/loop_linux.odin @@ -68,7 +68,7 @@ URING_OP_DOMAIN :: u64(1) << 63 force_readiness_backend: bool Platform_Loop :: struct { - use_uring: bool, + use_uring: bool, // Whether the proactor (RECV/SEND completion ops) is usable on this kernel. io_uring_setup // can succeed on kernels predating the single-shot RECV/SEND opcodes (added in 5.6), where // submitting one yields a -EINVAL CQE rather than a synchronous failure. We probe for opcode @@ -76,26 +76,26 @@ Platform_Loop :: struct { // callers fall back to watch_fd instead of mistaking a healthy socket for a failed one (#286). // Implies use_uring (we only probe when the ring initialized); the readiness/poll path on the // same ring stays available on older kernels regardless. - proactor_ok: bool, - ring: uring.Ring, - cqes: [32]linux.IO_Uring_CQE, - epoll_fd: linux.Fd, + proactor_ok: bool, + ring: uring.Ring, + cqes: [32]linux.IO_Uring_CQE, + epoll_fd: linux.Fd, // Self-pipe used by wakeup() to kick the loop out of poll from another thread. // A pipe (not an eventfd): io_uring POLL_ADD reliably completes on a pipe fd // but not on an eventfd in our kernels (#74). [0] = read end, [1] = write end. - wakeup_pipe: [2]linux.Fd, + wakeup_pipe: [2]linux.Fd, // Watcher table backing the generation-token scheme (io_uring only). Slots are // reused across watchers; the array only grows to the high-water mark of // concurrently watched fds, so retention stays bounded to the in-flight set. - watch_slots: [dynamic]Uring_Watch_Slot, + watch_slots: [dynamic]Uring_Watch_Slot, // Free-list of released watch_slots indices, so alloc/release are O(1) (no scan // for a vacant slot). Holds exactly the indices whose slot is currently !in_use. - free_slots: [dynamic]u32, + free_slots: [dynamic]u32, // Completion-op slot table + free-list (proactor RECV/SEND), same generation-token // scheme as watch_slots but in the op token domain. Sized to the high-water mark of // concurrently in-flight ops. - op_slots: [dynamic]Uring_Op_Slot, - op_free: [dynamic]u32, + op_slots: [dynamic]Uring_Op_Slot, + op_free: [dynamic]u32, // Provided-buffer ring (Slice 2a; the memory moat). A shared pool of N×M buffers the kernel // picks from for BUFFER_SELECT RECVs, so an idle connection holds no per-conn read buffer. // bufring_ok gates the ring-recv path (else callers use the 1b per-conn buffer). `bufring` is a @@ -124,8 +124,7 @@ platform_init :: proc(loop: ^Loop) -> bool { loop.platform.epoll_fd = -1 loop.platform.wakeup_pipe = {-1, -1} - if pipe_err := linux.pipe2(&loop.platform.wakeup_pipe, {.CLOEXEC, .NONBLOCK}); - pipe_err != nil { + if pipe_err := linux.pipe2(&loop.platform.wakeup_pipe, {.CLOEXEC, .NONBLOCK}); pipe_err != nil { return false } @@ -362,25 +361,14 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { res: i32 errno: linux.Errno if timeout_ms < 0 { - res, errno = linux.epoll_wait( - loop.platform.epoll_fd, - raw_data(events[:]), - i32(len(events)), - -1, - ) + res, errno = linux.epoll_wait(loop.platform.epoll_fd, raw_data(events[:]), i32(len(events)), -1) } else { remaining := poll_remaining_ms(poll_start, timeout_ms) ts := linux.Time_Spec { time_sec = uint(remaining / 1000), time_nsec = uint((remaining % 1000) * 1_000_000), } - res, errno = linux.epoll_pwait2( - loop.platform.epoll_fd, - raw_data(events[:]), - i32(len(events)), - &ts, - nil, - ) + res, errno = linux.epoll_pwait2(loop.platform.epoll_fd, raw_data(events[:]), i32(len(events)), &ts, nil) } if errno == .EINTR { @@ -481,12 +469,7 @@ drain_uring_completions :: proc(loop: ^Loop) { // arm_uring_poll retries once if the SQ ring is momentarily full rather // than silently dropping the re-arm — otherwise this loop could never be // woken across threads again (post_async could not break a parked poll). - arm_uring_poll( - loop, - u64(loop.platform.wakeup_pipe[0]), - URING_WAKEUP_USER_DATA, - {.IN}, - ) + arm_uring_poll(loop, u64(loop.platform.wakeup_pipe[0]), URING_WAKEUP_USER_DATA, {.IN}) continue } @@ -571,12 +554,7 @@ drain_uring_completions :: proc(loop: ^Loop) { } } -arm_uring_poll :: proc( - loop: ^Loop, - fd: u64, - user_data: u64, - events: linux.Fd_Poll_Events, -) -> bool { +arm_uring_poll :: proc(loop: ^Loop, fd: u64, user_data: u64, events: linux.Fd_Poll_Events) -> bool { sqe, ok := uring.get_sqe(&loop.platform.ring) if !ok { // SQ ring momentarily full: submit to flush staged entries to the kernel @@ -645,10 +623,7 @@ uring_alloc_slot :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> u64 { slot.in_use = true return uring_encode_token(index, slot.generation) } - append( - &loop.platform.watch_slots, - Uring_Watch_Slot{watcher = watcher, generation = 1, in_use = true}, - ) + append(&loop.platform.watch_slots, Uring_Watch_Slot{watcher = watcher, generation = 1, in_use = true}) return uring_encode_token(u32(len(loop.platform.watch_slots) - 1), 1) } @@ -744,8 +719,7 @@ uring_probe_proactor :: proc(ring_fd: linux.Fd) -> (proactor: bool, zc: bool) { // nr_args is the number of ops[] slots offered; the kernel caps its fill to the opcodes it // knows. REGISTER_PROBE itself postdates RECV/SEND, so an error here means an old kernel // without the proactor opcodes — report unsupported and let callers use the readiness path. - if errno := linux.io_uring_register(ring_fd, .REGISTER_PROBE, &probe, u32(len(probe.ops))); - errno != nil { + if errno := linux.io_uring_register(ring_fd, .REGISTER_PROBE, &probe, u32(len(probe.ops))); errno != nil { return false, false } proactor = uring_probe_supports(&probe, .RECV) && uring_probe_supports(&probe, .SEND) @@ -859,12 +833,7 @@ uring_op_slot_live :: proc(loop: ^Loop, index: u32, generation: u32) -> bool { return slot.in_use && slot.generation == generation } -uring_op_alloc_slot :: proc( - loop: ^Loop, - cb: Op_Completion, - dispose: Op_Dispose, - user_data: rawptr, -) -> u64 { +uring_op_alloc_slot :: proc(loop: ^Loop, cb: Op_Completion, dispose: Op_Dispose, user_data: rawptr) -> u64 { if len(loop.platform.op_free) > 0 { index := pop(&loop.platform.op_free) slot := &loop.platform.op_slots[index] @@ -876,13 +845,7 @@ uring_op_alloc_slot :: proc( } append( &loop.platform.op_slots, - Uring_Op_Slot { - callback = cb, - dispose = dispose, - user_data = user_data, - generation = 1, - in_use = true, - }, + Uring_Op_Slot{callback = cb, dispose = dispose, user_data = user_data, generation = 1, in_use = true}, ) return uring_op_encode_token(u32(len(loop.platform.op_slots) - 1), 1) } @@ -1045,13 +1008,7 @@ buf_ring_init :: proc(loop: ^Loop) -> bool { loop.platform.bufring_tail = 0 for bid in 0 ..< u32(URING_BUFRING_ENTRIES) { off := int(bid) * URING_BUFRING_BUFSIZE - buf_ring_add( - loop, - bid, - u64(uintptr(raw_data(pool[off:]))), - URING_BUFRING_BUFSIZE, - u16(bid), - ) + buf_ring_add(loop, bid, u64(uintptr(raw_data(pool[off:]))), URING_BUFRING_BUFSIZE, u16(bid)) } loop.platform.bufring_tail = u16(URING_BUFRING_ENTRIES) buf_ring_publish_tail(loop) @@ -1060,8 +1017,7 @@ buf_ring_init :: proc(loop: ^Loop) -> bool { ring_entries = u32(URING_BUFRING_ENTRIES), bgid = URING_BUFRING_BGID, } - if errno := linux.io_uring_register(loop.platform.ring.fd, .REGISTER_PBUF_RING, ®, 1); - errno != .NONE { + if errno := linux.io_uring_register(loop.platform.ring.fd, .REGISTER_PBUF_RING, ®, 1); errno != .NONE { linux.munmap(ring_ptr, ring_size) delete(pool, loop.allocator) loop.platform.bufring = nil @@ -1140,7 +1096,12 @@ Op_Send_Completion :: proc(loop: ^Loop, user_data: rawptr, res: i32, more: bool) // uring_op_alloc_slot_send allocates an op slot carrying ONLY send_cb (callback/recv_cb stay nil), so // the drain dispatches a SEND_ZC CQE to send_cb. Mirrors uring_op_alloc_slot_recv. -uring_op_alloc_slot_send :: proc(loop: ^Loop, send_cb: Op_Send_Completion, dispose: Op_Dispose, user_data: rawptr) -> u64 { +uring_op_alloc_slot_send :: proc( + loop: ^Loop, + send_cb: Op_Send_Completion, + dispose: Op_Dispose, + user_data: rawptr, +) -> u64 { token := uring_op_alloc_slot(loop, nil, dispose, user_data) loop.platform.op_slots[uring_op_token_index(token)].send_cb = send_cb return token @@ -1151,7 +1112,14 @@ uring_op_alloc_slot_send :: proc(loop: ^Loop, send_cb: Op_Send_Completion, dispo // uring_arm_rw (which zeroes the SQE — clearing ioprio/addr2 — sets opcode/addr/len/msg_flags, retries // once on a full SQ, caps len at URING_MAX_RW, and stages for the batched flush), so the only ZC-specific // bit is the .SEND_ZC opcode. NOSIGNAL like plain SEND. LOOP-THREAD ONLY. -submit_send_zc :: proc(loop: ^Loop, fd: uintptr, buf: []byte, cb: Op_Send_Completion, dispose: Op_Dispose, user_data: rawptr) -> Op_ID { +submit_send_zc :: proc( + loop: ^Loop, + fd: uintptr, + buf: []byte, + cb: Op_Send_Completion, + dispose: Op_Dispose, + user_data: rawptr, +) -> Op_ID { if cb == nil || !loop.platform.proactor_ok do return OP_ID_INVALID token := uring_op_alloc_slot_send(loop, cb, dispose, user_data) if !uring_arm_rw(loop, .SEND_ZC, fd, buf, token, {.NOSIGNAL}) { diff --git a/pkg/runtime/eventloop/loop_windows.odin b/pkg/runtime/eventloop/loop_windows.odin index 59a2cab4..59fc6b59 100644 --- a/pkg/runtime/eventloop/loop_windows.odin +++ b/pkg/runtime/eventloop/loop_windows.odin @@ -68,8 +68,7 @@ make_wakeup_pair :: proc(loop: ^Loop) -> bool { sin_port = 0, // ask the kernel for an ephemeral port sin_addr = {s_addr = transmute(u32)[4]u8{127, 0, 0, 1}}, } - if windows.bind(listener, cast(^windows.SOCKADDR_STORAGE_LH)&addr, size_of(addr)) == - windows.SOCKET_ERROR { + if windows.bind(listener, cast(^windows.SOCKADDR_STORAGE_LH)&addr, size_of(addr)) == windows.SOCKET_ERROR { return false } if windows.listen(listener, 1) == windows.SOCKET_ERROR do return false @@ -77,8 +76,7 @@ make_wakeup_pair :: proc(loop: ^Loop) -> bool { // Recover the bound ephemeral port to connect back to. bound: windows.sockaddr_in bound_len := i32(size_of(bound)) - if windows.getsockname(listener, cast(^windows.SOCKADDR_STORAGE_LH)&bound, &bound_len) == - windows.SOCKET_ERROR { + if windows.getsockname(listener, cast(^windows.SOCKADDR_STORAGE_LH)&bound, &bound_len) == windows.SOCKET_ERROR { return false } @@ -89,11 +87,7 @@ make_wakeup_pair :: proc(loop: ^Loop) -> bool { sin_port = bound.sin_port, sin_addr = {s_addr = transmute(u32)[4]u8{127, 0, 0, 1}}, } - if windows.connect( - send_sock, - cast(^windows.SOCKADDR_STORAGE_LH)&connect_addr, - size_of(connect_addr), - ) == + if windows.connect(send_sock, cast(^windows.SOCKADDR_STORAGE_LH)&connect_addr, size_of(connect_addr)) == windows.SOCKET_ERROR { windows.closesocket(send_sock) return false @@ -127,10 +121,7 @@ set_nonblocking :: proc(sock: windows.SOCKET) -> bool { nonblock: windows.c_ulong = 1 // FIONBIO has its high bit set (0x8004667e), so a checked cast to signed c_long // overflows; reinterpret the bits instead. - return( - windows.ioctlsocket(sock, transmute(windows.c_long)windows.FIONBIO, &nonblock) != - windows.SOCKET_ERROR \ - ) + return windows.ioctlsocket(sock, transmute(windows.c_long)windows.FIONBIO, &nonblock) != windows.SOCKET_ERROR } // platform_close_backend / platform_close_wakeup: the two halves of the teardown, @@ -266,9 +257,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { count := 0 for w in loop.platform.watchers { sock := windows.SOCKET(w.fd) - if fd_set_has(&readfds, sock) || - fd_set_has(&writefds, sock) || - fd_set_has(&exceptfds, sock) { + if fd_set_has(&readfds, sock) || fd_set_has(&writefds, sock) || fd_set_has(&exceptfds, sock) { if count < len(ready) { ready[count] = w count += 1 diff --git a/pkg/runtime/fetch.odin b/pkg/runtime/fetch.odin index 2eeaaced..16a4a2b9 100644 --- a/pkg/runtime/fetch.odin +++ b/pkg/runtime/fetch.odin @@ -78,15 +78,15 @@ Chunk_State :: enum { // settle_tick). Stale io_uring poll completions can no longer reference it: // unwatch_fd truly cancels the poll and invalidates its generation token (#183). Fetch_Request :: struct { - ctx: jsc.JSContextRef, - loop: ^eventloop.Loop, - on_response: jsc.JSObjectRef, // GC-protected JS callback(headersObject) — fires when headers arrive - on_error: jsc.JSObjectRef, // GC-protected JS callback(messageString) — pre-headers failure - on_chunk: jsc.JSObjectRef, // GC-protected JS callback(Uint8Array) -> bool wantMore (body chunk) - on_end: jsc.JSObjectRef, // GC-protected JS callback(errorOrNull) — body complete/errored - cancel_fn: jsc.JSObjectRef, // GC-protected cancel handle (private data == this req) - resume_fn: jsc.JSObjectRef, // GC-protected resume handle (private data == this req) - settled: bool, + ctx: jsc.JSContextRef, + loop: ^eventloop.Loop, + on_response: jsc.JSObjectRef, // GC-protected JS callback(headersObject) — fires when headers arrive + on_error: jsc.JSObjectRef, // GC-protected JS callback(messageString) — pre-headers failure + on_chunk: jsc.JSObjectRef, // GC-protected JS callback(Uint8Array) -> bool wantMore (body chunk) + on_end: jsc.JSObjectRef, // GC-protected JS callback(errorOrNull) — body complete/errored + cancel_fn: jsc.JSObjectRef, // GC-protected cancel handle (private data == this req) + resume_fn: jsc.JSObjectRef, // GC-protected resume handle (private data == this req) + settled: bool, // Streaming request-body (true chunked upload) state. When body_streaming, // request_bytes holds ONLY the head (Transfer-Encoding: chunked, no @@ -114,14 +114,14 @@ Fetch_Request :: struct { // this stored allocator keeps the pair matched regardless of the active context. // (The dynamic-array fields response/carry/body_out carry their own bound // allocator, so delete() frees them correctly without help here.) - allocator: runtime.Allocator, - url: string, - host: string, - path: string, - method: string, - port: int, - request_bytes: []byte, - write_offset: int, + allocator: runtime.Allocator, + url: string, + host: string, + path: string, + method: string, + port: int, + request_bytes: []byte, + write_offset: int, // DNS for a hostname runs on the loop's generic worker pool (#77, fetch_dns.odin): // the lookup result lives on a DNS_Job, not on the request, and the connect is @@ -133,47 +133,47 @@ Fetch_Request :: struct { // and one IPv6 address (ordered A then AAAA); fetch_advance_connect tries them in // turn, advancing on a connect failure and settling an error only when the list // is exhausted. A literal host bypasses this (addr_count stays 0, single connect). - addrs: [2]Fetch_Addr, - addr_count: int, - addr_index: int, + addrs: [2]Fetch_Addr, + addr_count: int, + addr_index: int, // Back-pointer to this request's outstanding DNS job (nil unless a pool lookup // is in flight), so an abort can cancel a still-queued lookup. Set by // fetch_dns_submit, cleared by its completion; loop-thread-only. - dns_job: ^DNS_Job, - response: [dynamic]byte, // accumulates bytes until the header terminator is found + dns_job: ^DNS_Job, + response: [dynamic]byte, // accumulates bytes until the header terminator is found // Length of `response` passed to picohttpparser on the previous (incomplete) head // parse — the `last_len` resume hint, so each read re-scans only new bytes for the // CRLFCRLF terminator rather than the whole accumulated head. 0 until the first read. - head_last_len: int, - watcher: eventloop.IO_Watcher, - fd: uintptr, - has_fd: bool, - phase: Fetch_Phase, + head_last_len: int, + watcher: eventloop.IO_Watcher, + fd: uintptr, + has_fd: bool, + phase: Fetch_Phase, // Streaming response-body state. The transport delivers status + headers as // soon as they are parsed (on_response), then pushes decoded body bytes // incrementally (on_chunk) until the framing completes (on_end). No full-body // buffer is kept; only a small carry holds undecoded chunked framing bytes. - headers_done: bool, - no_body: bool, // HEAD / 204 / 304 / … — settle with a null body, no read - body_is_chunked: bool, - body_len: int, // declared Content-Length; -1 == read until EOF - body_seen: int, // body bytes delivered so far (Content-Length accounting) - body_done: bool, // framing reached its end (final chunk / Content-Length met) - chunk_state: Chunk_State, - chunk_remaining: int, // data bytes left in the current chunk (Chunk_State.Data) - carry: [dynamic]byte, // undecoded chunked framing bytes spanning reads - read_paused: bool, // socket reads suspended for backpressure (consumer saturated) - want_pause: bool, // a delivered chunk reported the consumer is full this turn - drive_pending: int, // queued drive completions (read resume / body drain) referencing this req - settle_tick: u64, // loop iteration at settle; reclaim holds the req two ticks past it + headers_done: bool, + no_body: bool, // HEAD / 204 / 304 / … — settle with a null body, no read + body_is_chunked: bool, + body_len: int, // declared Content-Length; -1 == read until EOF + body_seen: int, // body bytes delivered so far (Content-Length accounting) + body_done: bool, // framing reached its end (final chunk / Content-Length met) + chunk_state: Chunk_State, + chunk_remaining: int, // data bytes left in the current chunk (Chunk_State.Data) + carry: [dynamic]byte, // undecoded chunked framing bytes spanning reads + read_paused: bool, // socket reads suspended for backpressure (consumer saturated) + want_pause: bool, // a delivered chunk reported the consumer is full this turn + drive_pending: int, // queued drive completions (read resume / body drain) referencing this req + settle_tick: u64, // loop iteration at settle; reclaim holds the req two ticks past it // TLS state for https:// requests. is_https gates the TLS path in the // transport; tls is an opaque per-backend session handle kept as rawptr so this // cross-platform struct stays free of any TLS binding, set at handshake start and // released by fetch_tls_cleanup in fetch_request_finish. - is_https: bool, - tls: rawptr, + is_https: bool, + tls: rawptr, } // fetch_cancel_class is a JSClass whose instances carry a ^Fetch_Request as @@ -325,9 +325,7 @@ fetch_end_fn_cb :: proc "c" ( req := cast(^Fetch_Request)jsc.JSObjectGetPrivate(function) if req != nil && !req.settled { is_error := - argument_count >= 1 && - !jsc.JSValueIsNull(ctx, arguments[0]) && - !jsc.JSValueIsUndefined(ctx, arguments[0]) + argument_count >= 1 && !jsc.JSValueIsNull(ctx, arguments[0]) && !jsc.JSValueIsUndefined(ctx, arguments[0]) if is_error { msg, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) defer if alloc do delete(msg, context.allocator) @@ -536,15 +534,7 @@ fetch_request_cb :: proc "c" ( // An IPv6 literal host ([::1]) is returned bracket-stripped (host == "::1"); // build_http_request re-brackets it for the Host header and the Linux transport // connects over AF_INET6. -parse_http_url :: proc( - url: string, -) -> ( - host: string, - port: int, - path: string, - scheme: string, - ok: bool, -) { +parse_http_url :: proc(url: string) -> (host: string, port: int, path: string, scheme: string, ok: bool) { rest := url switch { case strings.has_prefix(rest, "http://"): diff --git a/pkg/runtime/fetch_darwin.odin b/pkg/runtime/fetch_darwin.odin index cb336888..7239e448 100644 --- a/pkg/runtime/fetch_darwin.odin +++ b/pkg/runtime/fetch_darwin.odin @@ -41,7 +41,8 @@ fetch_new_socket :: proc(family: posix.AF) -> posix.FD { cast(posix.Sock_Option)SO_NOSIGPIPE, &one, posix.socklen_t(size_of(one)), - ) != .OK { + ) != + .OK { posix.close(fd) return -1 } @@ -56,10 +57,10 @@ fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) fd := fetch_new_socket(.INET) if fd < 0 do return false, "fetch: could not create socket" addr := posix.sockaddr_in { - sin_len = size_of(posix.sockaddr_in), + sin_len = size_of(posix.sockaddr_in), sin_family = cast(posix.sa_family_t)posix.AF.INET, - sin_port = u16be(port), - sin_addr = {s_addr = transmute(posix.in_addr_t)ip4}, + sin_port = u16be(port), + sin_addr = {s_addr = transmute(posix.in_addr_t)ip4}, } if posix.connect(fd, cast(^posix.sockaddr)&addr, posix.socklen_t(size_of(addr))) != .OK { // EINPROGRESS (and EINTR, a signal interrupting the call) both mean the @@ -111,9 +112,11 @@ fetch_raw_send :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetc sent := posix.send(posix.FD(req.fd), raw_data(chunk), len(chunk), {}) if sent >= 0 do return int(sent), .Ok #partial switch posix.errno() { - case .EAGAIN: // == EWOULDBLOCK on Darwin + case .EAGAIN: + // == EWOULDBLOCK on Darwin return 0, .Would_Block - case .EINTR: // interrupted before any byte was sent — re-poll and retry + case .EINTR: + // interrupted before any byte was sent — re-poll and retry return 0, .Would_Block case: return 0, .Failed @@ -127,9 +130,11 @@ fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_ if got > 0 do return int(got), .Ok if got == 0 do return 0, .Closed #partial switch posix.errno() { - case .EAGAIN: // == EWOULDBLOCK on Darwin + case .EAGAIN: + // == EWOULDBLOCK on Darwin return 0, .Would_Block - case .EINTR: // interrupted before any byte arrived — re-poll and retry + case .EINTR: + // interrupted before any byte arrived — re-poll and retry return 0, .Would_Block case: return 0, .Failed diff --git a/pkg/runtime/fetch_linux.odin b/pkg/runtime/fetch_linux.odin index 0846d772..26511890 100644 --- a/pkg/runtime/fetch_linux.odin +++ b/pkg/runtime/fetch_linux.odin @@ -29,22 +29,14 @@ fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) // EINTR: a signal interrupted connect() before it could report EINPROGRESS; // the connection still proceeds asynchronously, so treat it like EINPROGRESS // rather than a hard failure. - if conn_err := linux.connect(sock_fd, &addr); - conn_err != .NONE && conn_err != .EINPROGRESS && conn_err != .EINTR { + if conn_err := linux.connect(sock_fd, &addr); conn_err != .NONE && conn_err != .EINPROGRESS && conn_err != .EINTR { linux.close(sock_fd) return false, "fetch: connect failed" } return fetch_register_socket(req, uintptr(sock_fd)) } -fetch_connect_ip6 :: proc( - req: ^Fetch_Request, - ip6: net.IP6_Address, - port: int, -) -> ( - ok: bool, - err: string, -) { +fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) -> (ok: bool, err: string) { sock_fd, sock_err := linux.socket(.INET6, .STREAM, {.NONBLOCK}, .TCP) if sock_err != .NONE do return false, "fetch: could not create socket" // IP6_Address is [8]u16be, whose memory layout is already the 16 network-order @@ -57,8 +49,7 @@ fetch_connect_ip6 :: proc( // EINTR: a signal interrupted connect() before it could report EINPROGRESS; // the connection still proceeds asynchronously, so treat it like EINPROGRESS // rather than a hard failure. - if conn_err := linux.connect(sock_fd, &addr); - conn_err != .NONE && conn_err != .EINPROGRESS && conn_err != .EINTR { + if conn_err := linux.connect(sock_fd, &addr); conn_err != .NONE && conn_err != .EINPROGRESS && conn_err != .EINTR { linux.close(sock_fd) return false, "fetch: connect failed" } @@ -124,11 +115,7 @@ fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_ // The io_uring backend re-arms from watcher.mode after this callback returns, so // mutating the field is enough; epoll needs an explicit re-registration. A no-op // when the mode is unchanged. -fetch_set_watch_mode :: proc( - loop: ^eventloop.Loop, - req: ^Fetch_Request, - mode: eventloop.Poll_Mode, -) -> bool { +fetch_set_watch_mode :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, mode: eventloop.Poll_Mode) -> bool { if req.watcher.mode == mode do return true if loop.platform.use_uring { req.watcher.mode = mode diff --git a/pkg/runtime/fetch_tls.odin b/pkg/runtime/fetch_tls.odin index 3b16c10f..8a4fecd5 100644 --- a/pkg/runtime/fetch_tls.odin +++ b/pkg/runtime/fetch_tls.odin @@ -55,11 +55,7 @@ Fetch_TLS_Outcome :: enum { // close_notify; SSL_ERROR_SYSCALL with ret == 0 is an EOF without one (common // for HTTP/1.1 Connection: close), while ret < 0 is a genuine syscall failure // and stays Fatal so truncation is not silently treated as completion. -fetch_tls_classify :: proc( - loop: ^eventloop.Loop, - req: ^Fetch_Request, - ret: c.int, -) -> Fetch_TLS_Outcome { +fetch_tls_classify :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, ret: c.int) -> Fetch_TLS_Outcome { switch SSL_get_error(cast(SSL)req.tls, ret) { case SSL_ERROR_WANT_READ: // A failed re-arm becomes Fatal so the caller settles instead of stalling. @@ -120,14 +116,7 @@ fetch_tls_write :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // armed for readability, a WANT_WRITE for writability — collapsing both to "write" // would spin on writable events, or deadlock when the send buffer is full and the // peer's renegotiation bytes can only be read. -fetch_tls_send_chunk :: proc( - req: ^Fetch_Request, - chunk: []byte, -) -> ( - n: int, - res: Fetch_IO_Result, - want_read: bool, -) { +fetch_tls_send_chunk :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetch_IO_Result, want_read: bool) { ret := SSL_write(cast(SSL)req.tls, raw_data(chunk), c.int(len(chunk))) if ret > 0 do return int(ret), .Ok, false switch SSL_get_error(cast(SSL)req.tls, ret) { diff --git a/pkg/runtime/fetch_transport.odin b/pkg/runtime/fetch_transport.odin index 13fb1586..269ff432 100644 --- a/pkg/runtime/fetch_transport.odin +++ b/pkg/runtime/fetch_transport.odin @@ -29,14 +29,7 @@ Fetch_IO_Result :: enum { // deferred to dns_resolve_done (run back on the loop thread via // post_async). Returns ok=false with a message only for an immediate failure; the // async path returns ok=true and settles later. -fetch_transport_start :: proc( - req: ^Fetch_Request, - host: string, - port: int, -) -> ( - ok: bool, - err: string, -) { +fetch_transport_start :: proc(req: ^Fetch_Request, host: string, port: int) -> (ok: bool, err: string) { // Reject https:// up front on backends without TLS (fetch_tls_supported == // false), before any DNS lookup or outbound connect — so an unsupported // request fails instantly and locally instead of after network work. diff --git a/pkg/runtime/fetch_windows.odin b/pkg/runtime/fetch_windows.odin index 829f4227..81921ac1 100644 --- a/pkg/runtime/fetch_windows.odin +++ b/pkg/runtime/fetch_windows.odin @@ -28,8 +28,7 @@ fetch_new_socket :: proc(family: windows.c_int) -> windows.SOCKET { nonblock: windows.c_ulong = 1 // FIONBIO has its high bit set, so a checked cast to signed c_long overflows; // reinterpret the bits instead (same as the event loop's wakeup socket). - if windows.ioctlsocket(sock, transmute(windows.c_long)windows.FIONBIO, &nonblock) == - windows.SOCKET_ERROR { + if windows.ioctlsocket(sock, transmute(windows.c_long)windows.FIONBIO, &nonblock) == windows.SOCKET_ERROR { windows.closesocket(sock) return windows.INVALID_SOCKET } @@ -66,20 +65,13 @@ fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) if sock == windows.INVALID_SOCKET do return false, "fetch: could not create socket" addr := windows.sockaddr_in { sin_family = windows.ADDRESS_FAMILY(windows.AF_INET), - sin_port = u16be(port), - sin_addr = {s_addr = transmute(u32)ip4}, + sin_port = u16be(port), + sin_addr = {s_addr = transmute(u32)ip4}, } return fetch_start_connect(req, sock, cast(^windows.SOCKADDR_STORAGE_LH)&addr, size_of(addr)) } -fetch_connect_ip6 :: proc( - req: ^Fetch_Request, - ip6: net.IP6_Address, - port: int, -) -> ( - ok: bool, - err: string, -) { +fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) -> (ok: bool, err: string) { sock := fetch_new_socket(windows.AF_INET6) if sock == windows.INVALID_SOCKET do return false, "fetch: could not create socket" // net.IP6_Address is [8]u16be, whose memory layout is already the 16 @@ -130,11 +122,7 @@ fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_ // instead of stalling forever). The select backend reads watcher.mode when it // builds each fd_set, but re-registering explicitly (like epoll/kqueue) keeps this // correct regardless of how the backend tracks interest. A no-op when unchanged. -fetch_set_watch_mode :: proc( - loop: ^eventloop.Loop, - req: ^Fetch_Request, - mode: eventloop.Poll_Mode, -) -> bool { +fetch_set_watch_mode :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, mode: eventloop.Poll_Mode) -> bool { if req.watcher.mode == mode do return true eventloop.unwatch_fd(loop, &req.watcher) req.watcher.mode = mode diff --git a/pkg/runtime/fs.odin b/pkg/runtime/fs.odin index 2b592580..1ced3ee8 100644 --- a/pkg/runtime/fs.odin +++ b/pkg/runtime/fs.odin @@ -1,10 +1,10 @@ package lava_runtime import "base:runtime" -import "core:crypto" -import "core:io" import "core:c" +import "core:crypto" import "core:fmt" +import "core:io" import "core:os" import "core:path/filepath" import "core:strings" @@ -272,7 +272,11 @@ fs_make_error :: proc(ctx: jsc.JSContextRef, code, syscall, path: string, errno_ // fs_make_rename_error builds Node's rename error, which differs from the generic // fs error in two ways: the message names both paths ("rename 'old' -> 'new'") // and the error carries a `dest` property in addition to `path`. -fs_make_rename_error :: proc(ctx: jsc.JSContextRef, code, old_path, new_path: string, errno_val := 0) -> jsc.JSValueRef { +fs_make_rename_error :: proc( + ctx: jsc.JSContextRef, + code, old_path, new_path: string, + errno_val := 0, +) -> jsc.JSValueRef { msg := fmt.tprintf("%s: %s, rename '%s' -> '%s'", code, fs_errno_text(code), old_path, new_path) err := make_js_error(ctx, msg) if jsc.JSValueIsObject(ctx, err) { @@ -290,23 +294,40 @@ fs_make_rename_error :: proc(ctx: jsc.JSContextRef, code, old_path, new_path: st fs_errno_text :: proc(code: string) -> string { switch code { - case "ENOENT": return "no such file or directory" - case "EEXIST": return "file already exists" - case "ENOTDIR": return "not a directory" - case "EISDIR": return "illegal operation on a directory" - case "EACCES": return "permission denied" - case "EPERM": return "operation not permitted" - case "ENOTEMPTY": return "directory not empty" - case "EIO": return "i/o error" - case "EROFS": return "read-only file system" - case "ENOSPC": return "no space left on device" - case "EBADF": return "bad file descriptor" - case "EMFILE": return "too many open files" - case "ENFILE": return "file table overflow" - case "ELOOP": return "too many symbolic links encountered" - case "EINVAL": return "invalid argument" - case "ENOSYS": return "function not implemented" - case "ERR_FS_EISDIR": return "Path is a directory" + case "ENOENT": + return "no such file or directory" + case "EEXIST": + return "file already exists" + case "ENOTDIR": + return "not a directory" + case "EISDIR": + return "illegal operation on a directory" + case "EACCES": + return "permission denied" + case "EPERM": + return "operation not permitted" + case "ENOTEMPTY": + return "directory not empty" + case "EIO": + return "i/o error" + case "EROFS": + return "read-only file system" + case "ENOSPC": + return "no space left on device" + case "EBADF": + return "bad file descriptor" + case "EMFILE": + return "too many open files" + case "ENFILE": + return "file table overflow" + case "ELOOP": + return "too many symbolic links encountered" + case "EINVAL": + return "invalid argument" + case "ENOSYS": + return "function not implemented" + case "ERR_FS_EISDIR": + return "Path is a directory" } return "i/o error" } @@ -356,15 +377,21 @@ fs_os_error_to_code :: proc(err: os.Error) -> (code: string, errno_val: int) { #partial switch e in err { case os.General_Error: #partial switch e { - case .Not_Exist: return "ENOENT", 2 - case .Exist: return "EEXIST", 17 - case .Invalid_Dir: return "EISDIR", 21 - case: return "EIO", 5 + case .Not_Exist: + return "ENOENT", 2 + case .Exist: + return "EEXIST", 17 + case .Invalid_Dir: + return "EISDIR", 21 + case: + return "EIO", 5 } case io.Error: #partial switch e { - case .Permission_Denied: return "EACCES", 13 - case: return "EIO", 5 + case .Permission_Denied: + return "EACCES", 13 + case: + return "EIO", 5 } case os.Platform_Error: when ODIN_OS == .Windows { @@ -372,11 +399,16 @@ fs_os_error_to_code :: proc(err: os.Error) -> (code: string, errno_val: int) { // POSIX errno, so map the codes the fs paths actually produce. (Best // effort: the node-compat fs suite does not yet run on Windows CI.) switch i32(e) { - case 2, 3, 267: return "ENOENT", 2 // FILE_NOT_FOUND / PATH_NOT_FOUND / DIRECTORY (libuv maps ERROR_DIRECTORY -> ENOENT) - case 5: return "EACCES", 13 // ACCESS_DENIED - case 80, 183: return "EEXIST", 17 // FILE_EXISTS / ALREADY_EXISTS - case 145: return "ENOTEMPTY", 41 // DIR_NOT_EMPTY (CRT errno 41 on Win32) - case: return "EIO", 5 + case 2, 3, 267: + return "ENOENT", 2 // FILE_NOT_FOUND / PATH_NOT_FOUND / DIRECTORY (libuv maps ERROR_DIRECTORY -> ENOENT) + case 5: + return "EACCES", 13 // ACCESS_DENIED + case 80, 183: + return "EEXIST", 17 // FILE_EXISTS / ALREADY_EXISTS + case 145: + return "ENOTEMPTY", 41 // DIR_NOT_EMPTY (CRT errno 41 on Win32) + case: + return "EIO", 5 } } else { // Linux + Darwin/BSD: i32(e) is the platform errno, so it is the @@ -384,16 +416,26 @@ fs_os_error_to_code :: proc(err: os.Error) -> (code: string, errno_val: int) { // these platforms need both arms — notably ENOTEMPTY (Linux 39, BSD 66). errno := int(i32(e)) switch errno { - case 1: return "EPERM", errno - case 2: return "ENOENT", errno - case 13: return "EACCES", errno - case 17: return "EEXIST", errno - case 20: return "ENOTDIR", errno - case 21: return "EISDIR", errno - case 28: return "ENOSPC", errno - case 30: return "EROFS", errno - case 39, 66: return "ENOTEMPTY", errno - case: return "EIO", 5 + case 1: + return "EPERM", errno + case 2: + return "ENOENT", errno + case 13: + return "EACCES", errno + case 17: + return "EEXIST", errno + case 20: + return "ENOTDIR", errno + case 21: + return "EISDIR", errno + case 28: + return "ENOSPC", errno + case 30: + return "EROFS", errno + case 39, 66: + return "ENOTEMPTY", errno + case: + return "EIO", 5 } } case: @@ -435,7 +477,11 @@ is_data_view :: proc(ctx: jsc.JSContextRef, obj: jsc.JSObjectRef) -> bool { fs_resolve_write_payload :: proc( ctx: jsc.JSContextRef, value: jsc.JSValueRef, -) -> (bytes: []byte, owned: bool, ok: bool) { +) -> ( + bytes: []byte, + owned: bool, + ok: bool, +) { t := jsc.JSValueGetTypedArrayType(ctx, value, nil) // A bare ArrayBuffer is not a valid fs write payload (Node: ERR_INVALID_ARG_TYPE). if t == .ArrayBuffer do return nil, false, false @@ -1195,14 +1241,7 @@ fs_build_stats :: proc(ctx: jsc.JSContextRef, info: os.File_Info) -> jsc.JSValue // surface in Object.keys / JSON.stringify of the Stats object. ftype_name := jsc.JSStringCreateWithUTF8CString("__lava_ftype") defer jsc.JSStringRelease(ftype_name) - jsc.JSObjectSetProperty( - ctx, - obj, - ftype_name, - jsc.JSValueMakeNumber(ctx, f64(ftype)), - {.DontEnum}, - nil, - ) + jsc.JSObjectSetProperty(ctx, obj, ftype_name, jsc.JSValueMakeNumber(ctx, f64(ftype)), {.DontEnum}, nil) inject_native_function(ctx, obj, "isFile", stats_is_file_cb) inject_native_function(ctx, obj, "isDirectory", stats_is_directory_cb) diff --git a/pkg/runtime/fs_fd_posix.odin b/pkg/runtime/fs_fd_posix.odin index 01493239..60a48f31 100644 --- a/pkg/runtime/fs_fd_posix.odin +++ b/pkg/runtime/fs_fd_posix.odin @@ -10,15 +10,7 @@ import "core:sys/posix" // fs_platform_open opens `path` with a Node flags string and create mode, returning the // fd on success or a Node error code (+ errno) on failure. -fs_platform_open :: proc( - path: string, - flags_str: string, - mode: int, -) -> ( - fd: int, - err_code: string, - errno_val: int, -) { +fs_platform_open :: proc(path: string, flags_str: string, mode: int) -> (fd: int, err_code: string, errno_val: int) { flags, ok := fs_open_flags(flags_str) if !ok do return -1, "EINVAL", 22 diff --git a/pkg/runtime/fs_fd_windows.odin b/pkg/runtime/fs_fd_windows.odin index c88bcf01..3e3fa3e0 100644 --- a/pkg/runtime/fs_fd_windows.odin +++ b/pkg/runtime/fs_fd_windows.odin @@ -4,15 +4,7 @@ package lava_runtime // Linux-first stubs: fs.openSync/closeSync are not implemented on Windows yet (the // POSIX implementation lives in fs_fd_posix.odin). They report ENOSYS so callers get a // clean error rather than a crash. -fs_platform_open :: proc( - path: string, - flags_str: string, - mode: int, -) -> ( - fd: int, - err_code: string, - errno_val: int, -) { +fs_platform_open :: proc(path: string, flags_str: string, mode: int) -> (fd: int, err_code: string, errno_val: int) { return -1, "ENOSYS", 38 } diff --git a/pkg/runtime/globals.odin b/pkg/runtime/globals.odin index e8ee9525..1edb786b 100644 --- a/pkg/runtime/globals.odin +++ b/pkg/runtime/globals.odin @@ -276,12 +276,7 @@ module_cache_get :: proc(state: ^Runtime_State, key: string) -> (jsc.JSValueRef, // allocation failed (base/runtime/dynamic_map_internal.odin). Same signal the // host-native registry uses. @(private = "file") -module_cache_insert_new :: proc( - ctx: jsc.JSContextRef, - state: ^Runtime_State, - key: string, - value: jsc.JSValueRef, -) { +module_cache_insert_new :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string, value: jsc.JSValueRef) { cloned, err := strings.clone(key, state.allocator) if err != nil do return jsc.JSValueProtect(ctx, value) @@ -291,12 +286,7 @@ module_cache_insert_new :: proc( } } -module_cache_put :: proc( - ctx: jsc.JSContextRef, - state: ^Runtime_State, - key: string, - value: jsc.JSValueRef, -) { +module_cache_put :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string, value: jsc.JSValueRef) { if state == nil do return if _, ok := state.module_cache[key]; ok do return module_cache_insert_new(ctx, state, key, value) @@ -307,12 +297,7 @@ module_cache_put :: proc( // evaluating its body (so a re-entrant/circular require returns the partial // exports) and again afterwards to store the final exports (the body may have // reassigned module.exports). Replacing re-points GC protection to the new value. -module_cache_set :: proc( - ctx: jsc.JSContextRef, - state: ^Runtime_State, - key: string, - value: jsc.JSValueRef, -) { +module_cache_set :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string, value: jsc.JSValueRef) { if state == nil do return if entry, ok := state.module_cache[key]; ok { if entry.value == value do return @@ -573,13 +558,7 @@ set_timeout_cb :: proc "c" ( // Trailing args (setTimeout(fn, delay, ...args)) are forwarded on fire. cb := make_js_callback(ctx, fn, false, capture_timer_args(ctx, argument_count, arguments, 2, alloc), alloc) - id := eventloop.set_timeout( - loop, - js_callback_trampoline, - clamp_timer_delay(delay), - cb, - js_callback_dispose, - ) + id := eventloop.set_timeout(loop, js_callback_trampoline, clamp_timer_delay(delay), cb, js_callback_dispose) return jsc.JSValueMakeNumber(ctx, f64(id)) } @@ -606,13 +585,7 @@ set_interval_cb :: proc "c" ( // Trailing args (setInterval(fn, delay, ...args)) are forwarded on every fire. cb := make_js_callback(ctx, fn, true, capture_timer_args(ctx, argument_count, arguments, 2, alloc), alloc) - id := eventloop.set_interval( - loop, - js_callback_trampoline, - clamp_timer_delay(interval), - cb, - js_callback_dispose, - ) + id := eventloop.set_interval(loop, js_callback_trampoline, clamp_timer_delay(interval), cb, js_callback_dispose) return jsc.JSValueMakeNumber(ctx, f64(id)) } @@ -1002,14 +975,7 @@ install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef, surfa args := [3]jsc.JSValueRef{cast(jsc.JSValueRef)global, process, cast(jsc.JSValueRef)report} exception: jsc.JSValueRef - exports := jsc.JSObjectCallAsFunction( - ctx, - cast(jsc.JSObjectRef)factory, - nil, - 3, - raw_data(args[:]), - &exception, - ) + exports := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)factory, nil, 3, raw_data(args[:]), &exception) if exception != nil { report_internal_exception(ctx, "lava:microtasks", exception) return @@ -1101,14 +1067,7 @@ drain_next_ticks_settled :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { if state == nil || state.next_tick_drain == nil do return for { exc: jsc.JSValueRef - result := jsc.JSObjectCallAsFunction( - ctx, - cast(jsc.JSObjectRef)state.next_tick_drain, - nil, - 0, - nil, - &exc, - ) + result := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)state.next_tick_drain, nil, 0, nil, &exc) if exc != nil { report_uncaught(ctx, exc) mark_async_failed(ctx) @@ -1208,14 +1167,7 @@ install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) args := [2]jsc.JSValueRef{cast(jsc.JSValueRef)compile, cast(jsc.JSValueRef)natives} exception: jsc.JSValueRef - resolver := jsc.JSObjectCallAsFunction( - ctx, - cast(jsc.JSObjectRef)loader, - nil, - 2, - raw_data(args[:]), - &exception, - ) + resolver := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)loader, nil, 2, raw_data(args[:]), &exception) if exception != nil { report_internal_exception(ctx, "internal:loader", exception) return @@ -1406,14 +1358,7 @@ install_stdio :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { if proc_obj == nil || !jsc.JSValueIsObject(ctx, proc_obj) do return args := [1]jsc.JSValueRef{proc_obj} exception: jsc.JSValueRef - jsc.JSObjectCallAsFunction( - ctx, - cast(jsc.JSObjectRef)installer, - nil, - 1, - raw_data(args[:]), - &exception, - ) + jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)installer, nil, 1, raw_data(args[:]), &exception) if exception != nil do report_internal_exception(ctx, "internal:stdio", exception) } @@ -1434,14 +1379,7 @@ install_console :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { args := [2]jsc.JSValueRef{cast(jsc.JSValueRef)out_fn, cast(jsc.JSValueRef)err_fn} exception: jsc.JSValueRef - jsc.JSObjectCallAsFunction( - ctx, - cast(jsc.JSObjectRef)factory, - nil, - 2, - raw_data(args[:]), - &exception, - ) + jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)factory, nil, 2, raw_data(args[:]), &exception) if exception != nil do report_internal_exception(ctx, "lava:console", exception) } @@ -1494,7 +1432,15 @@ node_module_excluded :: proc(id: string) -> bool { return false } else { switch id { - case "node/sqlite", "node/fs", "node/os", "node/net", "node/http", "node/https", "node/dns", "node/tty", "node/dns/promises": + case "node/sqlite", + "node/fs", + "node/os", + "node/net", + "node/http", + "node/https", + "node/dns", + "node/tty", + "node/dns/promises": return true } return strings.has_prefix(id, "internal/http/") || strings.has_prefix(id, "internal/os/") @@ -1523,10 +1469,7 @@ js_override_dir :: proc() -> string { } if last_sep < 0 do return "" runtime_dir := file[:last_sep] - marker, err := strings.concatenate( - {runtime_dir, "/../../bin/.lava.js-override"}, - context.temp_allocator, - ) + marker, err := strings.concatenate({runtime_dir, "/../../bin/.lava.js-override"}, context.temp_allocator) if err != nil || !os.exists(marker) do return "" return runtime_dir } @@ -1617,12 +1560,7 @@ process_version_string :: proc() -> string { // --- helpers --- -set_named :: proc( - ctx: jsc.JSContextRef, - object: jsc.JSObjectRef, - name: string, - value: jsc.JSValueRef, -) { +set_named :: proc(ctx: jsc.JSContextRef, object: jsc.JSObjectRef, name: string, value: jsc.JSValueRef) { c_name, err := strings.clone_to_cstring(name, context.temp_allocator) if err != nil do return js_name := jsc.JSStringCreateWithUTF8CString(c_name) diff --git a/pkg/runtime/host_natives.odin b/pkg/runtime/host_natives.odin index a79a298c..bc7b1999 100644 --- a/pkg/runtime/host_natives.odin +++ b/pkg/runtime/host_natives.odin @@ -22,11 +22,7 @@ import jsc "lava:pkg/jsc" // pass as the function/thisObject parameters (nil when `this` is not a cell — // the callbacks that read it only ever receive objects), and a callback-set // exception becomes a real VM throw, matching JSCallbackFunction. -host_dispatch :: proc "c" ( - global: rawptr, - cf: [^]u64, - cb: jsc.JSObjectCallAsFunctionCallback, -) -> i64 { +host_dispatch :: proc "c" (global: rawptr, cf: [^]u64, cb: jsc.JSObjectCallAsFunctionCallback) -> i64 { context = runtime.default_context() // valid allocator for the overflow slice below ctx := jsc.JSContextRef(global) argc := int(u32(cf[jsc.CALL_FRAME_ARGC_SLOT] & 0xFFFFFFFF)) - 1 // minus `this` @@ -119,9 +115,12 @@ Host_Native_Key :: struct { // free_all'd between tests) or an embedder's per-eval arena, every later insert // writes through a reclaimed backing and corrupts whatever now occupies it. // Same rule Runtime_State.module_cache already follows (globals.odin). -@(private = "file", thread_local) g_host_native_fns: map[Host_Native_Key]jsc.JSObjectRef -@(private = "file", thread_local) g_host_native_cbs: map[rawptr]jsc.JSObjectCallAsFunctionCallback -@(private = "file", thread_local) g_host_tables_bound: bool +@(private = "file", thread_local) +g_host_native_fns: map[Host_Native_Key]jsc.JSObjectRef +@(private = "file", thread_local) +g_host_native_cbs: map[rawptr]jsc.JSObjectCallAsFunctionCallback +@(private = "file", thread_local) +g_host_tables_bound: bool // bind_host_tables gives both tables a backing allocator that outlives them, // before anything can insert. runtime.default_allocator() is the only lifetime @@ -145,16 +144,8 @@ bind_host_tables :: proc() { if g_host_tables_bound do return g_host_tables_bound = true sync.atomic_add(&g_host_tables_live, 1) - g_host_native_fns, _ = make( - map[Host_Native_Key]jsc.JSObjectRef, - 64, - runtime.default_allocator(), - ) - g_host_native_cbs, _ = make( - map[rawptr]jsc.JSObjectCallAsFunctionCallback, - 64, - runtime.default_allocator(), - ) + g_host_native_fns, _ = make(map[Host_Native_Key]jsc.JSObjectRef, 64, runtime.default_allocator()) + g_host_native_cbs, _ = make(map[rawptr]jsc.JSObjectCallAsFunctionCallback, 64, runtime.default_allocator()) } // g_host_tables_live counts the threads whose host-native tables are bound and not @@ -201,10 +192,7 @@ generic_native_host_cb :: proc "c" (global: rawptr, cf: [^]u64) -> i64 { // #force_no_inline proc restores the previous codegen instruction-for-instruction. cb, found := g_host_native_cbs[rawptr(uintptr(cf[jsc.CALL_FRAME_CALLEE_SLOT]))] if !found { - return host_dispatch_fail( - jsc.JSContextRef(global), - "lava: host native dispatch failed (unregistered callee)", - ) + return host_dispatch_fail(jsc.JSContextRef(global), "lava: host native dispatch failed (unregistered callee)") } return host_dispatch(global, cf, cb) } diff --git a/pkg/runtime/http.odin b/pkg/runtime/http.odin index d450cb53..0f262fa5 100644 --- a/pkg/runtime/http.odin +++ b/pkg/runtime/http.odin @@ -30,7 +30,13 @@ make_http_bindings :: proc(ctx: jsc.JSContextRef) -> jsc.JSObjectRef { inject_native_function(ctx, bindings, "parseRequest", http_parse_request_cb, http_parse_request_host) // Response-head serialization: same latin1WriteInto as node:buffer (package-local // callback). Avoids a Buffer require + intermediate array on every writeHead/end. - inject_native_function(ctx, bindings, "latin1WriteInto", buffer_latin1_write_into_cb, buffer_latin1_write_into_host) + inject_native_function( + ctx, + bindings, + "latin1WriteInto", + buffer_latin1_write_into_cb, + buffer_latin1_write_into_host, + ) return bindings } diff --git a/pkg/runtime/module_resolution.odin b/pkg/runtime/module_resolution.odin index 33837381..273353be 100644 --- a/pkg/runtime/module_resolution.odin +++ b/pkg/runtime/module_resolution.odin @@ -172,10 +172,7 @@ is_absolute_path :: proc(path: string) -> bool { // Leading separator, including UNC paths (\\server\share) and '//'. if path[0] == '/' || path[0] == '\\' do return true // Drive-letter absolute path: 'C:\' or 'C:/'. - if len(path) >= 3 && - is_ascii_letter(path[0]) && - path[1] == ':' && - (path[2] == '/' || path[2] == '\\') { + if len(path) >= 3 && is_ascii_letter(path[0]) && path[1] == ':' && (path[2] == '/' || path[2] == '\\') { return true } return false diff --git a/pkg/runtime/net.odin b/pkg/runtime/net.odin index b2e48ca4..4e2c2d93 100644 --- a/pkg/runtime/net.odin +++ b/pkg/runtime/net.odin @@ -277,12 +277,7 @@ net_listen_cb :: proc "c" ( // every socket sharing the port must set it, or the group is unsafe (a bind would collide). Surface // the failure as a startup abort. if g_multi_worker { - if so_err := linux.setsockopt( - sfd, - linux.SOL_SOCKET, - linux.Socket_Option.REUSEPORT, - &reuse, - ); so_err != .NONE { + if so_err := linux.setsockopt(sfd, linux.SOL_SOCKET, linux.Socket_Option.REUSEPORT, &reuse); so_err != .NONE { linux.close(sfd) net_startup_failed() if exception != nil do exception^ = make_js_error(ctx, "net.listen: SO_REUSEPORT failed") @@ -467,12 +462,7 @@ net_connect_io_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // getsockopt_base directly: the _sock overload's where-clause tests the // POINTEE type (a core:sys/linux quirk in this Odin build), so ^i32 never // matches it. - _, _ = linux.getsockopt_base( - linux.Fd(conn.fd), - cast(int)linux.SOL_SOCKET, - linux.Socket_Option.ERROR, - &soerr, - ) + _, _ = linux.getsockopt_base(linux.Fd(conn.fd), cast(int)linux.SOL_SOCKET, linux.Socket_Option.ERROR, &soerr) if soerr == 0 { fn := conn.on_connect conn.on_connect = nil @@ -480,10 +470,7 @@ net_connect_io_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { net_unprotect(conn.ctx, fn) return } - net_emit_error( - conn, - fmt.tprintf("connect %s %s", net_connect_errno_name(soerr), conn.connect_label), - ) + net_emit_error(conn, fmt.tprintf("connect %s %s", net_connect_errno_name(soerr), conn.connect_label)) net_close_conn(conn, true) } @@ -632,13 +619,7 @@ net_start_cb :: proc "c" ( // readiness watcher. The mode is set ONLY on a successful submit (never count a failed one). if !net_force_readiness() && eventloop.proactor_available(conn.loop) { if eventloop.bufring_available(conn.loop) { - id := eventloop.submit_recv_ring( - conn.loop, - conn.fd, - net_recv_ring_complete, - on_op_dispose, - conn, - ) + id := eventloop.submit_recv_ring(conn.loop, conn.fd, net_recv_ring_complete, on_op_dispose, conn) if id != eventloop.OP_ID_INVALID { conn.io_mode = .ProactorRing // no recv_buf — reads draw from the shared ring conn.recv_op = id @@ -647,14 +628,7 @@ net_start_cb :: proc "c" ( } } conn.recv_buf = make([]byte, NET_PROACTOR_RECV, context.allocator) - id := eventloop.submit_recv( - conn.loop, - conn.fd, - conn.recv_buf, - on_recv_complete, - on_op_dispose, - conn, - ) + id := eventloop.submit_recv(conn.loop, conn.fd, conn.recv_buf, on_recv_complete, on_op_dispose, conn) if id != eventloop.OP_ID_INVALID { conn.io_mode = .Proactor conn.recv_op = id @@ -694,8 +668,7 @@ net_force_readiness_state: enum u8 { net_force_readiness :: proc() -> bool { if net_force_readiness_state == .Unknown { - net_force_readiness_state = - os.get_env("LAVA_NET_FORCE_READINESS", context.temp_allocator) != "" ? .Yes : .No + net_force_readiness_state = os.get_env("LAVA_NET_FORCE_READINESS", context.temp_allocator) != "" ? .Yes : .No } return net_force_readiness_state == .Yes } @@ -731,27 +704,14 @@ net_maybe_arm_recv :: proc(conn: ^Net_Connection) -> bool { id: eventloop.Op_ID if conn.io_mode == .ProactorRing { // Shared ring: no per-conn buffer; the kernel picks one at completion (net_recv_ring_complete). - id = eventloop.submit_recv_ring( - conn.loop, - conn.fd, - net_recv_ring_complete, - on_op_dispose, - conn, - ) + id = eventloop.submit_recv_ring(conn.loop, conn.fd, net_recv_ring_complete, on_op_dispose, conn) // Record THIS op's submission mode so its completion can attribute a -EINVAL correctly: a // multishot op's -EINVAL means "kernel lacks RECV_MULTISHOT" (fall back); a single-shot op's // -EINVAL is a genuine error (close), never a capability signal to re-arm into a loop. conn.recv_multishot = eventloop.recv_ring_multishot(conn.loop) conn.recv_cancel_pending = false // a fresh op has no backpressure cancel outstanding } else { - id = eventloop.submit_recv( - conn.loop, - conn.fd, - conn.recv_buf, - on_recv_complete, - on_op_dispose, - conn, - ) + id = eventloop.submit_recv(conn.loop, conn.fd, conn.recv_buf, on_recv_complete, on_op_dispose, conn) } if id == eventloop.OP_ID_INVALID { net_emit_error(conn, "read submit failed") @@ -1027,10 +987,7 @@ net_zc_stats_note :: proc(loop: ^eventloop.Loop, use_zc: bool) { if os.get_env("LAVA_ZC_STATS", context.temp_allocator) == "" do return if !g_zc_ok_reported { g_zc_ok_reported = true - os.write_string( - os.stderr, - eventloop.send_zc_ok(loop) ? "LAVA_ZC: zc_ok=1\n" : "LAVA_ZC: zc_ok=0\n", - ) + os.write_string(os.stderr, eventloop.send_zc_ok(loop) ? "LAVA_ZC: zc_ok=1\n" : "LAVA_ZC: zc_ok=0\n") } if use_zc && !g_zc_engaged_reported { g_zc_engaged_reported = true @@ -1050,30 +1007,16 @@ net_zc_stats_note :: proc(loop: ^eventloop.Loop, use_zc: bool) { // saw_result/zc_err are reset per submission (one send op per conn, so this is the per-op reset). // PRECONDITION: send_op == INVALID (the caller cleared/gated). net_proactor_submit :: proc(conn: ^Net_Connection, force_plain := false) { - assert( - conn.send_op == eventloop.OP_ID_INVALID, - "net_proactor_submit: a send is already in flight", - ) + assert(conn.send_op == eventloop.OP_ID_INVALID, "net_proactor_submit: a send is already in flight") conn.saw_result = false conn.zc_err = 0 buf := conn.active_send[conn.active_send_off:] - use_zc := - !force_plain && - !conn.zc_unsupported && - eventloop.send_zc_ok(conn.loop) && - len(buf) >= NET_ZC_THRESHOLD + use_zc := !force_plain && !conn.zc_unsupported && eventloop.send_zc_ok(conn.loop) && len(buf) >= NET_ZC_THRESHOLD conn.send_was_zc = use_zc net_zc_stats_note(conn.loop, use_zc) // M3: env-gated stderr evidence that the SEND_ZC path actually ran id: eventloop.Op_ID if use_zc { - id = eventloop.submit_send_zc( - conn.loop, - conn.fd, - buf, - net_send_zc_complete, - on_op_dispose, - conn, - ) + id = eventloop.submit_send_zc(conn.loop, conn.fd, buf, net_send_zc_complete, on_op_dispose, conn) } else { id = eventloop.submit_send(conn.loop, conn.fd, buf, on_send_complete, on_op_dispose, conn) } @@ -1216,9 +1159,7 @@ net_proactor_on_drained :: proc(conn: ^Net_Connection) { if conn.closing do return } net_maybe_arm_recv(conn) // recomputes read_paused from the (possibly new) buffered count - if conn.end_after_drain && - conn.send_op == eventloop.OP_ID_INVALID && - len(conn.pending_writes) == 0 { + if conn.end_after_drain && conn.send_op == eventloop.OP_ID_INVALID && len(conn.pending_writes) == 0 { net_close_conn(conn, false) } } @@ -1545,9 +1486,7 @@ net_end_cb :: proc "c" ( if conn.tls do tls_server_begin_close(conn) else do net_proactor_kick_send(conn) // Nothing left to drain → close now; otherwise on_send_complete closes once drained. - if !conn.closing && - conn.send_op == eventloop.OP_ID_INVALID && - len(conn.pending_writes) == 0 { + if !conn.closing && conn.send_op == eventloop.OP_ID_INVALID && len(conn.pending_writes) == 0 { net_close_conn(conn, false) } return jsc.JSValueMakeUndefined(ctx) @@ -1765,8 +1704,7 @@ net_shutdown_active :: proc(state: ^Runtime_State) { net_unprotect(conn.ctx, conn.on_close) net_unprotect(conn.ctx, conn.on_error) net_unprotect(conn.ctx, conn.on_drain) - conn.on_data, conn.on_end, conn.on_close, conn.on_error, conn.on_drain = - nil, nil, nil, nil, nil + conn.on_data, conn.on_end, conn.on_close, conn.on_error, conn.on_drain = nil, nil, nil, nil, nil if conn.recv_starved { conn.recv_starved = false // the whole starved list is cleared after this loop eventloop.async_cancel(conn.loop) // balance the parked liveness ref @@ -1865,12 +1803,7 @@ net_unprotect :: proc(ctx: jsc.JSContextRef, fn: jsc.JSObjectRef) { if fn != nil do jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)fn) } -net_emit :: proc( - ctx: jsc.JSContextRef, - fn: jsc.JSObjectRef, - args: [^]jsc.JSValueRef, - argc: c.size_t, -) { +net_emit :: proc(ctx: jsc.JSContextRef, fn: jsc.JSObjectRef, args: [^]jsc.JSValueRef, argc: c.size_t) { if fn == nil do return exception: jsc.JSValueRef invoke_user_callback(ctx, fn, args, argc, &exception) diff --git a/pkg/runtime/os_linux.odin b/pkg/runtime/os_linux.odin index bf703781..c9cb9f55 100644 --- a/pkg/runtime/os_linux.odin +++ b/pkg/runtime/os_linux.odin @@ -147,8 +147,7 @@ os_cpus :: proc() -> []Os_Cpu { // Per-CPU tick counters: the "cpuN" lines of /proc/stat (the bare "cpu " total // is skipped). Columns are user, nice, system, idle, iowait, irq, softirq, ... - if data, err := os.read_entire_file("/proc/stat", context.temp_allocator); - err == os.ERROR_NONE { + if data, err := os.read_entire_file("/proc/stat", context.temp_allocator); err == os.ERROR_NONE { for line in strings.split(string(data), "\n", context.temp_allocator) { if len(line) < 4 || !strings.has_prefix(line, "cpu") { continue @@ -174,8 +173,7 @@ os_cpus :: proc() -> []Os_Cpu { // is exactly what Node reports in the same situation. models := make([dynamic]string, 0, 8, context.temp_allocator) speeds := make([dynamic]int, 0, 8, context.temp_allocator) - if data, err := os.read_entire_file("/proc/cpuinfo", context.temp_allocator); - err == os.ERROR_NONE { + if data, err := os.read_entire_file("/proc/cpuinfo", context.temp_allocator); err == os.ERROR_NONE { cur_model := "" cur_speed := 0 have := false diff --git a/pkg/runtime/os_windows.odin b/pkg/runtime/os_windows.odin index 7ba290bb..5bdfbb87 100644 --- a/pkg/runtime/os_windows.odin +++ b/pkg/runtime/os_windows.odin @@ -295,7 +295,8 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { // current process: GetCurrentProcess returns a pseudo-handle needing no close. os_get_priority :: proc(pid: int) -> (value: int, err: int) { current := pid == 0 - handle := current ? windows.GetCurrentProcess() : windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, windows.FALSE, windows.DWORD(pid)) + handle := + current ? windows.GetCurrentProcess() : windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, windows.FALSE, windows.DWORD(pid)) if handle == nil { return 0, win_errno(windows.GetLastError()) } @@ -389,16 +390,7 @@ reg_get_string :: proc(subkey, value: string) -> string { wsub := windows.utf8_to_wstring(subkey, context.temp_allocator) wval := windows.utf8_to_wstring(value, context.temp_allocator) size: windows.DWORD - if windows.RegGetValueW( - windows.HKEY_LOCAL_MACHINE, - wsub, - wval, - windows.RRF_RT_REG_SZ, - nil, - nil, - &size, - ) != - 0 || + if windows.RegGetValueW(windows.HKEY_LOCAL_MACHINE, wsub, wval, windows.RRF_RT_REG_SZ, nil, nil, &size) != 0 || size < 2 { return "" } @@ -459,7 +451,8 @@ win_errno :: proc(gle: windows.DWORD) -> int { EACCES :: 13 EINVAL :: 22 switch gle { - case windows.ERROR_INVALID_PARAMETER: // OpenProcess on a non-existent pid + case windows.ERROR_INVALID_PARAMETER: + // OpenProcess on a non-existent pid return ESRCH case windows.ERROR_ACCESS_DENIED: return EACCES diff --git a/pkg/runtime/picohttpparser/.clang-format b/pkg/runtime/picohttpparser/.clang-format new file mode 100644 index 00000000..91a4ee98 --- /dev/null +++ b/pkg/runtime/picohttpparser/.clang-format @@ -0,0 +1,4 @@ +# Vendored upstream code (picohttpparser): keep its own formatting, so a re-vendor diffs +# cleanly. +DisableFormat: true +SortIncludes: Never diff --git a/pkg/runtime/picohttpparser/picohttpparser.odin b/pkg/runtime/picohttpparser/picohttpparser.odin index 6a1fed50..7d9eaac9 100644 --- a/pkg/runtime/picohttpparser/picohttpparser.odin +++ b/pkg/runtime/picohttpparser/picohttpparser.odin @@ -113,7 +113,10 @@ parse_response :: proc( h := raw[i] name := h.name != nil && h.name_len > 0 ? string(h.name[:h.name_len]) : "" value := h.value != nil && h.value_len > 0 ? string(h.value[:h.value_len]) : "" - out[i] = Header{name = name, value = value} + out[i] = Header { + name = name, + value = value, + } } if msg_ptr != nil && msg_len > 0 do msg = string(msg_ptr[:msg_len]) return int(ret), int(status_c), msg, num, .Complete @@ -167,7 +170,10 @@ parse_request :: proc( h := raw[i] name := h.name != nil && h.name_len > 0 ? string(h.name[:h.name_len]) : "" value := h.value != nil && h.value_len > 0 ? string(h.value[:h.value_len]) : "" - out[i] = Header{name = name, value = value} + out[i] = Header { + name = name, + value = value, + } } if method_ptr != nil && method_len > 0 do method = string(method_ptr[:method_len]) if path_ptr != nil && path_len > 0 do path = string(path_ptr[:path_len]) diff --git a/pkg/runtime/require.odin b/pkg/runtime/require.odin index 1d6cc308..8240889a 100644 --- a/pkg/runtime/require.odin +++ b/pkg/runtime/require.odin @@ -243,12 +243,7 @@ native_require_cb :: proc "c" ( // make_module_not_found builds the Error Node throws for an unresolved require, // including the `code: 'MODULE_NOT_FOUND'` property user code commonly checks. make_module_not_found :: proc(ctx: jsc.JSContextRef, specifier: string) -> jsc.JSValueRef { - return make_native_error( - ctx, - "Error", - fmt.tprintf("Cannot find module '%s'", specifier), - "MODULE_NOT_FOUND", - ) + return make_native_error(ctx, "Error", fmt.tprintf("Cannot find module '%s'", specifier), "MODULE_NOT_FOUND") } // inject_native_function attaches a native function to `object`, preferring diff --git a/pkg/runtime/runtime.odin b/pkg/runtime/runtime.odin index 9f8c30a2..8741c3a4 100644 --- a/pkg/runtime/runtime.odin +++ b/pkg/runtime/runtime.odin @@ -28,10 +28,10 @@ Status :: enum { } Result :: struct { - status: Status, - exit_code: int, - message: string, - is_allocated: bool, + status: Status, + exit_code: int, + message: string, + is_allocated: bool, // True when the event loop exited because its backend poll failed fatally (loop.backend_error), // not because work drained or a stop was requested. The multi-worker supervisor reads this to tell // a crashed worker from one that finished cleanly (so a crash stops the other workers). @@ -218,11 +218,15 @@ eval :: proc( if strings.has_prefix(source_name, "node:") { if loop != nil do eventloop.destroy(loop) - return reported(Result { - status = .Invalid_Input, - exit_code = 2, - message = "node: specifiers are module names, not eval source names", - }, report, report_data) + return reported( + Result { + status = .Invalid_Input, + exit_code = 2, + message = "node: specifiers are module names, not eval source names", + }, + report, + report_data, + ) } // The ESM transform rewrites an `.mjs` entry to CommonJS that calls `require` and @@ -230,11 +234,15 @@ eval :: proc( // context exists, rather than failing inside the transformed body. if surface == .Web && strings.has_suffix(source_name, ".mjs") { if loop != nil do eventloop.destroy(loop) - return reported(Result { - status = .Invalid_Input, - exit_code = 2, - message = "the web global surface runs classic scripts only; .mjs sources need the node surface", - }, report, report_data) + return reported( + Result { + status = .Invalid_Input, + exit_code = 2, + message = "the web global surface runs classic scripts only; .mjs sources need the node surface", + }, + report, + report_data, + ) } // A JS runtime must survive writes to closed pipes/sockets (Node parity): @@ -276,10 +284,7 @@ eval :: proc( // script path (omitted for `lava eval`, where there is no script file). Built in // the per-eval temp arena, which outlives install_process (see the defer above). state.script_argv = build_process_argv(source_name, script_args) - jsc.JSObjectSetPrivate( - jsc.JSContextGetGlobalObject(cast(jsc.JSContextRef)ctx), - cast(rawptr)state, - ) + jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(cast(jsc.JSContextRef)ctx), cast(rawptr)state) // Runs before the context is released (defers execute in reverse order), so // JSValueUnprotect on cached modules still has a live context. defer destroy_runtime_state(cast(jsc.JSContextRef)ctx, state) @@ -338,20 +343,14 @@ eval :: proc( defer if mjs_allocated do delete(mjs_wrapped) if strings.has_suffix(source_name, ".mjs") { wrap_exception: jsc.JSValueRef - wrapped, ok := esm_wrap_source( - cast(jsc.JSContextRef)ctx, - source, - source_name, - &wrap_exception, - ) + wrapped, ok := esm_wrap_source(cast(jsc.JSContextRef)ctx, source, source_name, &wrap_exception) if !ok { msg, allocated := value_to_string(cast(jsc.JSContextRef)ctx, wrap_exception) - return reported(Result { - status = .Execution_Error, - exit_code = 1, - message = msg, - is_allocated = allocated, - }, report, report_data) + return reported( + Result{status = .Execution_Error, exit_code = 1, message = msg, is_allocated = allocated}, + report, + report_data, + ) } eval_source = wrapped mjs_wrapped = wrapped @@ -380,64 +379,55 @@ eval :: proc( // runs on both surfaces; it goes through Runtime_State, not a global. TOP_LEVEL_DRAIN :: "\n;var __lava_tl_drain = (typeof __lavaDrainNextTicks === 'function') && __lavaDrainNextTicks();\n" if surface == .Node { - if combined, concat_err := strings.concatenate( - {eval_source, TOP_LEVEL_DRAIN}, - context.temp_allocator, - ); concat_err == nil { + if combined, concat_err := strings.concatenate({eval_source, TOP_LEVEL_DRAIN}, context.temp_allocator); + concat_err == nil { eval_source = combined } } script := js_string_from_string(eval_source) if script == nil { - return reported(Result { - status = .Invalid_Input, - exit_code = 2, - message = "could not allocate JavaScript source string", - }, report, report_data) + return reported( + Result{status = .Invalid_Input, exit_code = 2, message = "could not allocate JavaScript source string"}, + report, + report_data, + ) } defer jsc.JSStringRelease(script) - c_source_name, c_source_name_err := strings.clone_to_cstring( - source_name, - context.temp_allocator, - ) + c_source_name, c_source_name_err := strings.clone_to_cstring(source_name, context.temp_allocator) if c_source_name_err != nil { - return reported(Result { - status = .Invalid_Input, - exit_code = 2, - message = "could not allocate JavaScript source name", - }, report, report_data) + return reported( + Result{status = .Invalid_Input, exit_code = 2, message = "could not allocate JavaScript source name"}, + report, + report_data, + ) } source_url := jsc.JSStringCreateWithUTF8CString(c_source_name) if source_url == nil { - return reported(Result { - status = .Invalid_Input, - exit_code = 2, - message = "could not allocate JavaScript source URL object", - }, report, report_data) + return reported( + Result { + status = .Invalid_Input, + exit_code = 2, + message = "could not allocate JavaScript source URL object", + }, + report, + report_data, + ) } defer jsc.JSStringRelease(source_url) exception: jsc.JSValueRef - value := jsc.JSEvaluateScript( - cast(jsc.JSContextRef)ctx, - script, - nil, - source_url, - 1, - &exception, - ) + value := jsc.JSEvaluateScript(cast(jsc.JSContextRef)ctx, script, nil, source_url, 1, &exception) if exception != nil { msg, allocated := value_to_string(cast(jsc.JSContextRef)ctx, exception) - return reported(Result { - status = .Execution_Error, - exit_code = 1, - message = msg, - is_allocated = allocated, - }, report, report_data) + return reported( + Result{status = .Execution_Error, exit_code = 1, message = msg, is_allocated = allocated}, + report, + report_data, + ) } // Refresh the cached entry exports: a CommonJS entry body may have reassigned @@ -481,13 +471,17 @@ eval :: proc( } msg, allocated := value_to_string(cast(jsc.JSContextRef)ctx, value) - return reported(Result { - status = .Ok, - exit_code = exit_code, - message = msg, - is_allocated = allocated, - backend_failed = backend_failed, - }, report, report_data) + return reported( + Result { + status = .Ok, + exit_code = exit_code, + message = msg, + is_allocated = allocated, + backend_failed = backend_failed, + }, + report, + report_data, + ) } // resolve_exit_code computes the final process exit code after the event loop @@ -527,21 +521,21 @@ run_file :: proc( ) -> Result { if len(path) == 0 { if loop != nil do eventloop.destroy(loop) - return reported(Result { - status = .Invalid_Input, - exit_code = 2, - message = "missing JavaScript file path", - }, report, report_data) + return reported( + Result{status = .Invalid_Input, exit_code = 2, message = "missing JavaScript file path"}, + report, + report_data, + ) } data, err := os.read_entire_file(path, context.allocator) if err != os.ERROR_NONE { if loop != nil do eventloop.destroy(loop) - return reported(Result { - status = .Read_Error, - exit_code = 1, - message = "could not read JavaScript file", - }, report, report_data) + return reported( + Result{status = .Read_Error, exit_code = 1, message = "could not read JavaScript file"}, + report, + report_data, + ) } defer delete(data) diff --git a/pkg/runtime/sqlite.odin b/pkg/runtime/sqlite.odin index 0b2c7f4e..056cbf65 100644 --- a/pkg/runtime/sqlite.odin +++ b/pkg/runtime/sqlite.odin @@ -395,11 +395,7 @@ sqlite_error :: proc(ctx: jsc.JSContextRef, message: string) -> jsc.JSValueRef { // out-of-range index — how node:sqlite reports too many positional params) as a // JS Error carrying SQLite's text and the ERR_SQLITE_ERROR code, instead of // letting the statement execute with the slot silently unbound. -sqlite_throw_bind_error :: proc( - ctx: jsc.JSContextRef, - res: sqlite.Result, - exception: ^jsc.JSValueRef, -) { +sqlite_throw_bind_error :: proc(ctx: jsc.JSContextRef, res: sqlite.Result, exception: ^jsc.JSValueRef) { if res.status == .Ok do return if exception == nil do return // Don't clobber a more specific exception already set by the caller. @@ -560,10 +556,7 @@ sqlite_int_value :: proc( if read_big_ints do return sqlite_make_bigint(ctx, v) if (v > SQLITE_MAX_SAFE_INTEGER || v < -SQLITE_MAX_SAFE_INTEGER) { if exception != nil { - msg := fmt.tprintf( - "Value is too large to be represented as a JavaScript number: %d", - v, - ) + msg := fmt.tprintf("Value is too large to be represented as a JavaScript number: %d", v) exception^ = make_native_error(ctx, "RangeError", msg, "ERR_OUT_OF_RANGE") } return jsc.JSValueMakeUndefined(ctx) @@ -581,14 +574,7 @@ sqlite_make_bigint :: proc(ctx: jsc.JSContextRef, v: i64) -> jsc.JSValueRef { fn := jsc.JSObjectGetProperty(ctx, global, name, nil) if !jsc.JSValueIsObject(ctx, fn) do return jsc.JSValueMakeNumber(ctx, f64(v)) args := [1]jsc.JSValueRef{js_string_value(ctx, s)} - result := jsc.JSObjectCallAsFunction( - ctx, - cast(jsc.JSObjectRef)fn, - nil, - 1, - raw_data(args[:]), - nil, - ) + result := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)fn, nil, 1, raw_data(args[:]), nil) if result == nil do return jsc.JSValueMakeNumber(ctx, f64(v)) return result } diff --git a/pkg/runtime/tls.odin b/pkg/runtime/tls.odin index 5f22b514..59cdfdb1 100644 --- a/pkg/runtime/tls.odin +++ b/pkg/runtime/tls.odin @@ -240,8 +240,7 @@ tls_new_client :: proc(fd: uintptr, host: string) -> SSL { } } else { // SSL_ctrl returns 1 on a successful SET_TLSEXT_HOSTNAME. - if SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, rawptr(chost)) != - 1 { + if SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, rawptr(chost)) != 1 { SSL_free(ssl) return nil } diff --git a/pkg/runtime/tls_darwin.odin b/pkg/runtime/tls_darwin.odin index 59960853..72037146 100644 --- a/pkg/runtime/tls_darwin.odin +++ b/pkg/runtime/tls_darwin.odin @@ -201,7 +201,8 @@ darwin_ssl_read_cb :: proc "c" (connection: SSLConnectionRef, data: rawptr, data #partial switch posix.get_errno() { case .EINTR: continue // interrupted before any byte arrived — retry - case .EAGAIN: // == EWOULDBLOCK on Darwin + case .EAGAIN: + // == EWOULDBLOCK on Darwin sess.want = .Read status = errSSLWouldBlock case: @@ -234,7 +235,8 @@ darwin_ssl_write_cb :: proc "c" (connection: SSLConnectionRef, data: rawptr, dat #partial switch posix.get_errno() { case .EINTR: continue // interrupted before any byte was sent — retry - case .EAGAIN: // == EWOULDBLOCK on Darwin + case .EAGAIN: + // == EWOULDBLOCK on Darwin sess.want = .Write status = errSSLWouldBlock case: diff --git a/pkg/runtime/typed_array.odin b/pkg/runtime/typed_array.odin index f5ae9c9d..ee653d0d 100644 --- a/pkg/runtime/typed_array.odin +++ b/pkg/runtime/typed_array.odin @@ -23,7 +23,7 @@ import jsc "lava:pkg/jsc" BytesPtr_Mode :: enum u8 { Unknown, Base_Plus_Offset, // BytesPtr == ArrayBuffer base (gtk today) - View_Start, // BytesPtr == base + offset (fixed JSC) + View_Start, // BytesPtr == base + offset (fixed JSC) } // Thread-local: the gtk-bug mode is a build-global fact, but each worker's JSC @@ -144,12 +144,7 @@ make_uint8_array_uninit :: proc(ctx: jsc.JSContextRef, size: int) -> (jsc.JSValu heap := runtime.heap_allocator() data, err := mem.alloc_bytes_non_zeroed(size, mem.DEFAULT_ALIGNMENT, heap) if err != nil || len(data) != size do return nil, false - array := jsc.make_uint8_nocopy_locked( - ctx, - raw_data(data), - c.size_t(size), - jsc_buffer_deallocator, - ) + array := jsc.make_uint8_nocopy_locked(ctx, raw_data(data), c.size_t(size), jsc_buffer_deallocator) if array == nil do return nil, false return cast(jsc.JSValueRef)array, true } diff --git a/pkg/runtime/workers.odin b/pkg/runtime/workers.odin index c72f9c5a..d98ada98 100644 --- a/pkg/runtime/workers.odin +++ b/pkg/runtime/workers.odin @@ -63,13 +63,13 @@ g_multi_worker: bool // - g_worker_crashed: a worker's loop died abnormally (backend_failed); the supervisor stops the rest. // - g_worker_exits: incremented by each worker as it exits, so the supervisor knows when all are done // (non-server scripts) without treating a clean finish as a crash. -g_shutdown: bool -g_worker_crashed: bool -g_worker_exits: int +g_shutdown: bool +g_worker_crashed: bool +g_worker_exits: int // Set by net_startup_failed when a listener fails to bind / set SO_REUSEPORT during startup, or // listen(0) is rejected under multi-worker. A worker checks it in its pre-run hook and aborts startup // (M7: all listeners bind or the whole startup aborts — no running with partial/partitioned capacity). -g_listen_failed: bool +g_listen_failed: bool // net_startup_failed records a fatal startup listener failure (called from net.odin, Linux). Aborting // is process-wide: every worker runs the same script, so a bind failure on one means the deployment diff --git a/pkg/runtime/workers_linux.odin b/pkg/runtime/workers_linux.odin index 7483feaa..c3bdd1f4 100644 --- a/pkg/runtime/workers_linux.odin +++ b/pkg/runtime/workers_linux.odin @@ -19,9 +19,7 @@ SUPERVISOR_TICK_MS :: 200 shutdown_sigset :: proc() -> linux.Sig_Set { set: linux.Sig_Set // Sig_Set is a bitmask; signal n is bit (n-1). SIGINT(2) and SIGTERM(15) both fall in word 0. - set[0] = - (uint(1) << (uint(linux.Signal.SIGINT) - 1)) | - (uint(1) << (uint(linux.Signal.SIGTERM) - 1)) + set[0] = (uint(1) << (uint(linux.Signal.SIGINT) - 1)) | (uint(1) << (uint(linux.Signal.SIGTERM) - 1)) return set } diff --git a/pkg/runtime/workers_test.odin b/pkg/runtime/workers_test.odin index 69ea369a..f4ca433b 100644 --- a/pkg/runtime/workers_test.odin +++ b/pkg/runtime/workers_test.odin @@ -14,7 +14,17 @@ import eventloop "lava:pkg/runtime/eventloop" worker_count_parsing :: proc(t: ^testing.T) { expect_ok :: proc(t: ^testing.T, raw: string, has: bool, cpu: int, want: int) { n, ok, _ := lava_parse_worker_count(raw, has, cpu) - testing.expectf(t, ok && n == want, "parse(%q,%v,cpu=%d): got (n=%d ok=%v), want n=%d ok", raw, has, cpu, n, ok, want) + testing.expectf( + t, + ok && n == want, + "parse(%q,%v,cpu=%d): got (n=%d ok=%v), want n=%d ok", + raw, + has, + cpu, + n, + ok, + want, + ) } expect_fail :: proc(t: ^testing.T, raw: string, has: bool, cpu: int) { _, ok, msg := lava_parse_worker_count(raw, has, cpu) @@ -177,5 +187,11 @@ workers_give_back_their_host_tables :: proc(t: ^testing.T) { testing.expectf(t, workers[i].result.exit_code == 0, "worker %d exit code %d", i, workers[i].result.exit_code) result_destroy(&workers[i].result) } - testing.expectf(t, host_native_tables_live() == baseline, "host-native tables live after workers exited: %d, want baseline %d", host_native_tables_live(), baseline) + testing.expectf( + t, + host_native_tables_live() == baseline, + "host-native tables live after workers exited: %d, want baseline %d", + host_native_tables_live(), + baseline, + ) } diff --git a/pkg/std/sqlite/sqlite.odin b/pkg/std/sqlite/sqlite.odin index d138e115..c94ffef0 100644 --- a/pkg/std/sqlite/sqlite.odin +++ b/pkg/std/sqlite/sqlite.odin @@ -409,9 +409,7 @@ bind_text :: proc(stmt: ^Statement, index: int, value: string) -> Result { // Explicit length (not strlen): an embedded NUL is a legal byte in SQLite // TEXT, so the whole slice is bound, not just up to the first NUL. cval := strings.clone_to_cstring(value, context.temp_allocator) - return bind_result( - sqlite3_bind_text(stmt.handle, c.int(index), cval, c.int(len(value)), sqlite_transient()), - ) + return bind_result(sqlite3_bind_text(stmt.handle, c.int(index), cval, c.int(len(value)), sqlite_transient())) } } @@ -437,9 +435,7 @@ bind_blob :: proc(stmt: ^Statement, index: int, value: []byte) -> Result { } empty: byte ptr := len(value) > 0 ? rawptr(raw_data(value)) : rawptr(&empty) - return bind_result( - sqlite3_bind_blob(stmt.handle, c.int(index), ptr, c.int(len(value)), sqlite_transient()), - ) + return bind_result(sqlite3_bind_blob(stmt.handle, c.int(index), ptr, c.int(len(value)), sqlite_transient())) } } From 854ca7562553956107fa9448ba83402c71d3de38 Mon Sep 17 00:00:00 2001 From: x_ror <16686943+x-ror@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:55:59 +0200 Subject: [PATCH 2/3] build(fmt): braces on every if, and a blank line around every if MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner's rules, now in CLAUDE.md §4 and applied by `make fmt`: - `if` always has braces, on their own lines: no `if x do y`, no `if x {y}`. odinfmt's convert_do (odinfmt.json) and clang-format's InsertBraces (.clang-format) add the braces; scripts/fmt-if.mjs spreads the one-line blocks odinfmt leaves behind. - A blank line before and after every `if` statement, unless it opens or closes a block or a case; a comment directly above belongs to the if. No formatter does this, so scripts/fmt-if.mjs does. It tracks strings, comments and Odin's multi-line raw strings, so embedded JS in the tests is untouched. Applied to cmd/lava, pkg/jsc, pkg/runtime and pkg/std/sqlite; `make fmt` is stable on the result (a second run changes nothing). Nine mutation-manifest entries pointed at `if … do` lines and were retargeted to the same code in its new form; every find matches exactly once. Formatting only. Checked: `make check` (all three targets), `make build`, and a `lava eval` touching nextTick, microtasks, timers, URL, Buffer and require. No tests run: paused for this phase. Co-Authored-By: Claude Opus 5.5 --- .clang-format | 2 + CLAUDE.md | 5 + Makefile | 3 + cmd/lava/buffer_reentrancy_test.odin | 7 +- cmd/lava/dns_alloc_test.odin | 6 +- cmd/lava/errors_test.odin | 50 +- cmd/lava/fetch_url_test.odin | 12 +- cmd/lava/fs_write_payload_test.odin | 11 +- cmd/lava/global_surface_test.odin | 2 + cmd/lava/host_native_alloc_test.odin | 4 +- cmd/lava/host_native_failclosed_test.odin | 10 +- cmd/lava/host_native_registry_test.odin | 95 ++- cmd/lava/jsc_predicates_test.odin | 8 +- cmd/lava/lazy_builtins_test.odin | 17 +- cmd/lava/main.odin | 3 + cmd/lava/module_cache_rollback_test.odin | 6 +- cmd/lava/net_teardown_stress_test.odin | 34 +- cmd/lava/nocopy_bytes_alloc_test.odin | 4 +- cmd/lava/pool_cancel_hooks_test.odin | 40 +- cmd/lava/repeated_eval_test.odin | 4 +- cmd/lava/stdio_fd_guard_test.odin | 6 +- cmd/lava/timer_binding_alloc_test.odin | 2 + odinfmt.json | 3 +- pkg/jsc/host_function.odin | 54 +- pkg/jsc/private_string.odin | 241 ++++-- pkg/jsc/private_value.odin | 34 +- pkg/jsc/private_view.odin | 148 +++- pkg/jsc/string_utf8.odin | 13 +- pkg/runtime/buffer.odin | 504 +++++++++--- pkg/runtime/buffer_simd.odin | 45 +- pkg/runtime/buffer_utf8.odin | 134 +++- pkg/runtime/crypto.odin | 120 ++- pkg/runtime/dns.odin | 92 ++- pkg/runtime/environment.odin | 135 +++- pkg/runtime/errors.odin | 68 +- .../eventloop_close_running_test.odin | 11 +- .../eventloop/eventloop_close_test.odin | 33 +- .../eventloop_close_wakeup_test.odin | 11 +- .../eventloop/eventloop_fd_lifetime_test.odin | 16 +- .../eventloop/eventloop_proactor_test.odin | 191 ++++- pkg/runtime/eventloop/eventloop_test.odin | 186 ++++- pkg/runtime/eventloop/loop.odin | 166 +++- pkg/runtime/eventloop/loop_darwin.odin | 10 + pkg/runtime/eventloop/loop_linux.odin | 235 +++++- pkg/runtime/eventloop/loop_windows.odin | 46 +- pkg/runtime/eventloop/threadpool.odin | 86 ++- pkg/runtime/fetch.odin | 341 +++++++-- pkg/runtime/fetch_darwin.odin | 47 +- pkg/runtime/fetch_dns.odin | 25 +- pkg/runtime/fetch_linux.odin | 22 +- pkg/runtime/fetch_tls.odin | 19 +- pkg/runtime/fetch_tls_darwin.odin | 25 +- pkg/runtime/fetch_transport.odin | 100 ++- pkg/runtime/fetch_windows.odin | 53 +- pkg/runtime/fs.odin | 509 ++++++++++-- pkg/runtime/fs_fd_posix.odin | 69 +- pkg/runtime/globals.odin | 510 +++++++++--- pkg/runtime/host_natives.odin | 90 ++- pkg/runtime/http.odin | 24 +- pkg/runtime/js_root.odin | 15 +- pkg/runtime/module_resolution.odin | 106 ++- pkg/runtime/net.odin | 723 ++++++++++++++---- pkg/runtime/net_other.odin | 5 +- pkg/runtime/net_zc_test.odin | 24 + pkg/runtime/os.odin | 35 +- pkg/runtime/os_darwin.odin | 28 + pkg/runtime/os_linux.odin | 35 + pkg/runtime/os_posix.odin | 34 + pkg/runtime/os_windows.odin | 51 +- .../picohttpparser/picohttpparser.odin | 6 +- pkg/runtime/require.odin | 88 ++- pkg/runtime/runtime.odin | 96 ++- pkg/runtime/sqlite.odin | 306 ++++++-- pkg/runtime/stdio.odin | 10 +- pkg/runtime/stdio_posix.odin | 6 +- pkg/runtime/tls.odin | 40 +- pkg/runtime/tls_darwin.odin | 108 ++- pkg/runtime/tls_roots_windows.odin | 20 +- pkg/runtime/tls_server.odin | 225 ++++-- pkg/runtime/tty.odin | 12 +- pkg/runtime/typed_array.odin | 54 +- pkg/runtime/workers.odin | 66 +- pkg/runtime/workers_linux.odin | 16 +- pkg/runtime/workers_test.odin | 33 +- pkg/std/sqlite/sqlite.odin | 118 ++- scripts/fmt-if.mjs | 198 +++++ tests/mutation-manifest.json | 28 +- 87 files changed, 6061 insertions(+), 1172 deletions(-) create mode 100644 scripts/fmt-if.mjs diff --git a/.clang-format b/.clang-format index 18efa895..a8b19d6a 100644 --- a/.clang-format +++ b/.clang-format @@ -15,6 +15,8 @@ AccessModifierOffset: -4 AllowShortFunctionsOnASingleLine: Inline AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: Never +# Every if/else/for/while body gets braces (CLAUDE.md §4). +InsertBraces: true AllowShortLoopsOnASingleLine: false IncludeBlocks: Preserve # #includes sorted within each blank-line-separated block. clang-format cannot reorder diff --git a/CLAUDE.md b/CLAUDE.md index 0a91b6c1..cc0b80e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -153,6 +153,11 @@ appears in CI, read the code or shrink the CPU set; do not just re-run. imports) and `odin strip-semicolon` for Odin, clang-format (`.clang-format`: tabs, 120 columns) for C/C++. odinfmt ships with the OLS extension; pass `ODINFMT=/path/to/odinfmt` when it is not on PATH. +- **`if` always has braces, on their own lines** — no `if x do y`, no `if x {y}` — + and **a blank line before and after every `if` statement**, unless it opens or + closes a block or a `case` (a comment directly above belongs to the `if`). Applied + by `make fmt`: odinfmt `convert_do`, clang-format `InsertBraces`, then + `scripts/fmt-if.mjs`, which neither formatter covers. - **Declaration order in a file**, Odin and C alike: imports/includes (sorted), then constants, then types, then procedures — public ones first, private helpers last. The formatters sort imports and includes; nothing reorders declarations, so this is diff --git a/Makefile b/Makefile index dd804376..07bf2516 100644 --- a/Makefile +++ b/Makefile @@ -373,6 +373,9 @@ fmt: $(ODIN) strip-semicolon cmd/lava -collection:lava=. $(ODIN) strip-semicolon pkg/jsc -no-entry-point clang-format -i pkg/jsc/*.cpp + # Multi-line blocks after if/else/for and blank lines around if: no formatter does + # either (scripts/fmt-if.mjs). Run after odinfmt, whose convert_do makes the braces. + node scripts/fmt-if.mjs cmd/lava pkg/jsc pkg/runtime pkg/std/sqlite # `rm` isn't a Windows command and can't take the $(RUNSCRIPT) prefix (bash would treat # `rm` as a script), so invoke the shell explicitly: $(SHELL) is Git Bash on Windows and diff --git a/cmd/lava/buffer_reentrancy_test.odin b/cmd/lava/buffer_reentrancy_test.odin index ca365880..1008edd4 100644 --- a/cmd/lava/buffer_reentrancy_test.odin +++ b/cmd/lava/buffer_reentrancy_test.odin @@ -55,7 +55,11 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -65,6 +69,7 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { ctx, reentrancy_eval(ctx, "typeof ArrayBuffer.prototype.transfer === 'function'"), ) + if !has_transfer { // Older JSC without the detach primitive: nothing to exercise. return diff --git a/cmd/lava/dns_alloc_test.odin b/cmd/lava/dns_alloc_test.odin index ac8c4efa..b78bffcd 100644 --- a/cmd/lava/dns_alloc_test.odin +++ b/cmd/lava/dns_alloc_test.odin @@ -83,11 +83,15 @@ watched_allocator_proc :: proc( mem.Allocator_Error, ) { w := cast(^Watched_Allocator)data + if mode == .Alloc || mode == .Alloc_Non_Zeroed { for p in WATCHED_PROCS { - if loc.procedure == p do sync.atomic_add(&w.hits, 1) + if loc.procedure == p { + sync.atomic_add(&w.hits, 1) + } } } + return w.backing.procedure(w.backing.data, mode, size, alignment, old_memory, old_size, loc) } diff --git a/cmd/lava/errors_test.odin b/cmd/lava/errors_test.odin index 4f7cb795..77475bd2 100644 --- a/cmd/lava/errors_test.odin +++ b/cmd/lava/errors_test.odin @@ -23,10 +23,12 @@ node_error_factory :: proc(t: ^testing.T) { gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -81,7 +83,11 @@ node_error_received_types :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -108,13 +114,18 @@ node_error_received_types :: proc(t: ^testing.T) { for c in cases { val := eval_value(ctx, c.expr) e := lava.err_invalid_arg_type(ctx, "x", "string", val) + if !testing.expectf(t, jsc.JSValueIsObject(ctx, e), "%s: error must be an object", c.expr) { continue } + msg, allocated := lava.value_to_string(ctx, lava.get_named(ctx, cast(jsc.JSObjectRef)e, "message")) want := fmt.tprintf("The \"x\" argument must be of type string. Received %s", c.want) testing.expectf(t, msg == want, "%s: got %q want %q", c.expr, msg, want) - if allocated do delete(msg) + + if allocated { + delete(msg) + } } } @@ -131,7 +142,11 @@ expect_error_shape :: proc( want_name, want_message, want_code: string, ) { testing.expect(t, jsc.JSValueIsObject(ctx, err), "error value must be an object") - if !jsc.JSValueIsObject(ctx, err) do return + + if !jsc.JSValueIsObject(ctx, err) { + return + } + obj := cast(jsc.JSObjectRef)err global := jsc.JSContextGetGlobalObject(ctx) @@ -143,6 +158,7 @@ expect_error_shape :: proc( check_string_prop(t, ctx, obj, "message", want_message) code_v := lava.get_named(ctx, obj, "code") + if want_code == "" { testing.expect(t, jsc.JSValueIsUndefined(ctx, code_v), "plain error should have no code") } else { @@ -154,19 +170,29 @@ expect_error_shape :: proc( check_string_prop :: proc(t: ^testing.T, ctx: jsc.JSContextRef, obj: jsc.JSObjectRef, prop, want: string) { v := lava.get_named(ctx, obj, prop) got, allocated := lava.value_to_string(ctx, v) - defer if allocated do delete(got) + defer if allocated { + delete(got) + } testing.expectf(t, got == want, "%s: got %q want %q", prop, got, want) } @(private = "file") eval_truthy :: proc(ctx: jsc.JSContextRef, expr: string) -> bool { c_expr, err := strings.clone_to_cstring(expr, context.temp_allocator) - if err != nil do return false + + if err != nil { + return false + } + src := jsc.JSStringCreateWithUTF8CString(c_expr) defer jsc.JSStringRelease(src) exc: jsc.JSValueRef v := jsc.JSEvaluateScript(ctx, src, nil, nil, 1, &exc) - if exc != nil || v == nil do return false + + if exc != nil || v == nil { + return false + } + return jsc.JSValueToBoolean(ctx, v) } @@ -175,11 +201,19 @@ eval_truthy :: proc(ctx: jsc.JSContextRef, expr: string) -> bool { @(private = "file") eval_value :: proc(ctx: jsc.JSContextRef, expr: string) -> jsc.JSValueRef { c_expr, err := strings.clone_to_cstring(expr, context.temp_allocator) - if err != nil do return jsc.JSValueMakeUndefined(ctx) + + if err != nil { + return jsc.JSValueMakeUndefined(ctx) + } + src := jsc.JSStringCreateWithUTF8CString(c_expr) defer jsc.JSStringRelease(src) exc: jsc.JSValueRef v := jsc.JSEvaluateScript(ctx, src, nil, nil, 1, &exc) - if exc != nil || v == nil do return jsc.JSValueMakeUndefined(ctx) + + if exc != nil || v == nil { + return jsc.JSValueMakeUndefined(ctx) + } + return v } diff --git a/cmd/lava/fetch_url_test.odin b/cmd/lava/fetch_url_test.odin index b0b617d2..707a401b 100644 --- a/cmd/lava/fetch_url_test.odin +++ b/cmd/lava/fetch_url_test.odin @@ -43,7 +43,11 @@ parse_http_url_cases :: proc(t: ^testing.T) { for c in cases { host, port, path, scheme, ok := lava_runtime.parse_http_url(c.url) testing.expectf(t, ok == c.ok, "%s: ok=%v want %v", c.url, ok, c.ok) - if !c.ok do continue + + if !c.ok { + continue + } + testing.expectf(t, host == c.host, "%s: host=%q want %q", c.url, host, c.host) testing.expectf(t, port == c.port, "%s: port=%d want %d", c.url, port, c.port) testing.expectf(t, path == c.path, "%s: path=%q want %q", c.url, path, c.path) @@ -78,7 +82,11 @@ fetch_parse_chunk_size_cases :: proc(t: ^testing.T) { for c in cases { size, ok := lava_runtime.fetch_parse_chunk_size(c.text) testing.expectf(t, ok == c.ok, "%q: ok=%v want %v", c.text, ok, c.ok) - if !c.ok do continue + + if !c.ok { + continue + } + testing.expectf(t, size == c.size, "%q: size=%d want %d", c.text, size, c.size) } } diff --git a/cmd/lava/fs_write_payload_test.odin b/cmd/lava/fs_write_payload_test.odin index eae0ea4b..b5e0f808 100644 --- a/cmd/lava/fs_write_payload_test.odin +++ b/cmd/lava/fs_write_payload_test.odin @@ -47,7 +47,11 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -57,7 +61,10 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. ctx, payload_eval(ctx, "new ArrayBuffer(8, { maxByteLength: 8 }).resizable === true"), ) - if !resizable do return + + if !resizable { + return + } // A genuine DataView over a 4096-byte resizable buffer, carrying an own byteOffset // getter that shrinks the backing to 8 bytes and an own byteLength that keeps diff --git a/cmd/lava/global_surface_test.odin b/cmd/lava/global_surface_test.odin index f3104d72..ff2a50c0 100644 --- a/cmd/lava/global_surface_test.odin +++ b/cmd/lava/global_surface_test.odin @@ -323,10 +323,12 @@ surface_events_compiles :: proc(t: ^testing.T, surface: lava.Global_Surface) -> gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx diff --git a/cmd/lava/host_native_alloc_test.odin b/cmd/lava/host_native_alloc_test.odin index 676335c0..dd0c3fc4 100644 --- a/cmd/lava/host_native_alloc_test.odin +++ b/cmd/lava/host_native_alloc_test.odin @@ -86,7 +86,9 @@ host_native_tables_are_not_charged_to_the_eval_allocator :: proc(t: ^testing.T) stray := 0 for _, entry in track.allocation_map { - if strings.contains(entry.location.file_path, "host_natives.odin") do stray += 1 + if strings.contains(entry.location.file_path, "host_natives.odin") { + stray += 1 + } } testing.expectf( t, diff --git a/cmd/lava/host_native_failclosed_test.odin b/cmd/lava/host_native_failclosed_test.odin index 8ab74ea7..e9439659 100644 --- a/cmd/lava/host_native_failclosed_test.odin +++ b/cmd/lava/host_native_failclosed_test.odin @@ -35,12 +35,18 @@ import lava "lava:pkg/runtime" host_native_dispatch_miss_fails_closed :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) // Without the private-ABI path nothing is registered, so there is no miss to // observe and every assertion below would pass vacuously. - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) diff --git a/cmd/lava/host_native_registry_test.odin b/cmd/lava/host_native_registry_test.odin index 41b9fdf6..ab380636 100644 --- a/cmd/lava/host_native_registry_test.odin +++ b/cmd/lava/host_native_registry_test.odin @@ -47,22 +47,35 @@ other_cb :: proc "c" ( eval_text :: proc(ctx: jsc.JSContextRef, source: string) -> (string, bool) { c_src, err := strings.clone_to_cstring(source, context.temp_allocator) - if err != nil do return "", false + + if err != nil { + return "", false + } + js_src := jsc.JSStringCreateWithUTF8CString(c_src) defer jsc.JSStringRelease(js_src) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, js_src, nil, nil, 1, &exception) - if exception != nil || value == nil do return "", false + + if exception != nil || value == nil { + return "", false + } + // jsc_value_to_string_or_default hands back an OWNED context.allocator buffer. // The test runner installs a per-test tracking allocator and reports whatever is // still live when the test ends, so a helper that keeps it would print a leak on // every assertion here and bury a real one in the code under test. owned, got := lava.jsc_value_to_string_or_default(ctx, value) - if !got do return "", true // empty string: nothing was allocated + + if !got {return "", true} // empty string: nothing was allocated defer delete(owned) copied, clone_err := strings.clone(owned, context.temp_allocator) - if clone_err != nil do return "", false + + if clone_err != nil { + return "", false + } + return copied, true } @@ -77,10 +90,12 @@ Context :: struct { make_context :: proc() -> (Context, bool) { class := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(class) + if gctx == nil { jsc.JSClassRelease(class) return {}, false } + return Context{class = class, gctx = gctx, ctx = cast(jsc.JSContextRef)gctx}, true } @@ -93,7 +108,10 @@ destroy_context :: proc(c: Context) { // this file asserts on it rather than skipping quietly: a silently vacuous // regression test is the failure mode this whole area keeps hitting. host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { - if jsc.host_calls_active(ctx) do return true + if jsc.host_calls_active(ctx) { + return true + } + testing.expect(t, false, "private-ABI host-call path inactive — this test cannot observe what it pins") return false } @@ -106,15 +124,25 @@ host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { a, a_ok := make_context() testing.expect(t, a_ok, "could not create the first JSC global context") - if !a_ok do return + + if !a_ok { + return + } + defer destroy_context(a) b, b_ok := make_context() testing.expect(t, b_ok, "could not create the second JSC global context") - if !b_ok do return + + if !b_ok { + return + } + defer destroy_context(b) - if !host_path_active(t, a.ctx) do return + if !host_path_active(t, a.ctx) { + return + } state_a := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(a.ctx), cast(rawptr)state_a) @@ -149,10 +177,16 @@ host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) @@ -160,7 +194,10 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { first := lava.host_native_create(c.ctx, "probe", answer_cb) testing.expect(t, first != nil, "host_native_create returned nil on the host path") - if first == nil do return + + if first == nil { + return + } same := lava.host_native_create(c.ctx, "probe", answer_cb) testing.expect(t, same == first, "same (callback, name) minted a second function object") @@ -186,10 +223,16 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { host_native_construct_returns_call_result :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) @@ -208,10 +251,16 @@ host_native_construct_returns_call_result :: proc(t: ^testing.T) { host_native_create_declines_without_state :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } // Deliberately no JSObjectSetPrivate: this is the bare embedder context. fn := lava.host_native_create(c.ctx, "probe", answer_cb) @@ -276,10 +325,16 @@ failing_allocator :: proc() -> mem.Allocator { host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } // Built normally, so its maps and its own allocation come from the real // allocator; only the name-clone allocator is faulted. Overwriting the field @@ -316,7 +371,11 @@ host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { host_throw_reports_whether_it_raised :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) testing.expect( diff --git a/cmd/lava/jsc_predicates_test.odin b/cmd/lava/jsc_predicates_test.odin index ebf2e2a9..e15c63cf 100644 --- a/cmd/lava/jsc_predicates_test.odin +++ b/cmd/lava/jsc_predicates_test.odin @@ -27,7 +27,11 @@ jsc_value_predicates :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -126,11 +130,13 @@ predicate_probe_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { probe_called = true + if argument_count >= 4 { probe_false_is_false = jsc.JSValueToBoolean(ctx, arguments[0]) == false probe_undef_is_undefined = jsc.JSValueIsUndefined(ctx, arguments[1]) probe_obj_is_object = jsc.JSValueIsObject(ctx, arguments[2]) probe_num_not_object = !jsc.JSValueIsObject(ctx, arguments[3]) } + return jsc.JSValueMakeUndefined(ctx) } diff --git a/cmd/lava/lazy_builtins_test.odin b/cmd/lava/lazy_builtins_test.odin index 9b3849f1..316677a5 100644 --- a/cmd/lava/lazy_builtins_test.odin +++ b/cmd/lava/lazy_builtins_test.odin @@ -22,10 +22,12 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -41,7 +43,9 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { embedded := 0 for dir in lava.EMBEDDED_JS_DIRS { for file in dir.files { - if strings.has_suffix(file.name, ".js") do embedded += 1 + if strings.has_suffix(file.name, ".js") { + embedded += 1 + } } } @@ -91,7 +95,10 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { // ponytail: count-based for internal/ ids; record compiled ids on Runtime_State if // that coincidence ever matters. check-js-graph.test.mjs keeps this list current. for id in STATIC_EAGER { - if !strings.has_prefix(id, "node/") do continue + if !strings.has_prefix(id, "node/") { + continue + } + before := state.builtin_compiles src, _ := strings.concatenate({"require('node:", id[len("node/"):], "') != null"}, context.temp_allocator) testing.expectf(t, run_bool(ctx, src), "%s did not load", id) @@ -160,6 +167,10 @@ run_bool :: proc(ctx: jsc.JSContextRef, src: string) -> bool { defer jsc.JSStringRelease(script) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, script, nil, nil, 1, &exception) - if exception != nil do return false + + if exception != nil { + return false + } + return jsc.JSValueToBoolean(ctx, value) } diff --git a/cmd/lava/main.odin b/cmd/lava/main.odin index 8f4ca34b..19f5f330 100644 --- a/cmd/lava/main.odin +++ b/cmd/lava/main.odin @@ -74,10 +74,12 @@ run_command :: proc(args: []string) { // LAVA_WORKERS>1 runs the file on N shared-nothing worker loops (Slice 3a). Resolved fail-fast: // an invalid value or an unsupported platform exits non-zero rather than silently degrading. worker_count, count_ok, count_msg := lava_runtime.lava_resolve_worker_count() + if !count_ok { fmt.eprintfln("lava: %s", count_msg) os.exit(2) } + if worker_count > 1 { // args is [scriptPath, ...userArgs]; the supervisor reads the file once and runs N workers. os.exit(lava_runtime.lava_run_workers(args[0], worker_count, args[1:])) @@ -110,6 +112,7 @@ print_result :: proc(result: lava_runtime.Result, user_data: rawptr) { if len(result.message) > 0 { lava_runtime.process_write(os.stdout, result.message, "\n") } + return } diff --git a/cmd/lava/module_cache_rollback_test.odin b/cmd/lava/module_cache_rollback_test.odin index 0ea4e2ab..049d2de4 100644 --- a/cmd/lava/module_cache_rollback_test.odin +++ b/cmd/lava/module_cache_rollback_test.odin @@ -35,7 +35,11 @@ import lava "lava:pkg/runtime" module_cache_insert_rolls_back_on_grow_failure :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) track: mem.Tracking_Allocator diff --git a/cmd/lava/net_teardown_stress_test.odin b/cmd/lava/net_teardown_stress_test.odin index 3e9b30f5..3fd47d2e 100644 --- a/cmd/lava/net_teardown_stress_test.odin +++ b/cmd/lava/net_teardown_stress_test.odin @@ -19,10 +19,18 @@ RUNNER_THREADS :: #config(ODIN_TEST_THREADS, 0) @(private = "file") open_fd_count :: proc() -> int { handle, err := os.open("/proc/self/fd") - if err != nil do return -1 + + if err != nil { + return -1 + } + defer os.close(handle) infos, read_err := os.read_directory(handle, -1, context.temp_allocator) - if read_err != nil do return -1 + + if read_err != nil { + return -1 + } + return len(infos) } @@ -32,14 +40,22 @@ open_fd_count :: proc() -> int { @(private = "file") eval_fd_delta :: proc(src: string) -> (delta: int, ok: bool) { before := open_fd_count() - if before < 0 do return 0, false + + if before < 0 { + return 0, false + } + loop := eventloop.init() // eval CONSUMES the loop — it destroys it on every path, including this // top-level-throw one (see the OWNERSHIP note in runtime.odin). result := lava.eval(src, "", &loop, false) defer lava.result_destroy(&result) after := open_fd_count() - if after < 0 do return 0, false + + if after < 0 { + return 0, false + } + return after - before, result.status != .Ok } @@ -86,7 +102,10 @@ eval_teardown_with_live_net_connections :: proc(t: ^testing.T) { baseline, base_ok := eval_fd_delta("const net = require('node:net'); throw new Error('x');") testing.expect(t, base_ok, "the baseline script was supposed to throw at top level") - if !base_ok do return + + if !base_ok { + return + } withconns, conn_ok := eval_fd_delta( ` @@ -98,7 +117,10 @@ eval_teardown_with_live_net_connections :: proc(t: ^testing.T) { `, ) testing.expect(t, conn_ok, "the connect script was supposed to throw at top level") - if !conn_ok do return + + if !conn_ok { + return + } testing.expectf( t, diff --git a/cmd/lava/nocopy_bytes_alloc_test.odin b/cmd/lava/nocopy_bytes_alloc_test.odin index c0e01ebc..1edc7477 100644 --- a/cmd/lava/nocopy_bytes_alloc_test.odin +++ b/cmd/lava/nocopy_bytes_alloc_test.odin @@ -32,7 +32,9 @@ srv.listen(0, '127.0.0.1', () => { live_net_allocations :: proc(track: ^mem.Tracking_Allocator) -> int { n := 0 for _, entry in track.allocation_map { - if strings.has_suffix(entry.location.file_path, "net.odin") do n += 1 + if strings.has_suffix(entry.location.file_path, "net.odin") { + n += 1 + } } return n } diff --git a/cmd/lava/pool_cancel_hooks_test.odin b/cmd/lava/pool_cancel_hooks_test.odin index d906636b..b47450d5 100644 --- a/cmd/lava/pool_cancel_hooks_test.odin +++ b/cmd/lava/pool_cancel_hooks_test.odin @@ -53,15 +53,26 @@ Watch :: struct { watch_pre_run :: proc(user_data: rawptr) -> bool { w := cast(^Watch)user_data pool := &w.loop.pool - if len(pool.outstanding) != 1 do return false + + if len(pool.outstanding) != 1 { + return false + } + job := pool.outstanding[0] deadline := time.tick_add(time.tick_now(), 2 * time.Second) for { sync.lock(&pool.mutex) running := job.running sync.unlock(&pool.mutex) - if running do break - if time.tick_diff(time.tick_now(), deadline) <= 0 do return false + + if running { + break + } + + if time.tick_diff(time.tick_now(), deadline) <= 0 { + return false + } + time.sleep(time.Millisecond) } w.started = true @@ -82,9 +93,13 @@ watch_proc :: proc(w: ^Watch, slot: ^rawptr) { sync.atomic_store(&w.released, true) break } + time.sleep(time.Millisecond) } - if w.release != nil do w.release(w) + + if w.release != nil { + w.release(w) + } } // A reader blocked in open(O_RDONLY) gets through once a writer opens; the writer @@ -94,10 +109,12 @@ release_reader :: proc(w: ^Watch) { deadline := time.tick_add(time.tick_now(), 2 * time.Second) for time.tick_diff(time.tick_now(), deadline) > 0 { fd := posix.open(strings.clone_to_cstring(w.fifo, context.temp_allocator), {.WRONLY, .NONBLOCK}) + if fd >= 0 { posix.close(fd) return } + time.sleep(time.Millisecond) } } @@ -114,10 +131,12 @@ release_writer :: proc(w: ^Watch) { make_test_fifo :: proc(t: ^testing.T, name: string) -> string { path := fmt.aprintf("/tmp/lava-cancel-%d-%s.fifo", os.get_pid(), name) os.remove(path) + if posix.mkfifo(strings.clone_to_cstring(path, context.temp_allocator), {.IRUSR, .IWUSR}) != .OK { delete(path) testing.fail_now(t, "mkfifo failed") } + return path } @@ -129,8 +148,15 @@ run_watched :: proc(t: ^testing.T, w: ^Watch, src: string, what: string, loc := w.fifo_fd = -1 result := lava.eval(src, what, &loop, false, nil, watch_pre_run, w) lava.result_destroy(&result) - if w.th != nil do thread.destroy(w.th) - if w.fifo_fd >= 0 do posix.close(w.fifo_fd) + + if w.th != nil { + thread.destroy(w.th) + } + + if w.fifo_fd >= 0 { + posix.close(w.fifo_fd) + } + testing.expectf(t, w.started, "%s: no pool worker took the job", what, loc = loc) testing.expectf( t, @@ -186,9 +212,11 @@ fs_write_file_cancel_releases_the_callback_of_a_blocked_write :: proc(t: ^testin dns_lookup_cancel_releases_the_callback_of_a_hanging_lookup :: proc(t: ^testing.T) { @(static) conf_buf: [64]u8 conf := fmt.bprintf(conf_buf[:], "/tmp/lava-cancel-%d-resolv.conf", os.get_pid()) + if err := os.write_entire_file(conf, transmute([]u8)string("nameserver 127.77.0.1\n")); err != nil { testing.fail_now(t, "could not write the stub resolv.conf") } + saved := net.dns_configuration.resolv_conf net.dns_configuration.resolv_conf = conf defer { diff --git a/cmd/lava/repeated_eval_test.odin b/cmd/lava/repeated_eval_test.odin index e04319a0..3ae3531e 100644 --- a/cmd/lava/repeated_eval_test.odin +++ b/cmd/lava/repeated_eval_test.odin @@ -45,7 +45,9 @@ repeated_eval_stays_correct :: proc(t: ^testing.T) { // on unfixed code. Assert the precondition so a green run means something. { gctx := jsc.JSGlobalContextCreate(nil) - defer if gctx != nil do jsc.JSGlobalContextRelease(gctx) + defer if gctx != nil { + jsc.JSGlobalContextRelease(gctx) + } testing.expect( t, gctx != nil && jsc.host_calls_active(jsc.JSContextRef(gctx)), diff --git a/cmd/lava/stdio_fd_guard_test.odin b/cmd/lava/stdio_fd_guard_test.odin index 00a8334b..900c384c 100644 --- a/cmd/lava/stdio_fd_guard_test.odin +++ b/cmd/lava/stdio_fd_guard_test.odin @@ -34,7 +34,11 @@ stdio_write_sync_rejects_every_fd_but_1_and_2 :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx diff --git a/cmd/lava/timer_binding_alloc_test.odin b/cmd/lava/timer_binding_alloc_test.odin index 9d8bee2e..6ac9ea8b 100644 --- a/cmd/lava/timer_binding_alloc_test.odin +++ b/cmd/lava/timer_binding_alloc_test.odin @@ -40,9 +40,11 @@ binding_counter_proc :: proc( mem.Allocator_Error, ) { c := cast(^Binding_Counter)data + if (mode == .Alloc || mode == .Alloc_Non_Zeroed) && size == size_of(lava.JS_Callback) { c.hits += 1 } + return c.backing.procedure(c.backing.data, mode, size, alignment, old_memory, old_size, loc) } diff --git a/odinfmt.json b/odinfmt.json index 50a45192..7cc33a8a 100644 --- a/odinfmt.json +++ b/odinfmt.json @@ -4,5 +4,6 @@ "tabs": true, "tabs_width": 4, "sort_imports": true, - "newline_limit": 2 + "newline_limit": 2, + "convert_do": true } diff --git a/pkg/jsc/host_function.odin b/pkg/jsc/host_function.odin index 52efdd1a..18b409ff 100644 --- a/pkg/jsc/host_function.odin +++ b/pkg/jsc/host_function.odin @@ -114,7 +114,10 @@ when ODIN_OS == .Linux { // the fallback is silent by design, so this is the diagnostic switch. @(private = "file") debug_log :: proc(msg: string) { - if len(os.get_env("LAVA_HOSTFN_DEBUG", context.temp_allocator)) == 0 do return + if len(os.get_env("LAVA_HOSTFN_DEBUG", context.temp_allocator)) == 0 { + return + } + os.write_string(os.stderr, msg) os.write_string(os.stderr, "\n") } @@ -125,27 +128,42 @@ when ODIN_OS == .Linux { // Guard the frame reads: if the layout assumption were wrong, the count // almost certainly won't be 3, and we bail before touching "arguments". argc := u32(cf[CALL_FRAME_ARGC_SLOT] & 0xFFFFFFFF) + if argc == 3 && rawptr(uintptr(cf[CALL_FRAME_CALLEE_SLOT])) == g_probe_callee { a0 := JSValueRef(uintptr(cf[CALL_FRAME_FIRST_ARG_SLOT])) a1 := JSValueRef(uintptr(cf[CALL_FRAME_FIRST_ARG_SLOT + 1])) + if JSValueIsNumber(ctx, a0) && JSValueIsString(ctx, a1) && JSValueToNumber(ctx, a0, nil) == 42 { s := JSValueToStringCopy(ctx, a1, nil) + if s != nil { equal := JSStringIsEqualToUTF8CString(s, "ab") JSStringRelease(s) - if equal do g_probe_seen = true + + if equal { + g_probe_seen = true + } } } } + return transmute(i64)JSValueMakeNumber(ctx, 7) } @(private = "file") create_raw :: proc(ctx: JSContextRef, name: string, fn: Host_Function_Proc, arity: int) -> JSObjectRef { impl, name_ok := wtf_string_impl_from_ascii(name) - if !name_ok do return nil + + if !name_ok { + return nil + } + vm := JSContextGetGroup(ctx) - if vm == nil do return nil + + if vm == nil { + return nil + } + holder: rawptr g_host_lock_ctor(&holder, rawptr(ctx)) // The same fn doubles as the constructor slot: our natives are never @@ -180,7 +198,9 @@ when ODIN_OS == .Linux { // not cost every later native on that thread its host-call path. @(private = "file") ensure_host :: proc(ctx: JSContextRef) { - if g_host_checked do return + if g_host_checked { + return + } // TEST-ONLY switch, same shape and purpose as net.odin's // LAVA_NET_FORCE_READINESS: force the C-API fallback so CI can exercise the @@ -204,11 +224,13 @@ when ODIN_OS == .Linux { pl := host_dlsym(nil, "_ZN3JSC12JSLockHolderC1EPNS_14JSGlobalObjectE") pd := host_dlsym(nil, "_ZN3JSC12JSLockHolderD1Ev") pt := host_dlsym(nil, "_ZN3JSC2VM14throwExceptionEPNS_14JSGlobalObjectENS_7JSValueE") + if pc == nil || pl == nil || pd == nil || pt == nil { debug_log("hostfn: dlsym miss") g_host_checked = true // definitive: this JSC does not export the path return } + g_host_create = transmute(Create_Host_Fn_Proc)pc g_host_lock_ctor = transmute(Lock_Ctor_Proc)pl g_host_lock_dtor = transmute(Lock_Dtor_Proc)pd @@ -227,6 +249,7 @@ when ODIN_OS == .Linux { } fn := create_raw(ctx, "__lava_hostcall_probe", host_probe, 2) + if fn == nil { // Two distinct causes, only one transient. create_raw builds its name // through the private string bridge; if THAT probe latched off (missing @@ -237,6 +260,7 @@ when ODIN_OS == .Linux { g_host_checked = true return } + // Otherwise a WTF string-impl or GC-cell allocation failed. Nothing about // the ABI was disproved, so do NOT latch — this call falls back, the next // injection tries again. Neither arm here is pinnable by an in-repo test @@ -253,14 +277,17 @@ when ODIN_OS == .Linux { g_probe_callee = rawptr(fn) g_probe_seen = false res := JSObjectCallAsFunction(ctx, fn, nil, 2, &args[0], nil) + if !g_probe_seen || res == nil { debug_log("hostfn: probe not seen / res nil") return } + if !JSValueIsNumber(ctx, res) || JSValueToNumber(ctx, res, nil) != 7 { debug_log("hostfn: bad probe result") return } + debug_log("hostfn: ACTIVE") g_host_ok = true } @@ -286,7 +313,11 @@ when ODIN_OS == .Linux { ok: bool, ) { ensure_host(ctx) - if !g_host_ok do return nil, false + + if !g_host_ok { + return nil, false + } + function = create_raw(ctx, name, fn, arity) return function, function != nil } @@ -318,9 +349,16 @@ when ODIN_OS == .Linux { // nil-value/nil-vm cases, where refusing to claim a raise is what keeps the // caller from returning the Error as a value. host_throw :: proc "contextless" (ctx: JSContextRef, value: JSValueRef) -> bool { - if !g_host_ok || value == nil do return false + if !g_host_ok || value == nil { + return false + } + vm := JSContextGetGroup(ctx) - if vm == nil do return false + + if vm == nil { + return false + } + g_vm_throw(vm, rawptr(ctx), transmute(u64)value) return true } diff --git a/pkg/jsc/private_string.odin b/pkg/jsc/private_string.odin index 1ae91bfe..d6928786 100644 --- a/pkg/jsc/private_string.odin +++ b/pkg/jsc/private_string.odin @@ -103,13 +103,19 @@ when ODIN_OS == .Linux { @(private = "file") ensure_resolved :: proc() { - if g_checked do return + if g_checked { + return + } + g_checked = true p8 := dlsym(nil, "_ZN3WTF10StringImpl19createUninitializedEmRSt4spanIhLm18446744073709551615EE") p16 := dlsym(nil, "_ZN3WTF10StringImpl19createUninitializedEmRSt4spanIDsLm18446744073709551615EE") pt := dlsym(nil, "_ZN14OpaqueJSString9tryCreateEON3WTF6StringE") - if p8 == nil || p16 == nil || pt == nil do return + + if p8 == nil || p16 == nil || pt == nil { + return + } g_create8 = transmute(Create_Uninit8_Proc)p8 g_create16 = transmute(Create_Uninit16_Proc)p16 @@ -119,7 +125,10 @@ when ODIN_OS == .Linux { // (ensure_resolved re-entry is cut off by g_checked above). g_ok = true g_ok = self_test() - if g_ok do g_read_ok = probe_read_layout() + + if g_ok { + g_read_ok = probe_read_layout() + } } // string_bridge_latched_off reports whether ensure_resolved reached a @@ -140,24 +149,47 @@ when ODIN_OS == .Linux { @(private = "file") self_test :: proc() -> bool { str8, d8, ok8 := string_alloc8(3) - if !ok8 do return false + + if !ok8 { + return false + } + d8[0] = 'a' d8[1] = 'b' d8[2] = 'c' defer JSStringRelease(str8) - if JSStringGetLength(str8) != 3 do return false + + if JSStringGetLength(str8) != 3 { + return false + } + buf: [8]byte n := JSStringGetUTF8CString(str8, &buf[0], len(buf)) - if n != 4 || buf[0] != 'a' || buf[1] != 'b' || buf[2] != 'c' do return false + + if n != 4 || buf[0] != 'a' || buf[1] != 'b' || buf[2] != 'c' { + return false + } str16, d16, ok16 := string_alloc16(2) - if !ok16 do return false + + if !ok16 { + return false + } + defer JSStringRelease(str16) d16[0] = 0x4F60 d16[1] = 0x597D - if JSStringGetLength(str16) != 2 do return false + + if JSStringGetLength(str16) != 2 { + return false + } + chars := JSStringGetCharactersPtr(str16) - if chars == nil || chars[0] != 0x4F60 || chars[1] != 0x597D do return false + + if chars == nil || chars[0] != 0x4F60 || chars[1] != 0x597D { + return false + } + return true } @@ -172,38 +204,70 @@ when ODIN_OS == .Linux { impl8: rawptr span8: Wtf_Span8 g_create8(&impl8, 3, &span8) - if impl8 == nil || span8.data == nil do return false + + if impl8 == nil || span8.data == nil { + return false + } + span8.data[0] = 'x' span8.data[1] = 'y' span8.data[2] = 'z' s8: rawptr moved8 := impl8 g_try_create(&s8, &moved8) - if s8 == nil do return false + + if s8 == nil { + return false + } + defer JSStringRelease(JSStringRef(s8)) impl16: rawptr span16: Wtf_Span16 g_create16(&impl16, 3, &span16) - if impl16 == nil || span16.data == nil do return false + + if impl16 == nil || span16.data == nil { + return false + } + span16.data[0] = 0x4F60 span16.data[1] = 0x597D span16.data[2] = 0x0021 s16: rawptr moved16 := impl16 g_try_create(&s16, &moved16) - if s16 == nil do return false + + if s16 == nil { + return false + } + defer JSStringRelease(JSStringRef(s16)) // StringImplShape: length and storage pointer where expected, on both widths. - if (^u32)(uintptr(impl8) + IMPL_LENGTH_OFFSET)^ != 3 do return false - if (^u32)(uintptr(impl16) + IMPL_LENGTH_OFFSET)^ != 3 do return false - if (^rawptr)(uintptr(impl8) + IMPL_DATA_OFFSET)^ != rawptr(span8.data) do return false - if (^rawptr)(uintptr(impl16) + IMPL_DATA_OFFSET)^ != rawptr(span16.data) do return false + if (^u32)(uintptr(impl8) + IMPL_LENGTH_OFFSET)^ != 3 { + return false + } + + if (^u32)(uintptr(impl16) + IMPL_LENGTH_OFFSET)^ != 3 { + return false + } + + if (^rawptr)(uintptr(impl8) + IMPL_DATA_OFFSET)^ != rawptr(span8.data) { + return false + } + + if (^rawptr)(uintptr(impl16) + IMPL_DATA_OFFSET)^ != rawptr(span16.data) { + return false + } // OpaqueJSString holds its String (one StringImpl*) right after the refcount. - if (^rawptr)(uintptr(s8) + OPAQUE_STRING_IMPL_OFFSET)^ != impl8 do return false - if (^rawptr)(uintptr(s16) + OPAQUE_STRING_IMPL_OFFSET)^ != impl16 do return false + if (^rawptr)(uintptr(s8) + OPAQUE_STRING_IMPL_OFFSET)^ != impl8 { + return false + } + + if (^rawptr)(uintptr(s16) + OPAQUE_STRING_IMPL_OFFSET)^ != impl16 { + return false + } // The two impls were created identically except for storage width, and // neither has a cached hash yet, so the flag words must differ in exactly @@ -216,7 +280,8 @@ when ODIN_OS == .Linux { f8 := (^u32)(uintptr(impl8) + IMPL_FLAGS_OFFSET)^ f16 := (^u32)(uintptr(impl16) + IMPL_FLAGS_OFFSET)^ diff := f8 ~ f16 - if diff == 0 || (diff & (diff - 1)) != 0 do return false // require exactly one bit + + if diff == 0 || (diff & (diff - 1)) != 0 {return false} // require exactly one bit g_flag_mask = diff g_flag_val8 = f8 & diff @@ -229,12 +294,18 @@ when ODIN_OS == .Linux { pub8 := JSStringCreateWithUTF8CString("abc") defer JSStringRelease(pub8) d, ok := string_chars8(pub8) - if !ok || len(d) != 3 || d[0] != 'a' || d[1] != 'b' || d[2] != 'c' do return false + + if !ok || len(d) != 3 || d[0] != 'a' || d[1] != 'b' || d[2] != 'c' { + return false + } wide := [1]JSChar{0x4F60} pub16 := JSStringCreateWithCharacters(&wide[0], 1) defer JSStringRelease(pub16) - if _, ok16 := string_chars8(pub16); ok16 do return false + + if _, ok16 := string_chars8(pub16); ok16 { + return false + } return true } @@ -260,17 +331,25 @@ when ODIN_OS == .Linux { @(private = "file") ensure_value_reads :: proc(ctx: JSContextRef) { - if g_val_checked do return + if g_val_checked { + return + } + // Need StringImpl layout from ensure_resolved → probe_read_layout first. ensure_resolved() + if !g_read_ok { // Permanent: write path ABI failed. Soft: not yet resolved — retry later. - if g_checked do g_val_checked = true + if g_checked { + g_val_checked = true + } + return } str8, d8, ok8 := string_alloc8(3) - if !ok8 do return // transient; leave g_val_checked false + + if !ok8 {return} // transient; leave g_val_checked false defer JSStringRelease(str8) d8[0] = 'q' d8[1] = 'r' @@ -282,10 +361,12 @@ when ODIN_OS == .Linux { // unrooted cell cannot be collected under us.) v := JSValueMakeString(ctx, str8) p := uintptr(v) + if p == 0 || (u64(p) & VALUE_NOT_CELL_MASK) != 0 { g_val_checked = true // layout/value shape wrong return } + ty := (^u8)(p + JSCELL_TYPE_OFFSET)^ off: uintptr found := false @@ -296,6 +377,7 @@ when ODIN_OS == .Linux { break } } + if !found { g_val_checked = true return @@ -303,17 +385,20 @@ when ODIN_OS == .Linux { // Cross-check on a 16-bit string. str16, d16, ok16 := string_alloc16(2) - if !ok16 do return // transient + + if !ok16 {return} // transient defer JSStringRelease(str16) d16[0] = 0x4F60 d16[1] = 0x0021 impl16 := (^rawptr)(uintptr(str16) + OPAQUE_STRING_IMPL_OFFSET)^ v16 := JSValueMakeString(ctx, str16) p16 := uintptr(v16) + if p16 == 0 || (u64(p16) & VALUE_NOT_CELL_MASK) != 0 { g_val_checked = true return } + if (^u8)(p16 + JSCELL_TYPE_OFFSET)^ != ty || (^rawptr)(p16 + off)^ != impl16 { g_val_checked = true return @@ -330,12 +415,24 @@ when ODIN_OS == .Linux { @(private = "file") value_string_impl :: proc(ctx: JSContextRef, value: JSValueRef) -> (impl: uintptr, ok: bool) { ensure_value_reads(ctx) - if !g_val_ok do return 0, false + + if !g_val_ok { + return 0, false + } + p := uintptr(value) - if p == 0 || (u64(p) & VALUE_NOT_CELL_MASK) != 0 do return 0, false - if (^u8)(p + JSCELL_TYPE_OFFSET)^ != g_string_type do return 0, false + + if p == 0 || (u64(p) & VALUE_NOT_CELL_MASK) != 0 { + return 0, false + } + + if (^u8)(p + JSCELL_TYPE_OFFSET)^ != g_string_type { + return 0, false + } + w := (^uintptr)(p + g_fiber_off)^ - if w == 0 || (w & 7) != 0 do return 0, false // rope or empty fiber + + if w == 0 || (w & 7) != 0 {return 0, false} // rope or empty fiber return w, true } @@ -345,24 +442,45 @@ when ODIN_OS == .Linux { // for the duration of the native call) and must not be written. value_chars8 :: proc(ctx: JSContextRef, value: JSValueRef) -> (data: []byte, ok: bool) { impl, iok := value_string_impl(ctx, value) - if !iok do return nil, false + + if !iok { + return nil, false + } + flags := (^u32)(impl + IMPL_FLAGS_OFFSET)^ - if flags & g_flag_mask != g_flag_val8 do return nil, false + + if flags & g_flag_mask != g_flag_val8 { + return nil, false + } + length := int((^u32)(impl + IMPL_LENGTH_OFFSET)^) chars := (^[^]byte)(impl + IMPL_DATA_OFFSET)^ - if chars == nil do return nil, false + + if chars == nil { + return nil, false + } + return chars[:length], true } // value_chars16 is value_chars8 for 16-bit storage (UTF-16 code units). value_chars16 :: proc(ctx: JSContextRef, value: JSValueRef) -> (data: []JSChar, ok: bool) { impl, iok := value_string_impl(ctx, value) - if !iok do return nil, false + + if !iok { + return nil, false + } + flags := (^u32)(impl + IMPL_FLAGS_OFFSET)^ - if flags & g_flag_mask == g_flag_val8 do return nil, false // 8-bit + + if flags & g_flag_mask == g_flag_val8 {return nil, false} // 8-bit length := int((^u32)(impl + IMPL_LENGTH_OFFSET)^) chars := (^[^]JSChar)(impl + IMPL_DATA_OFFSET)^ - if chars == nil do return nil, false + + if chars == nil { + return nil, false + } + return chars[:length], true } @@ -372,14 +490,29 @@ when ODIN_OS == .Linux { // the string's storage: it is valid only while the JSStringRef is alive, and // the caller must not write through it. string_chars8 :: proc(str: JSStringRef) -> (data: []byte, ok: bool) { - if !g_read_ok || str == nil do return nil, false + if !g_read_ok || str == nil { + return nil, false + } + impl := (^rawptr)(uintptr(str) + OPAQUE_STRING_IMPL_OFFSET)^ - if impl == nil do return nil, false + + if impl == nil { + return nil, false + } + flags := (^u32)(uintptr(impl) + IMPL_FLAGS_OFFSET)^ - if flags & g_flag_mask != g_flag_val8 do return nil, false + + if flags & g_flag_mask != g_flag_val8 { + return nil, false + } + length := int((^u32)(uintptr(impl) + IMPL_LENGTH_OFFSET)^) chars := (^[^]byte)(uintptr(impl) + IMPL_DATA_OFFSET)^ - if chars == nil do return nil, false + + if chars == nil { + return nil, false + } + return chars[:length], true } @@ -391,10 +524,18 @@ when ODIN_OS == .Linux { @(private) wtf_string_impl_from_ascii :: proc(s: string) -> (impl: rawptr, ok: bool) { ensure_resolved() - if !g_ok || len(s) == 0 do return nil, false + + if !g_ok || len(s) == 0 { + return nil, false + } + span: Wtf_Span8 g_create8(&impl, c.size_t(len(s)), &span) - if impl == nil || span.data == nil || int(span.size) != len(s) do return nil, false + + if impl == nil || span.data == nil || int(span.size) != len(s) { + return nil, false + } + copy(span.data[:len(s)], s) return impl, true } @@ -405,11 +546,15 @@ when ODIN_OS == .Linux { // g_ok is latched false only by ensure_resolved's self-test (ABI mismatch). string_alloc8 :: proc(n: int) -> (str: JSStringRef, data: []byte, ok: bool) { ensure_resolved() - if !g_ok || n <= 0 do return nil, nil, false + + if !g_ok || n <= 0 { + return nil, nil, false + } impl: rawptr span: Wtf_Span8 g_create8(&impl, c.size_t(n), &span) + if impl == nil || span.data == nil || int(span.size) != n { return nil, nil, false } @@ -417,10 +562,12 @@ when ODIN_OS == .Linux { s: rawptr moved := impl g_try_create(&s, &moved) + if s == nil { // Orphaned StringImpl (no public deref); rare. Fail this call only. return nil, nil, false } + return JSStringRef(s), span.data[:n], true } @@ -428,11 +575,15 @@ when ODIN_OS == .Linux { // uninitialized storage; units are UTF-16 code units, surrogates preserved. string_alloc16 :: proc(n: int) -> (str: JSStringRef, data: []JSChar, ok: bool) { ensure_resolved() - if !g_ok || n <= 0 do return nil, nil, false + + if !g_ok || n <= 0 { + return nil, nil, false + } impl: rawptr span: Wtf_Span16 g_create16(&impl, c.size_t(n), &span) + if impl == nil || span.data == nil || int(span.size) != n { return nil, nil, false } @@ -440,9 +591,11 @@ when ODIN_OS == .Linux { s: rawptr moved := impl g_try_create(&s, &moved) + if s == nil { return nil, nil, false } + return JSStringRef(s), span.data[:n], true } } else { diff --git a/pkg/jsc/private_value.odin b/pkg/jsc/private_value.odin index c37cc5e0..a8359c4a 100644 --- a/pkg/jsc/private_value.odin +++ b/pkg/jsc/private_value.odin @@ -23,7 +23,10 @@ when ODIN_OS == .Linux { @(private = "file") ensure_int32 :: proc(ctx: JSContextRef) { - if g_i32_checked do return + if g_i32_checked { + return + } + g_i32_checked = true enc :: proc(ctx: JSContextRef, v: i32) -> u64 { return transmute(u64)JSValueMakeNumber(ctx, f64(v)) @@ -32,10 +35,17 @@ when ODIN_OS == .Linux { t7 := enc(ctx, 7) ~ u64(u32(7)) tbig := enc(ctx, 1234567) ~ u64(u32(1234567)) tneg := enc(ctx, -3) ~ u64(u32(transmute(u32)i32(-3))) - if t5 != t7 || t5 != tbig || t5 != tneg do return + + if t5 != t7 || t5 != tbig || t5 != tneg { + return + } + // The tag must live entirely in the high 32 bits, or the decode below // could not separate it from the payload. - if t5 & 0xFFFFFFFF != 0 do return + if t5 & 0xFFFFFFFF != 0 { + return + } + g_i32_tag = t5 g_i32_ok = true } @@ -44,9 +54,17 @@ when ODIN_OS == .Linux { // non-numbers (fall back to JSValueToNumber). value_int32 :: proc(ctx: JSContextRef, value: JSValueRef) -> (v: i32, ok: bool) { ensure_int32(ctx) - if !g_i32_ok do return 0, false + + if !g_i32_ok { + return 0, false + } + bits := transmute(u64)value - if bits & 0xFFFFFFFF_00000000 != g_i32_tag do return 0, false + + if bits & 0xFFFFFFFF_00000000 != g_i32_tag { + return 0, false + } + return i32(u32(bits & 0xFFFFFFFF)), true } @@ -54,7 +72,11 @@ when ODIN_OS == .Linux { // unavailable (fall back to JSValueMakeNumber). make_int32 :: proc(ctx: JSContextRef, v: i32) -> (value: JSValueRef, ok: bool) { ensure_int32(ctx) - if !g_i32_ok do return nil, false + + if !g_i32_ok { + return nil, false + } + return transmute(JSValueRef)(g_i32_tag | u64(transmute(u32)v)), true } } else { diff --git a/pkg/jsc/private_view.odin b/pkg/jsc/private_view.odin index 80b7d4b5..21b105a5 100644 --- a/pkg/jsc/private_view.odin +++ b/pkg/jsc/private_view.odin @@ -86,29 +86,46 @@ when ODIN_OS == .Linux { @(private = "file") ensure_view :: proc(ctx: JSContextRef) { - if g_view_checked do return + if g_view_checked { + return + } + // Soft failures (nil create) leave g_view_checked false so a later call // retries. Layout disagreements after successful allocates latch closed. a := JSObjectMakeTypedArrayWithBytesNoCopy(ctx, .Uint8Array, &g_probe_a[0], len(g_probe_a), nil, nil, nil) - if a == nil do return + + if a == nil { + return + } + JSValueProtect(ctx, JSValueRef(a)) defer JSValueUnprotect(ctx, JSValueRef(a)) b := JSObjectMakeTypedArrayWithBytesNoCopy(ctx, .Uint8Array, &g_probe_b[0], len(g_probe_b), nil, nil, nil) - if b == nil do return + + if b == nil { + return + } + JSValueProtect(ctx, JSValueRef(b)) defer JSValueUnprotect(ctx, JSValueRef(b)) cc := JSObjectMakeTypedArrayWithBytesNoCopy(ctx, .Uint8Array, &g_probe_c[0], len(g_probe_c), nil, nil, nil) - if cc == nil do return + + if cc == nil { + return + } + JSValueProtect(ctx, JSValueRef(cc)) defer JSValueUnprotect(ctx, JSValueRef(cc)) pa, pb, pc := uintptr(rawptr(a)), uintptr(rawptr(b)), uintptr(rawptr(cc)) ty := (^u8)(pa + JSCELL_TYPE_OFFSET)^ + if (^u8)(pb + JSCELL_TYPE_OFFSET)^ != ty || (^u8)(pc + JSCELL_TYPE_OFFSET)^ != ty { g_view_checked = true return } + vec_off: uintptr vec_found := false for cand: uintptr = 8; cand <= 120; cand += 8 { @@ -120,6 +137,7 @@ when ODIN_OS == .Linux { break } } + if !vec_found { g_view_checked = true return @@ -132,7 +150,10 @@ when ODIN_OS == .Linux { len_found := false len_u64 := false for cand: uintptr = 8; cand <= 120; cand += 8 { - if cand == vec_off do continue + if cand == vec_off { + continue + } + if (^u64)(pa + cand)^ == len(g_probe_a) && (^u64)(pb + cand)^ == len(g_probe_b) && (^u64)(pc + cand)^ == len(g_probe_c) { @@ -142,9 +163,13 @@ when ODIN_OS == .Linux { break } } + if !len_found { for cand: uintptr = 8; cand <= 124; cand += 4 { - if cand >= vec_off && cand < vec_off + 8 do continue + if cand >= vec_off && cand < vec_off + 8 { + continue + } + if (^u32)(pa + cand)^ == len(g_probe_a) && (^u32)(pb + cand)^ == len(g_probe_b) && (^u32)(pc + cand)^ == len(g_probe_c) { @@ -154,10 +179,12 @@ when ODIN_OS == .Linux { } } } + if !len_found { g_view_checked = true return } + // Disambiguate the width with a view at a NON-ZERO byteOffset. All three // probes above have byteOffset 0, so if m_length is really u32 with an // adjacent u32 byteOffset, a u64 read at len_off equals the length anyway @@ -170,33 +197,41 @@ when ODIN_OS == .Linux { OFF :: 16 LEN :: 32 ab := JSObjectMakeArrayBufferWithBytesNoCopy(ctx, &g_probe_d[0], len(g_probe_d), nil, nil, nil) - if ab == nil do return // soft + + if ab == nil {return} // soft JSValueProtect(ctx, JSValueRef(ab)) defer JSValueUnprotect(ctx, JSValueRef(ab)) global := JSContextGetGlobalObject(ctx) u8_name := JSStringCreateWithUTF8CString("Uint8Array") defer JSStringRelease(u8_name) u8_ctor := JSObjectGetProperty(ctx, global, u8_name, nil) + if u8_ctor == nil || !JSValueIsObject(ctx, u8_ctor) { g_view_checked = true return } + args := [3]JSValueRef{JSValueRef(ab), JSValueMakeNumber(ctx, f64(OFF)), JSValueMakeNumber(ctx, f64(LEN))} ov := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 3, &args[0], nil) - if ov == nil do return // soft + + if ov == nil {return} // soft JSValueProtect(ctx, JSValueRef(ov)) defer JSValueUnprotect(ctx, JSValueRef(ov)) pv := uintptr(rawptr(ov)) + if (^u8)(pv + JSCELL_TYPE_OFFSET)^ != ty { g_view_checked = true return } + // m_vector already includes byteOffset. if (^rawptr)(pv + vec_off)^ != rawptr(&g_probe_d[OFF]) { g_view_checked = true return } + read := len_u64 ? int((^u64)(pv + len_off)^) : int((^u32)(pv + len_off)^) + if read != LEN { // Wide read folded in byteOffset; the field is really u32. if len_u64 && int((^u32)(pv + len_off)^) == LEN { @@ -279,9 +314,11 @@ when ODIN_OS == .Linux { defer JSStringRelease(max_name) u8_ctor := JSObjectGetProperty(ctx, global, u8_name, nil) ab_ctor := JSObjectGetProperty(ctx, global, ab_name, nil) + if u8_ctor == nil || !JSValueIsObject(ctx, u8_ctor) || ab_ctor == nil || !JSValueIsObject(ctx, ab_ctor) { return 0, {}, .Mismatch } + // Rooted by the global object only while nobody reassigns it; protect. JSValueProtect(ctx, u8_ctor) defer JSValueUnprotect(ctx, u8_ctor) @@ -290,63 +327,106 @@ when ODIN_OS == .Linux { fast_args := [1]JSValueRef{JSValueMakeNumber(ctx, 4)} fast := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 1, &fast_args[0], nil) - if fast == nil do return 0, {}, .Soft + + if fast == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(fast)) defer JSValueUnprotect(ctx, JSValueRef(fast)) big_args := [1]JSValueRef{JSValueMakeNumber(ctx, 4096)} big := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 1, &big_args[0], nil) - if big == nil do return 0, {}, .Soft + + if big == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(big)) defer JSValueUnprotect(ctx, JSValueRef(big)) // The NoCopy offset view from ensure_view is gone by now; one more // ArrayBuffer-backed wasteful view stands in for it. ab := JSObjectMakeArrayBufferWithBytesNoCopy(ctx, &g_probe_d[0], len(g_probe_d), nil, nil, nil) - if ab == nil do return 0, {}, .Soft + + if ab == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(ab)) defer JSValueUnprotect(ctx, JSValueRef(ab)) wv_args := [1]JSValueRef{JSValueRef(ab)} wv := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 1, &wv_args[0], nil) - if wv == nil do return 0, {}, .Soft + + if wv == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(wv)) defer JSValueUnprotect(ctx, JSValueRef(wv)) opts := JSObjectMake(ctx, nil, nil) - if opts == nil do return 0, {}, .Soft + + if opts == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(opts)) defer JSValueUnprotect(ctx, JSValueRef(opts)) JSObjectSetProperty(ctx, opts, max_name, JSValueMakeNumber(ctx, 16), {}, nil) rab_args := [2]JSValueRef{JSValueMakeNumber(ctx, 8), JSValueRef(opts)} rab := JSObjectCallAsConstructor(ctx, JSObjectRef(ab_ctor), 2, &rab_args[0], nil) - if rab == nil do return 0, {}, .Soft + + if rab == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(rab)) defer JSValueUnprotect(ctx, JSValueRef(rab)) tracking_args := [1]JSValueRef{JSValueRef(rab)} tracking := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 1, &tracking_args[0], nil) - if tracking == nil do return 0, {}, .Soft + + if tracking == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(tracking)) defer JSValueUnprotect(ctx, JSValueRef(tracking)) fixed_args := [3]JSValueRef{JSValueRef(rab), JSValueMakeNumber(ctx, 0), JSValueMakeNumber(ctx, 4)} bounded := JSObjectCallAsConstructor(ctx, JSObjectRef(u8_ctor), 3, &fixed_args[0], nil) - if bounded == nil do return 0, {}, .Soft + + if bounded == nil { + return 0, {}, .Soft + } + JSValueProtect(ctx, JSValueRef(bounded)) defer JSValueUnprotect(ctx, JSValueRef(bounded)) pf, pg, pw := uintptr(rawptr(fast)), uintptr(rawptr(big)), uintptr(rawptr(wv)) pt, pr := uintptr(rawptr(tracking)), uintptr(rawptr(bounded)) for p in ([5]uintptr{pf, pg, pw, pt, pr}) { - if (^u8)(p + JSCELL_TYPE_OFFSET)^ != ty do return 0, {}, .Mismatch + if (^u8)(p + JSCELL_TYPE_OFFSET)^ != ty { + return 0, {}, .Mismatch + } } byte_at :: #force_inline proc(p, off: uintptr) -> u8 {return (^u8)(p + off)^} for cand := max(vec_off, len_off) + 8; cand <= 120; cand += 1 { w := byte_at(wasteful[0], cand) + if byte_at(wasteful[1], cand) != w || byte_at(wasteful[2], cand) != w || byte_at(pw, cand) != w { continue } + set := [3]u8{byte_at(pf, cand), byte_at(pg, cand), w} t, r := byte_at(pt, cand), byte_at(pr, cand) - if t == set[0] || t == set[1] || t == set[2] do continue - if r == set[0] || r == set[1] || r == set[2] do continue + + if t == set[0] || t == set[1] || t == set[2] { + continue + } + + if r == set[0] || r == set[1] || r == set[2] { + continue + } + return cand, set, .Found } return 0, {}, .Mismatch @@ -382,24 +462,44 @@ when ODIN_OS == .Linux { // of the native call. typed_array_bytes :: proc(ctx: JSContextRef, value: JSValueRef) -> (data: []byte, ok: bool) { ensure_view(ctx) - if !g_view_ok do return nil, false + + if !g_view_ok { + return nil, false + } + p := uintptr(value) - if p == 0 || (u64(p) & VALUE_NOT_CELL_MASK) != 0 do return nil, false - if (^u8)(p + JSCELL_TYPE_OFFSET)^ != g_view_type do return nil, false + + if p == 0 || (u64(p) & VALUE_NOT_CELL_MASK) != 0 { + return nil, false + } + + if (^u8)(p + JSCELL_TYPE_OFFSET)^ != g_view_type { + return nil, false + } + // A resizable- or growable-backed view: m_length is not its length. mode := (^u8)(p + g_mode_off)^ - if mode != g_mode_fixed[0] && mode != g_mode_fixed[1] && mode != g_mode_fixed[2] do return nil, false + + if mode != g_mode_fixed[0] && mode != g_mode_fixed[1] && mode != g_mode_fixed[2] { + return nil, false + } + vec := (^rawptr)(p + g_vec_off)^ n := g_len_u64 ? int((^u64)(p + g_len_off)^) : int((^u32)(p + g_len_off)^) + if vec == nil || n < 0 { // Detached (or zero-length wasteful) views have a null vector and a // zeroed length; report those as a valid empty view. return nil, n == 0 } + // Defense in depth against a mis-probed length field: a real Uint8Array // never exceeds MAX_VIEW_LENGTH, so anything larger means the read is // bogus — fall back to the C API rather than hand out a wild slice. - if n > MAX_VIEW_LENGTH do return nil, false + if n > MAX_VIEW_LENGTH { + return nil, false + } + return ([^]byte)(vec)[:n], true } } else { diff --git a/pkg/jsc/string_utf8.odin b/pkg/jsc/string_utf8.odin index 42b0b66a..ee01657e 100644 --- a/pkg/jsc/string_utf8.odin +++ b/pkg/jsc/string_utf8.odin @@ -9,6 +9,7 @@ utf16_js_utf8_byte_len :: proc "contextless" (chars: [^]JSChar, n: int) -> int { i := 0 for i < n { u := u32(chars[i]) + if u < 0x80 { total += 1 i += 1 @@ -19,12 +20,14 @@ utf16_js_utf8_byte_len :: proc "contextless" (chars: [^]JSChar, n: int) -> int { // High surrogate: pair with a following low, else U+FFFD (3 bytes). if i + 1 < n { lo := u32(chars[i + 1]) + if lo >= 0xDC00 && lo <= 0xDFFF { total += 4 // astral scalar i += 2 continue } } + total += 3 // unpaired → U+FFFD i += 1 } else if u >= 0xDC00 && u <= 0xDFFF { @@ -48,6 +51,7 @@ utf16_js_to_utf8_capped :: proc "contextless" (chars: [^]JSChar, n: int, out: [] for i < n { u := u32(chars[i]) need: int + // Pre-compute how many bytes this unit (or pair) wants. if u < 0x80 { need = 1 @@ -56,6 +60,7 @@ utf16_js_to_utf8_capped :: proc "contextless" (chars: [^]JSChar, n: int, out: [] } else if u >= 0xD800 && u <= 0xDBFF { if i + 1 < n { lo := u32(chars[i + 1]) + if lo >= 0xDC00 && lo <= 0xDFFF { need = 4 } else { @@ -69,7 +74,11 @@ utf16_js_to_utf8_capped :: proc "contextless" (chars: [^]JSChar, n: int, out: [] } else { need = 3 } - if o + need > cap do break + + if o + need > cap { + break + } + // Encode one scalar / replacement using the uncapped helper on a 4-byte window. // Advance i by the whole (paired) code point. if u < 0x80 { @@ -84,6 +93,7 @@ utf16_js_to_utf8_capped :: proc "contextless" (chars: [^]JSChar, n: int, out: [] } else if u >= 0xD800 && u <= 0xDBFF { if i + 1 < n { lo := u32(chars[i + 1]) + if lo >= 0xDC00 && lo <= 0xDFFF { cp := 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00) out[o] = byte(0xF0 | (cp >> 18)) @@ -95,6 +105,7 @@ utf16_js_to_utf8_capped :: proc "contextless" (chars: [^]JSChar, n: int, out: [] continue } } + out[o] = 0xEF out[o + 1] = 0xBF out[o + 2] = 0xBD diff --git a/pkg/runtime/buffer.odin b/pkg/runtime/buffer.odin index c9c1bba8..1dddb649 100644 --- a/pkg/runtime/buffer.odin +++ b/pkg/runtime/buffer.odin @@ -24,10 +24,15 @@ bytes_all_ascii :: proc(data: []byte) -> bool { i := 0 for ; i + 8 <= len(data); i += 8 { chunk := intrinsics.unaligned_load((^u64)(raw_data(data[i:]))) - if chunk & 0x8080808080808080 != 0 do return false + + if chunk & 0x8080808080808080 != 0 { + return false + } } for ; i < len(data); i += 1 { - if data[i] >= 0x80 do return false + if data[i] >= 0x80 { + return false + } } return true } @@ -40,10 +45,15 @@ bytes_all_ascii_no_nul :: proc(data: []byte) -> bool { for ; i + 8 <= len(data); i += 8 { chunk := intrinsics.unaligned_load((^u64)(raw_data(data[i:]))) has_nul := (chunk - 0x0101010101010101) & ~chunk & 0x8080808080808080 - if chunk & 0x8080808080808080 != 0 || has_nul != 0 do return false + + if chunk & 0x8080808080808080 != 0 || has_nul != 0 { + return false + } } for ; i < len(data); i += 1 { - if data[i] >= 0x80 || data[i] == 0 do return false + if data[i] >= 0x80 || data[i] == 0 { + return false + } } return true } @@ -60,6 +70,7 @@ ascii_string_value :: proc(ctx: jsc.JSContextRef, buf: []byte) -> jsc.JSValueRef defer jsc.JSStringRelease(str) return jsc.JSValueMakeString(ctx, str) } + js_str := jsc.JSStringCreateWithUTF8CString(cstring(raw_data(buf))) defer jsc.JSStringRelease(js_str) return jsc.JSValueMakeString(ctx, js_str) @@ -84,13 +95,19 @@ read_string_arg :: proc(ctx: jsc.JSContextRef, v: jsc.JSValueRef) -> (r: String_ r.ok = true return } + if s16, ok := jsc.value_chars16(ctx, v); ok { r.s16 = s16 r.ok = true return } + str := jsc.JSValueToStringCopy(ctx, v, nil) - if str == nil do return + + if str == nil { + return + } + if s8, ok := jsc.string_chars8(str); ok { r.s8 = s8 r.is8 = true @@ -98,12 +115,15 @@ read_string_arg :: proc(ctx: jsc.JSContextRef, v: jsc.JSValueRef) -> (r: String_ r.ok = true return } + length := int(jsc.JSStringGetLength(str)) chars := jsc.JSStringGetCharactersPtr(str) + if chars == nil { jsc.JSStringRelease(str) return } + r.s16 = chars[:length] r.str = str r.ok = true @@ -111,7 +131,10 @@ read_string_arg :: proc(ctx: jsc.JSContextRef, v: jsc.JSValueRef) -> (r: String_ } string_read_len :: proc(r: String_Read) -> int { - if r.is8 do return len(r.s8) + if r.is8 { + return len(r.s8) + } + return len(r.s16) } @@ -127,17 +150,25 @@ buffer_hex_encode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) == 0 do return js_string_value(ctx, "") + + if !ok || len(data) == 0 { + return js_string_value(ctx, "") + } n := len(data) * 2 + if str, dst, ok8 := jsc.string_alloc8(n); ok8 { hex_write(dst, data) defer jsc.JSStringRelease(str) return jsc.JSValueMakeString(ctx, str) } + out := make([]byte, n + 1, context.temp_allocator) hex_write(out[:n], data) out[n] = 0 @@ -146,13 +177,18 @@ buffer_hex_encode_cb :: proc "c" ( @(private = "file") hex_decode_from :: proc(ctx: jsc.JSContextRef, chars: []$T) -> jsc.JSValueRef { - if len(chars) < 2 do return make_uint8_array(ctx, nil) + if len(chars) < 2 { + return make_uint8_array(ctx, nil) + } + out := make([]byte, len(chars) / 2, context.allocator) n := hex_parse_into(out, chars) + if n == 0 { delete(out, context.allocator) return make_uint8_array(ctx, nil) } + return make_uint8_array(ctx, out[:n]) } @@ -165,12 +201,25 @@ buffer_hex_decode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return make_uint8_array(ctx, nil) + + if argument_count < 1 { + return make_uint8_array(ctx, nil) + } r := read_string_arg(ctx, arguments[0]) - if !r.ok do return make_uint8_array(ctx, nil) - defer if r.str != nil do jsc.JSStringRelease(r.str) - if r.is8 do return hex_decode_from(ctx, r.s8) + + if !r.ok { + return make_uint8_array(ctx, nil) + } + + defer if r.str != nil { + jsc.JSStringRelease(r.str) + } + + if r.is8 { + return hex_decode_from(ctx, r.s8) + } + return hex_decode_from(ctx, r.s16) } @@ -186,17 +235,25 @@ buffer_base64_encode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) == 0 do return js_string_value(ctx, "") + + if !ok || len(data) == 0 { + return js_string_value(ctx, "") + } n := (len(data) + 2) / 3 * 4 + if str, dst, ok8 := jsc.string_alloc8(n); ok8 { base64_write(dst, data) defer jsc.JSStringRelease(str) return jsc.JSValueMakeString(ctx, str) } + out := make([]byte, n + 1, context.temp_allocator) base64_write(out[:n], data) out[n] = 0 @@ -216,26 +273,45 @@ buffer_base64_decode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return make_uint8_array(ctx, nil) + + if argument_count < 1 { + return make_uint8_array(ctx, nil) + } // Same in-place read as hexDecode: base64 input is ASCII by contract. r := read_string_arg(ctx, arguments[0]) - if !r.ok do return make_uint8_array(ctx, nil) - defer if r.str != nil do jsc.JSStringRelease(r.str) - if r.is8 do return base64_decode_from(ctx, r.s8) + + if !r.ok { + return make_uint8_array(ctx, nil) + } + + defer if r.str != nil { + jsc.JSStringRelease(r.str) + } + + if r.is8 { + return base64_decode_from(ctx, r.s8) + } + return base64_decode_from(ctx, r.s16) } @(private = "file") base64_decode_from :: proc(ctx: jsc.JSContextRef, chars: []$T) -> jsc.JSValueRef { length := len(chars) - if length == 0 || length % 4 != 0 do return make_uint8_array(ctx, nil) + + if length == 0 || length % 4 != 0 { + return make_uint8_array(ctx, nil) + } + out := make([]byte, length / 4 * 3, context.allocator) n, okp := base64_parse(out, chars) + if !okp { delete(out, context.allocator) return make_uint8_array(ctx, nil) } + return make_uint8_array(ctx, out[:n]) } @@ -252,11 +328,18 @@ buffer_alloc_uninit_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNull(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeNull(ctx) + } n := js_int_arg(ctx, arguments[0]) array, ok := make_uint8_array_uninit(ctx, n) - if !ok do return jsc.JSValueMakeNull(ctx) + + if !ok { + return jsc.JSValueMakeNull(ctx) + } + return array } @@ -283,17 +366,27 @@ when size_of(uintptr) >= 8 { // silently capping every allocation to zero. max_buffer_alloc_bytes :: proc() -> f64 { environ, err := os.environ(context.temp_allocator) + if err == os.ERROR_NONE { for entry in environ { idx := strings.index_byte(entry, '=') - if idx <= 0 do continue - if entry[:idx] != "LAVA_MAX_BUFFER_BYTES" do continue + + if idx <= 0 { + continue + } + + if entry[:idx] != "LAVA_MAX_BUFFER_BYTES" { + continue + } + if n, ok := strconv.parse_f64(entry[idx + 1:]); ok && n > 0 { return n } + break } } + return DEFAULT_MAX_BUFFER_BYTES } @@ -312,17 +405,37 @@ buffer_compare_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return js_int_value(ctx, 0) + + if argument_count < 2 { + return js_int_value(ctx, 0) + } + a, aok := typed_array_view(ctx, arguments[0]) b, bok := typed_array_view(ctx, arguments[1]) - if !aok || !bok do return js_int_value(ctx, 0) + + if !aok || !bok { + return js_int_value(ctx, 0) + } + n := min(len(a), len(b)) for i in 0 ..< n { - if a[i] < b[i] do return js_int_value(ctx, -1) - if a[i] > b[i] do return js_int_value(ctx, 1) + if a[i] < b[i] { + return js_int_value(ctx, -1) + } + + if a[i] > b[i] { + return js_int_value(ctx, 1) + } + } + + if len(a) < len(b) { + return js_int_value(ctx, -1) } - if len(a) < len(b) do return js_int_value(ctx, -1) - if len(a) > len(b) do return js_int_value(ctx, 1) + + if len(a) > len(b) { + return js_int_value(ctx, 1) + } + return js_int_value(ctx, 0) } @@ -341,31 +454,62 @@ buffer_index_of_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 4 do return js_int_value(ctx, -1) + + if argument_count < 4 { + return js_int_value(ctx, -1) + } + // js_int_arg can run JS (valueOf) — read it before borrowing the views; see // the note in buffer_utf16le_write_into_cb. start := js_int_arg(ctx, arguments[2]) forward := jsc.JSValueToBoolean(ctx, arguments[3]) hay, hok := typed_array_view(ctx, arguments[0]) needle, nok := typed_array_view(ctx, arguments[1]) - if !hok || !nok do return js_int_value(ctx, -1) + + if !hok || !nok { + return js_int_value(ctx, -1) + } + nlen := len(needle) hlen := len(hay) - if nlen == 0 || nlen > hlen do return js_int_value(ctx, -1) + + if nlen == 0 || nlen > hlen { + return js_int_value(ctx, -1) + } + if forward { s := start - if s < 0 do s = 0 - if s > hlen do return js_int_value(ctx, -1) + + if s < 0 { + s = 0 + } + + if s > hlen { + return js_int_value(ctx, -1) + } + idx := bytes.index(hay[s:], needle) - if idx < 0 do return js_int_value(ctx, -1) + + if idx < 0 { + return js_int_value(ctx, -1) + } + return js_int_value(ctx, s + idx) } + // Backward: search the window [0, start+nlen) so the last match within it // starts at the largest k <= start. bytes.last_index returns an absolute index // (the window begins at 0) or -1. end := start + nlen - if end > hlen do end = hlen - if end < nlen do return js_int_value(ctx, -1) + + if end > hlen { + end = hlen + } + + if end < nlen { + return js_int_value(ctx, -1) + } + return js_int_value(ctx, bytes.last_index(hay[:end], needle)) } @@ -380,25 +524,42 @@ buffer_latin1_encode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return make_uint8_array(ctx, nil) + + if argument_count < 1 { + return make_uint8_array(ctx, nil) + } r := read_string_arg(ctx, arguments[0]) - if !r.ok do return make_uint8_array(ctx, nil) - defer if r.str != nil do jsc.JSStringRelease(r.str) + + if !r.ok { + return make_uint8_array(ctx, nil) + } + + defer if r.str != nil { + jsc.JSStringRelease(r.str) + } + // 8-bit storage IS the latin1 byte sequence — one copy, no widen; 16-bit // units are masked to their low byte. if r.is8 { - if len(r.s8) == 0 do return make_uint8_array(ctx, nil) + if len(r.s8) == 0 { + return make_uint8_array(ctx, nil) + } + out := make([]byte, len(r.s8), context.allocator) copy(out, r.s8) return make_uint8_array(ctx, out) } + return latin1_bytes_from_units(ctx, r.s16) } @(private = "file") latin1_bytes_from_units :: proc(ctx: jsc.JSContextRef, chars: []jsc.JSChar) -> jsc.JSValueRef { - if len(chars) == 0 do return make_uint8_array(ctx, nil) + if len(chars) == 0 { + return make_uint8_array(ctx, nil) + } + out := make([]byte, len(chars), context.allocator) for u, i in chars { out[i] = byte(u & 0xFF) @@ -414,20 +575,27 @@ latin1_bytes_from_units :: proc(ctx: jsc.JSContextRef, chars: []jsc.JSChar) -> j // anything else goes through CreateWithCharacters so bytes are preserved. // Shared with the node:http request parser (header name/value/method/url). latin1_string_from_bytes :: proc(ctx: jsc.JSContextRef, data: []byte) -> jsc.JSValueRef { - if len(data) == 0 do return js_string_value(ctx, "") + if len(data) == 0 { + return js_string_value(ctx, "") + } + if str, dst, ok := jsc.string_alloc8(len(data)); ok { copy(dst, data) defer jsc.JSStringRelease(str) return jsc.JSValueMakeString(ctx, str) } + if bytes_all_ascii_no_nul(data) { tmp := make([]byte, len(data) + 1, context.temp_allocator) copy(tmp, data) tmp[len(data)] = 0 return ascii_string_value(ctx, tmp) } + units := make([]jsc.JSChar, len(data), context.temp_allocator) - for i in 0 ..< len(data) do units[i] = jsc.JSChar(data[i]) + for i in 0 ..< len(data) { + units[i] = jsc.JSChar(data[i]) + } js_str := jsc.JSStringCreateWithCharacters(raw_data(units), c.size_t(len(data))) defer jsc.JSStringRelease(js_str) return jsc.JSValueMakeString(ctx, js_str) @@ -443,10 +611,17 @@ buffer_latin1_decode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) == 0 do return js_string_value(ctx, "") + + if !ok || len(data) == 0 { + return js_string_value(ctx, "") + } + return latin1_string_from_bytes(ctx, data) } @@ -462,10 +637,16 @@ buffer_ascii_decode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) == 0 do return js_string_value(ctx, "") + + if !ok || len(data) == 0 { + return js_string_value(ctx, "") + } // Mask in a temp only when a high bit is present; otherwise latin1 path is // identical and avoids an extra pass + allocation. @@ -476,10 +657,15 @@ buffer_ascii_decode_cb :: proc "c" ( break } } - if !needs_mask do return latin1_string_from_bytes(ctx, data) + + if !needs_mask { + return latin1_string_from_bytes(ctx, data) + } masked := make([]byte, len(data), context.temp_allocator) - for b, i in data do masked[i] = b & 0x7F + for b, i in data { + masked[i] = b & 0x7F + } return latin1_string_from_bytes(ctx, masked) } @@ -494,14 +680,27 @@ buffer_utf16le_encode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return make_uint8_array(ctx, nil) + + if argument_count < 1 { + return make_uint8_array(ctx, nil) + } r := read_string_arg(ctx, arguments[0]) - if !r.ok do return make_uint8_array(ctx, nil) - defer if r.str != nil do jsc.JSStringRelease(r.str) + + if !r.ok { + return make_uint8_array(ctx, nil) + } + + defer if r.str != nil { + jsc.JSStringRelease(r.str) + } + if r.is8 { // 8-bit storage: each unit is a byte, high byte always 0 — no widen pass. - if len(r.s8) == 0 do return make_uint8_array(ctx, nil) + if len(r.s8) == 0 { + return make_uint8_array(ctx, nil) + } + out := make([]byte, len(r.s8) * 2, context.allocator) for b, i in r.s8 { out[i * 2] = b @@ -509,12 +708,16 @@ buffer_utf16le_encode_cb :: proc "c" ( } return make_uint8_array(ctx, out) } + return utf16le_bytes_from_units(ctx, r.s16) } @(private = "file") utf16le_bytes_from_units :: proc(ctx: jsc.JSContextRef, chars: []jsc.JSChar) -> jsc.JSValueRef { - if len(chars) == 0 do return make_uint8_array(ctx, nil) + if len(chars) == 0 { + return make_uint8_array(ctx, nil) + } + out := make([]byte, len(chars) * 2, context.allocator) when ODIN_ENDIAN == .Little { mem.copy(raw_data(out), raw_data(chars), len(out)) @@ -539,17 +742,25 @@ buffer_utf16le_decode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) < 2 do return js_string_value(ctx, "") + + if !ok || len(data) < 2 { + return js_string_value(ctx, "") + } n := len(data) / 2 + if str, dst, ok16 := jsc.string_alloc16(n); ok16 { utf16le_units_write(dst, data) defer jsc.JSStringRelease(str) return jsc.JSValueMakeString(ctx, str) } + units := make([]jsc.JSChar, n, context.temp_allocator) utf16le_units_write(units, data) js_str := jsc.JSStringCreateWithCharacters(raw_data(units), c.size_t(n)) @@ -583,7 +794,11 @@ buffer_utf16le_write_into_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 4 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 4 { + return jsc.JSValueMakeNumber(ctx, 0) + } + // Argument-read order is load-bearing: read_string_arg / js_int_arg can run // arbitrary JS (toString/valueOf on a non-primitive), which may detach or // resize the target's ArrayBuffer. The borrowed target view must therefore be @@ -591,27 +806,58 @@ buffer_utf16le_write_into_cb :: proc "c" ( // borrows are immune: string storage is immutable and pinned by the retained // ref / the live argument.) src := read_string_arg(ctx, arguments[1]) - if !src.ok do return js_int_value(ctx, 0) - defer if src.str != nil do jsc.JSStringRelease(src.str) + + if !src.ok { + return js_int_value(ctx, 0) + } + + defer if src.str != nil { + jsc.JSStringRelease(src.str) + } slen := string_read_len(src) - if slen == 0 do return js_int_value(ctx, 0) + + if slen == 0 { + return js_int_value(ctx, 0) + } offset := js_int_arg(ctx, arguments[2]) max := js_int_arg(ctx, arguments[3]) target, tok := typed_array_view(ctx, arguments[0]) - if !tok do return jsc.JSValueMakeNumber(ctx, 0) - if offset < 0 do offset = 0 - if offset > len(target) do offset = len(target) + + if !tok { + return jsc.JSValueMakeNumber(ctx, 0) + } + + if offset < 0 { + offset = 0 + } + + if offset > len(target) { + offset = len(target) + } + avail := len(target) - offset - if max > avail do max = avail + + if max > avail { + max = avail + } + // Even byte count only — half a code unit is never written. max = max - (max % 2) - if max <= 0 do return js_int_value(ctx, 0) + + if max <= 0 { + return js_int_value(ctx, 0) + } n_units := max / 2 - if n_units > slen do n_units = slen + + if n_units > slen { + n_units = slen + } + dst := target[offset:] + if src.is8 { for i in 0 ..< n_units { dst[i * 2] = src.s8[i] @@ -628,6 +874,7 @@ buffer_utf16le_write_into_cb :: proc "c" ( } } } + return js_int_value(ctx, n_units * 2) } @@ -645,29 +892,62 @@ buffer_latin1_write_into_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 4 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 4 { + return jsc.JSValueMakeNumber(ctx, 0) + } + // Re-entrancy hazard: the target view must be acquired after every argument // coercion — see the note in buffer_utf16le_write_into_cb. src := read_string_arg(ctx, arguments[1]) - if !src.ok do return js_int_value(ctx, 0) - defer if src.str != nil do jsc.JSStringRelease(src.str) + + if !src.ok { + return js_int_value(ctx, 0) + } + + defer if src.str != nil { + jsc.JSStringRelease(src.str) + } slen := string_read_len(src) - if slen == 0 do return js_int_value(ctx, 0) + + if slen == 0 { + return js_int_value(ctx, 0) + } offset := js_int_arg(ctx, arguments[2]) max := js_int_arg(ctx, arguments[3]) target, tok := typed_array_view(ctx, arguments[0]) - if !tok do return jsc.JSValueMakeNumber(ctx, 0) - if offset < 0 do offset = 0 - if offset > len(target) do offset = len(target) + + if !tok { + return jsc.JSValueMakeNumber(ctx, 0) + } + + if offset < 0 { + offset = 0 + } + + if offset > len(target) { + offset = len(target) + } + avail := len(target) - offset n := slen - if n > max do n = max - if n > avail do n = avail - if n <= 0 do return js_int_value(ctx, 0) + + if n > max { + n = max + } + + if n > avail { + n = avail + } + + if n <= 0 { + return js_int_value(ctx, 0) + } dst := target[offset:][:n] + // 8-bit storage IS the latin1 byte sequence — straight copy. if src.is8 { copy(dst, src.s8) @@ -676,6 +956,7 @@ buffer_latin1_write_into_cb :: proc "c" ( dst[i] = byte(src.s16[i] & 0xFF) } } + return js_int_value(ctx, n) } @@ -693,10 +974,16 @@ buffer_base64url_encode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) == 0 do return js_string_value(ctx, "") + + if !ok || len(data) == 0 { + return js_string_value(ctx, "") + } // Unpadded: exact output length is known up front. n := len(data) @@ -708,11 +995,13 @@ buffer_base64url_encode_cb :: proc "c" ( case 2: out_len += 3 } + if str, dst, ok8 := jsc.string_alloc8(out_len); ok8 { base64url_write(dst, data) defer jsc.JSStringRelease(str) return jsc.JSValueMakeString(ctx, str) } + out := make([]byte, out_len + 1, context.temp_allocator) base64url_write(out[:out_len], data) out[out_len] = 0 @@ -728,25 +1017,45 @@ buffer_base64_byte_length_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 0) + } src := read_string_arg(ctx, arguments[0]) - if !src.ok do return js_int_value(ctx, 0) - defer if src.str != nil do jsc.JSStringRelease(src.str) + + if !src.ok { + return js_int_value(ctx, 0) + } + + defer if src.str != nil { + jsc.JSStringRelease(src.str) + } len := string_read_len(src) - if len == 0 do return js_int_value(ctx, 0) + + if len == 0 { + return js_int_value(ctx, 0) + } + // Only the final two characters matter. if src.is8 { if src.s8[len - 1] == '=' { len -= 1 - if len > 0 && src.s8[len - 1] == '=' do len -= 1 + + if len > 0 && src.s8[len - 1] == '=' { + len -= 1 + } } } else { if src.s16[len - 1] == '=' { len -= 1 - if len > 0 && src.s16[len - 1] == '=' do len -= 1 + + if len > 0 && src.s16[len - 1] == '=' { + len -= 1 + } } } + return js_int_value(ctx, (len * 3) >> 2) } @@ -759,15 +1068,30 @@ buffer_swap_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 2 { + return jsc.JSValueMakeUndefined(ctx) + } + // js_int_arg can run JS (valueOf) — read it before borrowing the view; see // the note in buffer_utf16le_write_into_cb. width := js_int_arg(ctx, arguments[1]) - if width != 2 && width != 4 && width != 8 do return jsc.JSValueMakeUndefined(ctx) + + if width != 2 && width != 4 && width != 8 { + return jsc.JSValueMakeUndefined(ctx) + } + data, ok := typed_array_view(ctx, arguments[0]) - if !ok do return jsc.JSValueMakeUndefined(ctx) + + if !ok { + return jsc.JSValueMakeUndefined(ctx) + } + n := len(data) - if n % width != 0 do return jsc.JSValueMakeUndefined(ctx) + + if n % width != 0 { + return jsc.JSValueMakeUndefined(ctx) + } switch width { case 2: diff --git a/pkg/runtime/buffer_simd.odin b/pkg/runtime/buffer_simd.odin index d2148b6f..97cf7f3f 100644 --- a/pkg/runtime/buffer_simd.odin +++ b/pkg/runtime/buffer_simd.odin @@ -28,10 +28,18 @@ buffer_codec_tables_init :: proc "contextless" () { g_hex_val[i] = 0xFF g_b64_val[i] = 0xFF } - for ch, v in "0123456789" do g_hex_val[ch] = u8(v) - for ch, v in "abcdef" do g_hex_val[ch] = u8(v) + 10 - for ch, v in "ABCDEF" do g_hex_val[ch] = u8(v) + 10 - for ch, v in B64_ALPHABET do g_b64_val[ch] = u8(v) + for ch, v in "0123456789" { + g_hex_val[ch] = u8(v) + } + for ch, v in "abcdef" { + g_hex_val[ch] = u8(v) + 10 + } + for ch, v in "ABCDEF" { + g_hex_val[ch] = u8(v) + 10 + } + for ch, v in B64_ALPHABET { + g_b64_val[ch] = u8(v) + } } @(private) @@ -81,7 +89,11 @@ hex_parse_into :: proc(out: []byte, chars: []$T) -> int { is_digit := transmute(U8x16)simd.lanes_lt(vd, cast(U8x16)u8(10)) va := (v | cast(U8x16)u8(0x20)) - cast(U8x16)u8('a') is_alpha := transmute(U8x16)simd.lanes_lt(va, cast(U8x16)u8(6)) - if simd.reduce_and(is_digit | is_alpha) != 0xFF do break + + if simd.reduce_and(is_digit | is_alpha) != 0xFF { + break + } + vals := (is_digit & vd) | (is_alpha & (va + cast(U8x16)u8(10))) ev := simd.shuffle(vals, vals, 0, 2, 4, 6, 8, 10, 12, 14) od := simd.shuffle(vals, vals, 1, 3, 5, 7, 9, 11, 13, 15) @@ -93,11 +105,17 @@ hex_parse_into :: proc(out: []byte, chars: []$T) -> int { c0 := chars[i * 2] c1 := chars[i * 2 + 1] when size_of(T) > 1 { - if c0 >= 256 || c1 >= 256 do return i + if c0 >= 256 || c1 >= 256 { + return i + } } d0 := g_hex_val[c0] d1 := g_hex_val[c1] - if d0 == 0xFF || d1 == 0xFF do return i + + if d0 == 0xFF || d1 == 0xFF { + return i + } + out[i] = d0 << 4 | d1 } return pairs @@ -157,6 +175,7 @@ base64_write_impl :: proc(dst: []byte, src: []byte, alphabet: string, sub61: u8, v := u32(src[i]) << 16 dst[di] = alphabet[v >> 18] dst[di + 1] = alphabet[v >> 12 & 0x3F] + if padded { dst[di + 2] = '=' dst[di + 3] = '=' @@ -166,7 +185,10 @@ base64_write_impl :: proc(dst: []byte, src: []byte, alphabet: string, sub61: u8, dst[di] = alphabet[v >> 18] dst[di + 1] = alphabet[v >> 12 & 0x3F] dst[di + 2] = alphabet[v >> 6 & 0x3F] - if padded do dst[di + 3] = '=' + + if padded { + dst[di + 3] = '=' + } } } @@ -192,7 +214,9 @@ base64_parse :: proc(out: []byte, chars: []$T) -> (n: int, ok: bool) { for g in 0 ..< groups { s := chars[g * 4:g * 4 + 4] when size_of(T) > 1 { - if s[0] >= 256 || s[1] >= 256 || s[2] >= 256 || s[3] >= 256 do return 0, false + if s[0] >= 256 || s[1] >= 256 || s[2] >= 256 || s[3] >= 256 { + return 0, false + } } d0 := g_b64_val[s[0]] d1 := g_b64_val[s[1]] @@ -200,6 +224,7 @@ base64_parse :: proc(out: []byte, chars: []$T) -> (n: int, ok: bool) { pad3 := s[3] == '=' d2 := pad2 ? 0 : g_b64_val[s[2]] d3 := pad3 ? 0 : g_b64_val[s[3]] + if d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || @@ -208,9 +233,11 @@ base64_parse :: proc(out: []byte, chars: []$T) -> (n: int, ok: bool) { ((pad2 || pad3) && g != groups - 1) { return 0, false } + v := u32(d0) << 18 | u32(d1) << 12 | u32(d2) << 6 | u32(d3) out[n] = byte(v >> 16) n += 1 + if !pad2 && !pad3 { out[n] = byte(v >> 8) out[n + 1] = byte(v) diff --git a/pkg/runtime/buffer_utf8.odin b/pkg/runtime/buffer_utf8.odin index d98f8ba7..9488c7a8 100644 --- a/pkg/runtime/buffer_utf8.odin +++ b/pkg/runtime/buffer_utf8.odin @@ -18,10 +18,14 @@ buffer_utf8_encode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return make_uint8_array(ctx, nil) + + if argument_count < 1 { + return make_uint8_array(ctx, nil) + } str, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - if !alloc do return make_uint8_array(ctx, nil) // empty string + + if !alloc {return make_uint8_array(ctx, nil)} // empty string // Do NOT free `str`: its backing buffer is handed to JSC below. return make_uint8_array(ctx, transmute([]byte)str) } @@ -33,6 +37,7 @@ emit_utf16 :: proc "contextless" (out: []u16, cp: u32) -> int { out[0] = u16(cp) return 1 } + c := cp - 0x10000 out[0] = u16(0xD800 + (c >> 10)) out[1] = u16(0xDC00 + (c & 0x3FF)) @@ -72,24 +77,28 @@ decode_utf8_to_utf16_whatwg :: proc "contextless" (data: []byte, out: []u16) -> for i < len(data) { b := data[i] + if bytes_needed == 0 { if b <= 0x7F { // ASCII resumes after a completed multi-byte sequence out[n] = u16(b); n += 1 i += 1 continue } + switch { case b >= 0xC2 && b <= 0xDF: bytes_needed = 1; code_point = u32(b & 0x1F) i += 1 case b >= 0xE0 && b <= 0xEF: - if b == 0xE0 do lower = 0xA0 // exclude overlong < U+0800 - if b == 0xED do upper = 0x9F // exclude UTF-16 surrogates + if b == 0xE0 {lower = 0xA0} // exclude overlong < U+0800 + + if b == 0xED {upper = 0x9F} // exclude UTF-16 surrogates bytes_needed = 2; code_point = u32(b & 0x0F) i += 1 case b >= 0xF0 && b <= 0xF4: - if b == 0xF0 do lower = 0x90 // exclude overlong < U+10000 - if b == 0xF4 do upper = 0x8F // exclude > U+10FFFF + if b == 0xF0 {lower = 0x90} // exclude overlong < U+10000 + + if b == 0xF4 {upper = 0x8F} // exclude > U+10FFFF bytes_needed = 3; code_point = u32(b & 0x07) i += 1 case: @@ -109,6 +118,7 @@ decode_utf8_to_utf16_whatwg :: proc "contextless" (data: []byte, out: []u16) -> code_point = (code_point << 6) | u32(b & 0x3F) bytes_seen += 1 i += 1 + if bytes_seen == bytes_needed { // #force_inline: hot path, but keep emit_utf16 a single named unit // (no duplicated surrogate-pair logic). @@ -118,10 +128,12 @@ decode_utf8_to_utf16_whatwg :: proc "contextless" (data: []byte, out: []u16) -> } } } + // Unfinished trailing sequence at end of input -> a single replacement. if bytes_needed != 0 { out[n] = 0xFFFD; n += 1 } + return n } @@ -140,10 +152,16 @@ buffer_utf8_decode_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return js_string_value(ctx, "") + + if argument_count < 1 { + return js_string_value(ctx, "") + } data, ok := typed_array_view(ctx, arguments[0]) - if !ok || len(data) == 0 do return js_string_value(ctx, "") + + if !ok || len(data) == 0 { + return js_string_value(ctx, "") + } // Pure-ASCII (NULs included): same as latin1 bytes → 8-bit StringImpl. if bytes_all_ascii(data) { @@ -157,11 +175,13 @@ buffer_utf8_decode_cb :: proc "c" ( copy(tmp, data) tmp[len(data)] = 0 js_str := jsc.JSStringCreateWithUTF8CString(cstring(raw_data(tmp))) + if js_str != nil { if jsc.JSStringGetLength(js_str) > 0 { defer jsc.JSStringRelease(js_str) return jsc.JSValueMakeString(ctx, js_str) } + jsc.JSStringRelease(js_str) } } @@ -194,10 +214,21 @@ buffer_is_valid_utf8_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeBoolean(ctx, true) + + if argument_count < 1 { + return jsc.JSValueMakeBoolean(ctx, true) + } + data, ok := typed_array_view(ctx, arguments[0]) - if !ok do return jsc.JSValueMakeBoolean(ctx, false) - if len(data) == 0 do return jsc.JSValueMakeBoolean(ctx, true) + + if !ok { + return jsc.JSValueMakeBoolean(ctx, false) + } + + if len(data) == 0 { + return jsc.JSValueMakeBoolean(ctx, true) + } + return jsc.JSValueMakeBoolean(ctx, b32(utf8.valid_string(string(data)))) } @@ -213,41 +244,78 @@ buffer_utf8_write_into_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 4 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 4 { + return jsc.JSValueMakeNumber(ctx, 0) + } + // Re-entrancy hazard: the target view must be acquired after every argument // coercion — see the note in buffer_utf16le_write_into_cb (buffer.odin). src := read_string_arg(ctx, arguments[1]) - if !src.ok do return js_int_value(ctx, 0) - defer if src.str != nil do jsc.JSStringRelease(src.str) + + if !src.ok { + return js_int_value(ctx, 0) + } + + defer if src.str != nil { + jsc.JSStringRelease(src.str) + } slen := string_read_len(src) - if slen == 0 do return js_int_value(ctx, 0) + + if slen == 0 { + return js_int_value(ctx, 0) + } offset := js_int_arg(ctx, arguments[2]) max := js_int_arg(ctx, arguments[3]) target, tok := typed_array_view(ctx, arguments[0]) - if !tok do return jsc.JSValueMakeNumber(ctx, 0) - if offset < 0 do offset = 0 - if offset > len(target) do offset = len(target) + + if !tok { + return jsc.JSValueMakeNumber(ctx, 0) + } + + if offset < 0 { + offset = 0 + } + + if offset > len(target) { + offset = len(target) + } + avail := len(target) - offset - if max > avail do max = avail - if max <= 0 do return js_int_value(ctx, 0) + + if max > avail { + max = avail + } + + if max <= 0 { + return js_int_value(ctx, 0) + } dst := target[offset:][:max] + if src.is8 { // ASCII 8-bit storage is already UTF-8 — straight capped copy. Latin-1 // high bytes expand to two UTF-8 bytes each, capped at the boundary. if bytes_all_ascii(src.s8) { return js_int_value(ctx, copy(dst, src.s8)) } + o := 0 for b in src.s8 { if b < 0x80 { - if o + 1 > len(dst) do break + if o + 1 > len(dst) { + break + } + dst[o] = b o += 1 } else { - if o + 2 > len(dst) do break + if o + 2 > len(dst) { + break + } + dst[o] = 0xC0 | (b >> 6) dst[o + 1] = 0x80 | (b & 0x3F) o += 2 @@ -255,6 +323,7 @@ buffer_utf8_write_into_cb :: proc "c" ( } return js_int_value(ctx, o) } + n := jsc.utf16_js_to_utf8_capped(raw_data(src.s16), slen, dst) return js_int_value(ctx, n) } @@ -268,19 +337,32 @@ buffer_utf8_byte_length_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 0) + } src := read_string_arg(ctx, arguments[0]) - if !src.ok do return js_int_value(ctx, 0) - defer if src.str != nil do jsc.JSStringRelease(src.str) + + if !src.ok { + return js_int_value(ctx, 0) + } + + defer if src.str != nil { + jsc.JSStringRelease(src.str) + } + // 8-bit storage: no surrogates possible; UTF-8 length is len + one extra // byte per Latin-1 high byte. if src.is8 { n := len(src.s8) for b in src.s8 { - if b >= 0x80 do n += 1 + if b >= 0x80 { + n += 1 + } } return js_int_value(ctx, n) } + return js_int_value(ctx, jsc.utf16_js_utf8_byte_len(raw_data(src.s16), len(src.s16))) } diff --git a/pkg/runtime/crypto.odin b/pkg/runtime/crypto.odin index a5cdb0e6..5efdf743 100644 --- a/pkg/runtime/crypto.odin +++ b/pkg/runtime/crypto.odin @@ -80,16 +80,25 @@ crypto_random_fill_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } view, ok := typed_array_view(ctx, arguments[0]) + if !ok { if exception != nil { exception^ = make_js_error(ctx, "randomFill expects a Uint8Array") } + return jsc.JSValueMakeUndefined(ctx) } - if len(view) > 0 do crypto.rand_bytes(view) + + if len(view) > 0 { + crypto.rand_bytes(view) + } + return arguments[0] } @@ -105,12 +114,19 @@ crypto_random_int_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } range := u64(jsc.JSValueToNumber(ctx, arguments[0], nil)) max_48 :: u64(1) << 48 + if range == 0 || range > max_48 { - if exception != nil do exception^ = make_js_error(ctx, "randomInt range must be in (0, 2^48]") + if exception != nil { + exception^ = make_js_error(ctx, "randomInt range must be in (0, 2^48]") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -130,22 +146,33 @@ crypto_hash_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 2 { + return jsc.JSValueMakeUndefined(ctx) + } name, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if alloc do delete(name, context.allocator) + defer if alloc { + delete(name, context.allocator) + } algo, valid := crypto_algorithm(name) + if !valid { if exception != nil { exception^ = make_js_error(ctx, "Digest method not supported") } + return jsc.JSValueMakeUndefined(ctx) } data, ok := typed_array_view(ctx, arguments[1]) + if !ok { - if exception != nil do exception^ = make_js_error(ctx, "hash expects a Uint8Array") + if exception != nil { + exception^ = make_js_error(ctx, "hash expects a Uint8Array") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -164,23 +191,34 @@ crypto_hmac_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 3 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 3 { + return jsc.JSValueMakeUndefined(ctx) + } name, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if alloc do delete(name, context.allocator) + defer if alloc { + delete(name, context.allocator) + } algo, valid := crypto_algorithm(name) + if !valid { if exception != nil { exception^ = make_js_error(ctx, "Digest method not supported") } + return jsc.JSValueMakeUndefined(ctx) } key, key_ok := typed_array_view(ctx, arguments[1]) data, data_ok := typed_array_view(ctx, arguments[2]) + if !key_ok || !data_ok { - if exception != nil do exception^ = make_js_error(ctx, "hmac expects Uint8Array key and data") + if exception != nil { + exception^ = make_js_error(ctx, "hmac expects Uint8Array key and data") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -199,16 +237,23 @@ crypto_pbkdf2_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 5 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 5 { + return jsc.JSValueMakeUndefined(ctx) + } name, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if alloc do delete(name, context.allocator) + defer if alloc { + delete(name, context.allocator) + } algo, valid := crypto_algorithm(name) + if !valid { if exception != nil { exception^ = make_js_error(ctx, "Digest method not supported") } + return jsc.JSValueMakeUndefined(ctx) } @@ -216,15 +261,23 @@ crypto_pbkdf2_cb :: proc "c" ( // the views; see the note in buffer_utf16le_write_into_cb (buffer.odin). iterations := u32(jsc.JSValueToNumber(ctx, arguments[3], nil)) keylen := int(jsc.JSValueToNumber(ctx, arguments[4], nil)) + if iterations == 0 || keylen <= 0 { - if exception != nil do exception^ = make_js_error(ctx, "pbkdf2 requires positive iterations and keylen") + if exception != nil { + exception^ = make_js_error(ctx, "pbkdf2 requires positive iterations and keylen") + } + return jsc.JSValueMakeUndefined(ctx) } password, pw_ok := typed_array_view(ctx, arguments[1]) salt, salt_ok := typed_array_view(ctx, arguments[2]) + if !pw_ok || !salt_ok { - if exception != nil do exception^ = make_js_error(ctx, "pbkdf2 expects Uint8Array password and salt") + if exception != nil { + exception^ = make_js_error(ctx, "pbkdf2 expects Uint8Array password and salt") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -245,14 +298,23 @@ crypto_hkdf_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 5 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 5 { + return jsc.JSValueMakeUndefined(ctx) + } name, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if alloc do delete(name, context.allocator) + defer if alloc { + delete(name, context.allocator) + } algo, valid := crypto_algorithm(name) + if !valid { - if exception != nil do exception^ = make_js_error(ctx, "Digest method not supported") + if exception != nil { + exception^ = make_js_error(ctx, "Digest method not supported") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -260,16 +322,24 @@ crypto_hkdf_cb :: proc "c" ( // see the note in buffer_utf16le_write_into_cb (buffer.odin). keylen := int(jsc.JSValueToNumber(ctx, arguments[4], nil)) hash_len := hash.DIGEST_SIZES[algo] + if keylen < 0 || keylen > 255 * hash_len { - if exception != nil do exception^ = make_js_error(ctx, "Invalid key length") + if exception != nil { + exception^ = make_js_error(ctx, "Invalid key length") + } + return jsc.JSValueMakeUndefined(ctx) } ikm, ikm_ok := typed_array_view(ctx, arguments[1]) salt, salt_ok := typed_array_view(ctx, arguments[2]) info, info_ok := typed_array_view(ctx, arguments[3]) + if !ikm_ok || !salt_ok || !info_ok { - if exception != nil do exception^ = make_js_error(ctx, "hkdf expects Uint8Array ikm, salt, and info") + if exception != nil { + exception^ = make_js_error(ctx, "hkdf expects Uint8Array ikm, salt, and info") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -289,14 +359,22 @@ crypto_timing_safe_equal_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return jsc.JSValueMakeBoolean(ctx, false) + + if argument_count < 2 { + return jsc.JSValueMakeBoolean(ctx, false) + } a, a_ok := typed_array_view(ctx, arguments[0]) b, b_ok := typed_array_view(ctx, arguments[1]) + if !a_ok || !b_ok { - if exception != nil do exception^ = make_js_error(ctx, "timingSafeEqual expects Uint8Array arguments") + if exception != nil { + exception^ = make_js_error(ctx, "timingSafeEqual expects Uint8Array arguments") + } + return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeBoolean(ctx, b32(crypto.compare_constant_time(a, b) == 1)) } diff --git a/pkg/runtime/dns.odin b/pkg/runtime/dns.odin index 2b15b43a..ca5e8a09 100644 --- a/pkg/runtime/dns.odin +++ b/pkg/runtime/dns.odin @@ -81,21 +81,33 @@ dns_lookup_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 5 { - if exception != nil do exception^ = make_js_error(ctx, "dns lookup requires (hostname, family, order, all, callback)") + if exception != + nil {exception^ = make_js_error(ctx, "dns lookup requires (hostname, family, order, all, callback)")} + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] callback := callback_arg(ctx, args[4]) + if callback == nil { - if exception != nil do exception^ = make_js_error(ctx, "dns lookup callback must be a function") + if exception != nil { + exception^ = make_js_error(ctx, "dns lookup callback must be a function") + } + return jsc.JSValueMakeUndefined(ctx) } loop := get_loop_from_ctx(ctx) + if loop == nil { - if exception != nil do exception^ = make_js_error(ctx, "dns: no event loop is bound to this context") + if exception != nil { + exception^ = make_js_error(ctx, "dns: no event loop is bound to this context") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -104,7 +116,9 @@ dns_lookup_cb :: proc "c" ( alloc := runtime.heap_allocator() hostname, host_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if host_alloc do delete(hostname, context.allocator) + defer if host_alloc { + delete(hostname, context.allocator) + } req := new(Dns_Lookup_Request, alloc) req.allocator = alloc @@ -129,9 +143,14 @@ dns_lookup_cb :: proc "c" ( jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)callback) delete(req.hostname, req.allocator) free(req, req.allocator) - if exception != nil do exception^ = make_js_error(ctx, "dns: could not start resolver pool") + + if exception != nil { + exception^ = make_js_error(ctx, "dns: could not start resolver pool") + } + return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeUndefined(ctx) } @@ -144,6 +163,7 @@ dns_query_family :: proc(req: ^Dns_Lookup_Request, type: net.DNS_Record_Type, fa recs: []net.DNS_Record err: net.DNS_Error is_mdns := ODIN_OS != .Windows && strings.has_suffix(req.hostname, ".local") + if is_mdns && type == .IP4 { recs, err = net.get_dns_records_from_nameservers( req.hostname, @@ -163,9 +183,13 @@ dns_query_family :: proc(req: ^Dns_Lookup_Request, type: net.DNS_Record_Type, fa } else { recs, err = net.get_dns_records_from_os(req.hostname, type, context.temp_allocator) } + // Keep any reported resolver failure so the worker can tell a real "no such // host" (empty + .None) from a transient/system error (see dns_error_to_code). - if err != .None do req.last_err = err + if err != .None { + req.last_err = err + } + for rec in recs { addr: net.Address #partial switch r in rec { @@ -177,7 +201,10 @@ dns_query_family :: proc(req: ^Dns_Lookup_Request, type: net.DNS_Record_Type, fa continue } append(&req.results, Dns_Lookup_Result{addr = addr, family = family}) - if first_only do break + + if first_only { + break + } } } @@ -202,30 +229,54 @@ dns_work :: proc(user_data: rawptr) { want4 := req.family == 0 || req.family == 4 want6 := req.family == 0 || req.family == 6 prefer6 := req.order == ORDER_IPV6FIRST + if req.all { // Full enumeration of every requested family, concatenated per order. if prefer6 { - if want6 do dns_query_family(req, .IP6, 6, false) - if want4 do dns_query_family(req, .IP4, 4, false) + if want6 { + dns_query_family(req, .IP6, 6, false) + } + + if want4 { + dns_query_family(req, .IP4, 4, false) + } } else { - if want4 do dns_query_family(req, .IP4, 4, false) - if want6 do dns_query_family(req, .IP6, 6, false) + if want4 { + dns_query_family(req, .IP4, 4, false) + } + + if want6 { + dns_query_family(req, .IP6, 6, false) + } } } else { // Single address: first of the preferred family, else fall back. Querying // the preferred family first also avoids the second query in the common case. if prefer6 { - if want6 do dns_query_family(req, .IP6, 6, true) - if len(req.results) == 0 && want4 do dns_query_family(req, .IP4, 4, true) + if want6 { + dns_query_family(req, .IP6, 6, true) + } + + if len(req.results) == 0 && want4 { + dns_query_family(req, .IP4, 4, true) + } } else { - if want4 do dns_query_family(req, .IP4, 4, true) - if len(req.results) == 0 && want6 do dns_query_family(req, .IP6, 6, true) + if want4 { + dns_query_family(req, .IP4, 4, true) + } + + if len(req.results) == 0 && want6 { + dns_query_family(req, .IP6, 6, true) + } } } } req.ok = len(req.results) > 0 - if !req.ok do req.err_code = dns_error_to_code(req.last_err) + + if !req.ok { + req.err_code = dns_error_to_code(req.last_err) + } } // dns_error_to_code maps a failed lookup to a Node getaddrinfo error code. A real @@ -252,6 +303,7 @@ dns_lookup_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { ctx := req.ctx code_val, addrs_val: jsc.JSValueRef + if req.ok { code_val = jsc.JSValueMakeNull(ctx) // Set each entry into the array as it is built — never park unrooted JSValueRefs in @@ -275,6 +327,7 @@ dns_lookup_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { cb_args := [2]jsc.JSValueRef{code_val, addrs_val} exception: jsc.JSValueRef invoke_user_callback(ctx, req.callback, raw_data(cb_args[:]), 2, &exception) + if exception != nil { report_uncaught(ctx, exception) mark_async_failed(ctx) @@ -291,11 +344,15 @@ dns_lookup_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // teardown, before it fires). It never races a worker: the pool disposes a job a // worker took only once that worker has exited. dns_request_free :: proc(req: ^Dns_Lookup_Request) { - if req == nil do return + if req == nil { + return + } + if req.callback != nil { jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) req.callback = nil } + delete(req.results) delete(req.hostname, req.allocator) free(req, req.allocator) @@ -318,6 +375,7 @@ dns_dispose :: proc(user_data: rawptr) { // before the page releases its context. dns_work never reads req.callback or req.ctx. dns_cancel :: proc(user_data: rawptr) { req := cast(^Dns_Lookup_Request)user_data + if req.callback != nil { jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) req.callback = nil diff --git a/pkg/runtime/environment.odin b/pkg/runtime/environment.odin index 491271e6..0e02401c 100644 --- a/pkg/runtime/environment.odin +++ b/pkg/runtime/environment.odin @@ -124,9 +124,16 @@ remove_node_globals :: proc(ctx: jsc.JSContextRef, global_obj: jsc.JSObjectRef) inject_global_string :: proc(ctx: jsc.JSContextRef, global_obj: jsc.JSObjectRef, name: string, value: string) { c_name, c_name_err := strings.clone_to_cstring(name, context.temp_allocator) - if c_name_err != nil do return + + if c_name_err != nil { + return + } + c_value, c_value_err := strings.clone_to_cstring(value, context.temp_allocator) - if c_value_err != nil do return + + if c_value_err != nil { + return + } js_name := jsc.JSStringCreateWithUTF8CString(c_name) js_val_str := jsc.JSStringCreateWithUTF8CString(c_value) @@ -150,18 +157,29 @@ eval_source_value :: proc( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { script := js_string_from_string(source) - if script == nil do return jsc.JSValueMakeUndefined(ctx) + + if script == nil { + return jsc.JSValueMakeUndefined(ctx) + } + defer jsc.JSStringRelease(script) source_url := js_string_from_string(source_name) - defer if source_url != nil do jsc.JSStringRelease(source_url) + defer if source_url != nil { + jsc.JSStringRelease(source_url) + } child_exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, script, nil, source_url, 1, &child_exception) + if child_exception != nil && exception != nil { exception^ = child_exception } - if value == nil do return jsc.JSValueMakeUndefined(ctx) + + if value == nil { + return jsc.JSValueMakeUndefined(ctx) + } + return value } @@ -178,18 +196,22 @@ esm_wrap_source :: proc( bool, ) { state := get_state_from_ctx(ctx) + if state == nil || state.esm_transform == nil { if exception != nil { exception^ = make_js_error(ctx, "ESM transform unavailable") } + return "", false } abs_path, abs_err := filepath.abs(filename, context.temp_allocator) + if abs_err != os.ERROR_NONE { // Fall back to the path as given when abs resolution fails. abs_path = filename } + dir := filepath.dir(abs_path) url := esm_file_url(abs_path) @@ -208,18 +230,25 @@ esm_wrap_source :: proc( raw_data(args[:]), &call_exception, ) + if call_exception != nil { - if exception != nil do exception^ = call_exception + if exception != nil { + exception^ = call_exception + } + return "", false } wrapped, allocated := jsc_value_to_string_or_default(ctx, result) + if !allocated { if exception != nil { exception^ = make_js_error(ctx, "ESM transform produced no output") } + return "", false } + return wrapped, true } @@ -229,12 +258,20 @@ esm_file_url :: proc(abs_path: string) -> string { slashed, _ := strings.replace_all(abs_path, "\\", "/", context.temp_allocator) parts := [?]string{"file:///", slashed} result, err := strings.concatenate(parts[:], context.temp_allocator) - if err != nil do return abs_path + + if err != nil { + return abs_path + } + return result } else { parts := [?]string{"file://", abs_path} result, err := strings.concatenate(parts[:], context.temp_allocator) - if err != nil do return abs_path + + if err != nil { + return abs_path + } + return result } } @@ -294,20 +331,32 @@ js_quote :: proc(value: string) -> string { // sees the partial exports, like Node) and again after (the body may reassign // module.exports). register_entry_module :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, source_name: string) { - if state == nil do return + if state == nil { + return + } + abs_path, abs_err := filepath.abs(source_name, context.temp_allocator) - if abs_err != os.ERROR_NONE || len(abs_path) == 0 do return + + if abs_err != os.ERROR_NONE || len(abs_path) == 0 { + return + } global_obj := jsc.JSContextGetGlobalObject(ctx) mod_name := jsc.JSStringCreateWithUTF8CString("module") defer jsc.JSStringRelease(mod_name) mod_val := jsc.JSObjectGetProperty(ctx, global_obj, mod_name, nil) - if !jsc.JSValueIsObject(ctx, mod_val) do return + + if !jsc.JSValueIsObject(ctx, mod_val) { + return + } exp_name := jsc.JSStringCreateWithUTF8CString("exports") defer jsc.JSStringRelease(exp_name) exports := jsc.JSObjectGetProperty(ctx, cast(jsc.JSObjectRef)mod_val, exp_name, nil) - if exports == nil do return + + if exports == nil { + return + } module_cache_set(ctx, state, abs_path, exports) } @@ -326,7 +375,10 @@ js_string_value :: proc(ctx: jsc.JSContextRef, value: string) -> jsc.JSValueRef } c_value, err := strings.clone_to_cstring(value, context.temp_allocator) - if err != nil do return jsc.JSValueMakeUndefined(ctx) + + if err != nil { + return jsc.JSValueMakeUndefined(ctx) + } js_str := jsc.JSStringCreateWithUTF8CString(c_value) defer jsc.JSStringRelease(js_str) @@ -340,7 +392,10 @@ js_string_value :: proc(ctx: jsc.JSContextRef, value: string) -> jsc.JSValueRef // at the first 0x00), this preserves the full content — needed for SQLite TEXT, // where a NUL is a legal byte. js_string_from_bytes :: proc(ctx: jsc.JSContextRef, value: string) -> jsc.JSValueRef { - if len(value) == 0 do return js_string_value(ctx, "") + if len(value) == 0 { + return js_string_value(ctx, "") + } + // ASCII (NULs included — this builder's contract preserves them) copies // straight into 8-bit string storage. if bytes_all_ascii(transmute([]byte)value) { @@ -350,6 +405,7 @@ js_string_from_bytes :: proc(ctx: jsc.JSContextRef, value: string) -> jsc.JSValu return jsc.JSValueMakeString(ctx, str) } } + runes := utf8.string_to_runes(value, context.temp_allocator) // Each rune is at most two UTF-16 code units (a surrogate pair). units := make([]u16, len(runes) * 2, context.temp_allocator) @@ -363,9 +419,15 @@ js_string_from_bytes :: proc(ctx: jsc.JSContextRef, value: string) -> jsc.JSValu // Pure codecs live in pkg/jsc/string_utf8.odin; these wrappers allocate. js_string_ref_to_utf8_owned :: proc(js_string: jsc.JSStringRef) -> (string, bool) { - if js_string == nil do return "", false + if js_string == nil { + return "", false + } + length := int(jsc.JSStringGetLength(js_string)) - if length == 0 do return "", false + + if length == 0 { + return "", false + } // 8-bit storage read directly (GetCharactersPtr would widen the whole string // to UTF-16 first). @@ -374,7 +436,11 @@ js_string_ref_to_utf8_owned :: proc(js_string: jsc.JSStringRef) -> (string, bool } chars := jsc.JSStringGetCharactersPtr(js_string) - if chars == nil do return "", false + + if chars == nil { + return "", false + } + return utf16_to_utf8_owned(chars, length) } @@ -387,9 +453,12 @@ latin1_to_utf8_owned :: proc(s8: []byte) -> (string, bool) { copy(buffer, s8) return string(buffer), true } + n := len(s8) for b in s8 { - if b >= 0x80 do n += 1 + if b >= 0x80 { + n += 1 + } } buffer := make([]byte, n, context.allocator) o := 0 @@ -416,22 +485,31 @@ utf16_to_utf8_owned :: proc(chars: [^]jsc.JSChar, length: int) -> (string, bool) break } } + if ascii { buffer := make([]byte, length, context.allocator) - for i in 0 ..< length do buffer[i] = byte(chars[i]) + for i in 0 ..< length { + buffer[i] = byte(chars[i]) + } return string(buffer), true } n := jsc.utf16_js_utf8_byte_len(chars, length) - if n <= 0 do return "", false + + if n <= 0 { + return "", false + } + buffer := make([]byte, n, context.allocator) // Exact-size buffer: the capped writer never truncates here (need always // fits), so it yields the same bytes as an uncapped encode. written := jsc.utf16_js_to_utf8_capped(chars, length, buffer) + if written != n { delete(buffer, context.allocator) return "", false } + return string(buffer), true } @@ -442,16 +520,27 @@ jsc_value_to_string_or_default :: proc(ctx: jsc.JSContextRef, value: jsc.JSValue // Flat string values resolve with no C-API call; everything else (ropes, // non-strings needing coercion) goes through JSValueToStringCopy. if s8, ok := jsc.value_chars8(ctx, value); ok { - if len(s8) == 0 do return "", false + if len(s8) == 0 { + return "", false + } + return latin1_to_utf8_owned(s8) } + if s16, ok := jsc.value_chars16(ctx, value); ok { - if len(s16) == 0 do return "", false + if len(s16) == 0 { + return "", false + } + return utf16_to_utf8_owned(raw_data(s16), len(s16)) } js_string := jsc.JSValueToStringCopy(ctx, value, nil) - if js_string == nil do return "", false + + if js_string == nil { + return "", false + } + defer jsc.JSStringRelease(js_string) return js_string_ref_to_utf8_owned(js_string) } diff --git a/pkg/runtime/errors.odin b/pkg/runtime/errors.odin index c6c6469a..6606bf62 100644 --- a/pkg/runtime/errors.odin +++ b/pkg/runtime/errors.odin @@ -34,10 +34,14 @@ ERROR_INTRINSIC_NAMES := [?]string { // different object (Node's internal errors are likewise immune to user globals). // The JSValueIs* / JSObjectIsConstructor predicates are ABI-safe (#159). capture_error_intrinsics :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + global := jsc.JSContextGetGlobalObject(ctx) for name in ERROR_INTRINSIC_NAMES { ctor := get_named(ctx, global, name) + if ctor != nil && jsc.JSValueIsObject(ctx, ctor) && jsc.JSObjectIsConstructor(ctx, cast(jsc.JSObjectRef)ctor) { jsc.JSValueProtect(ctx, ctor) state.error_intrinsics[name] = ctor @@ -52,7 +56,11 @@ capture_error_intrinsics :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { @(private = "file") captured_error_ctor :: proc(ctx: jsc.JSContextRef, name: string) -> jsc.JSValueRef { state := get_state_from_ctx(ctx) - if state == nil do return nil + + if state == nil { + return nil + } + return state.error_intrinsics[name] } @@ -77,9 +85,13 @@ make_native_error :: proc( args := [1]jsc.JSValueRef{msg} err: jsc.JSValueRef + if ctor := captured_error_ctor(ctx, ctor_name); ctor != nil { built := jsc.JSObjectCallAsConstructor(ctx, cast(jsc.JSObjectRef)ctor, 1, raw_data(args[:]), nil) - if built != nil do err = cast(jsc.JSValueRef)built + + if built != nil { + err = cast(jsc.JSValueRef)built + } } if err == nil { @@ -87,6 +99,7 @@ make_native_error :: proc( // user-reachable global — JSObjectMakeError is a protected intrinsic. base := jsc.JSObjectMakeError(ctx, 1, raw_data(args[:]), nil) err = cast(jsc.JSValueRef)base + if ctor_name != "Error" && jsc.JSValueIsObject(ctx, err) { set_named(ctx, cast(jsc.JSObjectRef)err, "name", js_string_value(ctx, ctor_name)) } @@ -95,6 +108,7 @@ make_native_error :: proc( if len(code) > 0 && jsc.JSValueIsObject(ctx, err) { set_named(ctx, cast(jsc.JSObjectRef)err, "code", js_string_value(ctx, code)) } + return err } @@ -169,7 +183,11 @@ determine_received_type :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> if value_is_bigint(ctx, value) { s, allocated := value_to_string(ctx, value) out := fmt.tprintf("type bigint (%sn)", s) - if allocated do delete(s) + + if allocated { + delete(s) + } + return out } #partial switch jsc.JSValueGetType(ctx, value) { @@ -184,30 +202,56 @@ determine_received_type :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> case .Boolean: s, allocated := value_to_string(ctx, value) out := fmt.tprintf("type boolean (%s)", s) - if allocated do delete(s) + + if allocated { + delete(s) + } + return out case .Number: s, allocated := value_to_string(ctx, value) out := fmt.tprintf("type number (%s)", s) - if allocated do delete(s) + + if allocated { + delete(s) + } + return out case .Object: obj := cast(jsc.JSObjectRef)value + if jsc.JSObjectIsFunction(ctx, obj) { n, allocated := value_to_string(ctx, get_named(ctx, obj, "name")) out := "function (anonymous)" - if len(n) > 0 do out = fmt.tprintf("function %s", n) - if allocated do delete(n) + + if len(n) > 0 { + out = fmt.tprintf("function %s", n) + } + + if allocated { + delete(n) + } + return out } + ctor := get_named(ctx, obj, "constructor") + if ctor != nil && jsc.JSValueIsObject(ctx, ctor) { cn, allocated := value_to_string(ctx, get_named(ctx, cast(jsc.JSObjectRef)ctor, "name")) out := "type object" - if len(cn) > 0 do out = fmt.tprintf("an instance of %s", cn) - if allocated do delete(cn) + + if len(cn) > 0 { + out = fmt.tprintf("an instance of %s", cn) + } + + if allocated { + delete(cn) + } + return out } + return "type object" } return "type object" @@ -221,7 +265,9 @@ determine_received_type :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> // object* (Object(10n)) is a real object and is handled as such, not here. @(private = "file") value_is_bigint :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> bool { - if jsc.JSValueIsObject(ctx, value) do return false + if jsc.JSValueIsObject(ctx, value) { + return false + } #partial switch jsc.JSValueGetType(ctx, value) { case .Undefined, .Null, .Boolean, .Number, .String, .Symbol: return false diff --git a/pkg/runtime/eventloop/eventloop_close_running_test.odin b/pkg/runtime/eventloop/eventloop_close_running_test.odin index 36e44330..ae6c95ad 100644 --- a/pkg/runtime/eventloop/eventloop_close_running_test.odin +++ b/pkg/runtime/eventloop/eventloop_close_running_test.odin @@ -57,7 +57,10 @@ close_begin_never_disposes_a_job_its_worker_is_running :: proc(t: ^testing.T) { job := new(Held_Job, heap) testing.expect(t, pool_submit(loop, held_work, held_done, job, held_dispose, held_cancel)) deadline := time.tick_add(time.tick_now(), 2 * time.Second) - for !sync.atomic_load(&job.started) && time.tick_diff(time.tick_now(), deadline) > 0 do time.sleep(time.Millisecond) + for !sync.atomic_load(&job.started) && time.tick_diff(time.tick_now(), deadline) > 0 { + time.sleep(time.Millisecond) + } + if !sync.atomic_load(&job.started) { // Still queued: close_begin disposes it outright, and no worker holds it. destroy(loop) @@ -68,6 +71,7 @@ close_begin_never_disposes_a_job_its_worker_is_running :: proc(t: ^testing.T) { busy := close_begin(loop) disposed := sync.atomic_load(&job.dispose) + if disposed != 0 || !busy { // Leave the worker blocked: see the file comment. testing.expectf( @@ -79,11 +83,14 @@ close_begin_never_disposes_a_job_its_worker_is_running :: proc(t: ^testing.T) { ) return } + testing.expect_value(t, sync.atomic_load(&job.cancel), 1) sync.sema_post(&job.gate) deadline = time.tick_add(time.tick_now(), 3 * time.Second) - for !close_ready(loop) && time.tick_diff(time.tick_now(), deadline) > 0 do time.sleep(time.Millisecond) + for !close_ready(loop) && time.tick_diff(time.tick_now(), deadline) > 0 { + time.sleep(time.Millisecond) + } close_finish(loop) free(loop, heap) testing.expect_value(t, sync.atomic_load(&job.dispose), 1) diff --git a/pkg/runtime/eventloop/eventloop_close_test.odin b/pkg/runtime/eventloop/eventloop_close_test.odin index 09eb565c..ad500709 100644 --- a/pkg/runtime/eventloop/eventloop_close_test.odin +++ b/pkg/runtime/eventloop/eventloop_close_test.odin @@ -60,7 +60,10 @@ Releaser :: struct { releaser_proc :: proc(r: ^Releaser) { deadline := time.tick_add(time.tick_now(), r.delay) for time.tick_diff(time.tick_now(), deadline) > 0 { - if sync.atomic_load(&r.stop) do return + if sync.atomic_load(&r.stop) { + return + } + time.sleep(5 * time.Millisecond) } sync.sema_post(&r.job.gate) @@ -70,7 +73,10 @@ releaser_proc :: proc(r: ^Releaser) { wait_started :: proc(job: ^Blocking_Job) -> bool { deadline := time.tick_add(time.tick_now(), 2 * time.Second) for !sync.atomic_load(&job.started) { - if time.tick_diff(time.tick_now(), deadline) <= 0 do return false + if time.tick_diff(time.tick_now(), deadline) <= 0 { + return false + } + time.sleep(time.Millisecond) } return true @@ -92,9 +98,11 @@ close_begin_cancels_a_running_job_without_waiting_for_it :: proc(t: ^testing.T) loop := heap_loop() job: Blocking_Job testing.expect(t, pool_submit(loop, blocking_work, blocking_done, &job, blocking_dispose, blocking_cancel)) + if !wait_started(&job) { testing.fail_now(t, "the worker never started the job") } + rel := Releaser { job = &job, delay = 2 * time.Second, @@ -114,7 +122,9 @@ close_begin_cancels_a_running_job_without_waiting_for_it :: proc(t: ^testing.T) thread.destroy(th) sync.sema_post(&job.gate) deadline := time.tick_add(time.tick_now(), 3 * time.Second) - for !close_ready(loop) && time.tick_diff(time.tick_now(), deadline) > 0 do time.sleep(time.Millisecond) + for !close_ready(loop) && time.tick_diff(time.tick_now(), deadline) > 0 { + time.sleep(time.Millisecond) + } testing.expect(t, close_ready(loop), "workers never reported their exit") close_finish(loop) free(loop, runtime.heap_allocator()) @@ -134,9 +144,11 @@ close_detach_leaves_the_loop_to_its_last_worker :: proc(t: ^testing.T) { loop := heap_loop() job: Blocking_Job testing.expect(t, pool_submit(loop, blocking_work, blocking_done, &job, blocking_dispose, blocking_cancel)) + if !wait_started(&job) { testing.fail_now(t, "the worker never started the job") } + rel := Releaser { job = &job, delay = 2 * time.Second, @@ -168,7 +180,8 @@ close_detach_leaves_the_loop_to_its_last_worker :: proc(t: ^testing.T) { thread.destroy(th) sync.sema_post(&job.gate) deadline := time.tick_add(time.tick_now(), 3 * time.Second) - for sync.atomic_load(&job.dispose) == 0 && time.tick_diff(time.tick_now(), deadline) > 0 do time.sleep(time.Millisecond) + for sync.atomic_load(&job.dispose) == 0 && + time.tick_diff(time.tick_now(), deadline) > 0 {time.sleep(time.Millisecond)} testing.expect_value(t, sync.atomic_load(&job.dispose), 1) testing.expect_value(t, sync.atomic_load(&job.cancel), 1) testing.expect_value(t, job.done, 0) @@ -178,7 +191,11 @@ close_detach_leaves_the_loop_to_its_last_worker :: proc(t: ^testing.T) { now := fd_link(int(pipe_fd)) closed = now != pipe_link delete(now) - if closed do break + + if closed { + break + } + time.sleep(time.Millisecond) } testing.expectf(t, closed, "the detached loop's wakeup pipe (fd %d) was never closed", pipe_fd) @@ -189,6 +206,10 @@ close_detach_leaves_the_loop_to_its_last_worker :: proc(t: ^testing.T) { @(private = "file") fd_link :: proc(fd: int) -> string { target, err := os.read_link(fmt.tprintf("/proc/self/fd/%d", fd), context.allocator) - if err != nil do return "" + + if err != nil { + return "" + } + return target } diff --git a/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin b/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin index 0cf0eb30..c6e012be 100644 --- a/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin +++ b/pkg/runtime/eventloop/eventloop_close_wakeup_test.odin @@ -43,21 +43,28 @@ close_ready_is_announced_on_the_wakeup_pipe :: proc(t: ^testing.T) { job: Quick_Job testing.expect(t, pool_submit(&loop, quick_work, quick_done, &job)) deadline := time.tick_add(time.tick_now(), 2 * time.Second) - for !job.done && time.tick_diff(time.tick_now(), deadline) > 0 do run_once(&loop) + for !job.done && time.tick_diff(time.tick_now(), deadline) > 0 { + run_once(&loop) + } + if !job.done { destroy(&loop) testing.fail_now(t, "the pool job never completed") } pipe_fd, ok := wakeup_fd(&loop) + if !ok { destroy(&loop) testing.fail_now(t, "the loop has no wakeup pipe") } + drain_wakeup(&loop) testing.expect(t, !close_begin(&loop), "close_begin reported a busy worker with none in a job") - for !close_ready(&loop) && time.tick_diff(time.tick_now(), deadline) > 0 do time.sleep(time.Millisecond) + for !close_ready(&loop) && time.tick_diff(time.tick_now(), deadline) > 0 { + time.sleep(time.Millisecond) + } testing.expect(t, close_ready(&loop), "idle workers never counted themselves out") // The last worker writes the pipe just after its count moves; allow it a second. diff --git a/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin b/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin index d4f90aeb..f5739678 100644 --- a/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin +++ b/pkg/runtime/eventloop/eventloop_fd_lifetime_test.odin @@ -38,15 +38,21 @@ failed_platform_init_does_not_double_close :: proc(t: ^testing.T) { // after it, and the canary later reclaims it. probe, probe_err := linux.epoll_create1({.FDCLOEXEC}) testing.expectf(t, probe_err == nil, "could not open a probe descriptor: %v", probe_err) - if probe_err != nil do return + + if probe_err != nil { + return + } + lowest := probe linux.close(probe) saved: linux.RLimit + if get_err := linux.getrlimit(.NOFILE, &saved); get_err != nil { testing.expectf(t, false, "getrlimit failed: %v", get_err) return } + // Room for exactly the two pipe ends: no descriptor may have a number >= cur, // so io_uring_setup and epoll_create1 both fail with EMFILE and platform_init // takes the path under test. @@ -54,6 +60,7 @@ failed_platform_init_does_not_double_close :: proc(t: ^testing.T) { cur = uint(lowest) + 2, max = saved.max, } + if set_err := linux.setrlimit(.NOFILE, &tight); set_err != nil { testing.expectf(t, false, "setrlimit failed: %v", set_err) return @@ -69,10 +76,12 @@ failed_platform_init_does_not_double_close :: proc(t: ^testing.T) { // wakeup_pipe, destroy is about to close THIS descriptor. canary, canary_err := linux.epoll_create1({.FDCLOEXEC}) testing.expectf(t, canary_err == nil, "could not open the canary: %v", canary_err) + if canary_err != nil { destroy(&loop) return } + testing.expectf( t, canary == lowest, @@ -86,5 +95,8 @@ failed_platform_init_does_not_double_close :: proc(t: ^testing.T) { st: linux.Stat fstat_err := linux.fstat(canary, &st) testing.expectf(t, fstat_err == nil, "destroy closed an unrelated descriptor: fstat(canary) -> %v", fstat_err) - if fstat_err == nil do linux.close(canary) + + if fstat_err == nil { + linux.close(canary) + } } diff --git a/pkg/runtime/eventloop/eventloop_proactor_test.odin b/pkg/runtime/eventloop/eventloop_proactor_test.odin index 79b307ba..866f8845 100644 --- a/pkg/runtime/eventloop/eventloop_proactor_test.odin +++ b/pkg/runtime/eventloop/eventloop_proactor_test.odin @@ -52,6 +52,7 @@ make_socketpair :: proc(t: ^testing.T) -> (sv: [2]linux.Fd, ok: bool) { testing.expect(t, false, "socketpair failed") return sv, false } + return sv, true } @@ -61,10 +62,17 @@ make_socketpair :: proc(t: ^testing.T) -> (sv: [2]linux.Fd, ok: bool) { proactor_recv_send_roundtrip :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -83,7 +91,10 @@ proactor_recv_send_roundtrip :: proc(t: ^testing.T) { arm_watchdog(&loop) for i in 0 ..< 5 { - if rec.recv_done && rec.send_done do break + if rec.recv_done && rec.send_done { + break + } + run_once(&loop) } testing.expect(t, rec.send_done, "send did not complete") @@ -99,10 +110,17 @@ proactor_recv_send_roundtrip :: proc(t: ^testing.T) { proactor_recv_short_read :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -115,7 +133,10 @@ proactor_recv_short_read :: proc(t: ^testing.T) { testing.expect(t, submit_send(&loop, uintptr(sv[1]), three[:], proactor_on_send, nil, &rec) != OP_ID_INVALID) arm_watchdog(&loop) for i in 0 ..< 5 { - if rec.recv_done && rec.send_done do break + if rec.recv_done && rec.send_done { + break + } + run_once(&loop) } testing.expect_value(t, rec.recv_res, 3) @@ -128,10 +149,17 @@ proactor_recv_short_read :: proc(t: ^testing.T) { proactor_cancel_op :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -142,7 +170,10 @@ proactor_cancel_op :: proc(t: ^testing.T) { arm_watchdog(&loop) for i in 0 ..< 5 { - if rec.recv_done do break + if rec.recv_done { + break + } + run_once(&loop) } testing.expect(t, rec.recv_done, "cancelled recv did not deliver a terminal completion") @@ -155,15 +186,19 @@ proactor_cancel_op :: proc(t: ^testing.T) { @(test) proactor_dispose_on_destroy :: proc(t: ^testing.T) { loop := init() + if !proactor_available(&loop) { destroy(&loop) return } + sv, sp_ok := make_socketpair(t) + if !sp_ok { destroy(&loop) return } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -182,10 +217,17 @@ proactor_dispose_on_destroy :: proc(t: ^testing.T) { proactor_send_to_closed_peer :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + linux.close(sv[0]) // close the peer; sv[1] sends into a dead connection defer linux.close(sv[1]) @@ -194,7 +236,10 @@ proactor_send_to_closed_peer :: proc(t: ^testing.T) { testing.expect(t, submit_send(&loop, uintptr(sv[1]), msg[:], proactor_on_send, nil, &rec) != OP_ID_INVALID) arm_watchdog(&loop) for i in 0 ..< 5 { - if rec.send_done do break + if rec.send_done { + break + } + run_once(&loop) } testing.expect(t, rec.send_done, "send to closed peer did not complete") @@ -207,10 +252,17 @@ proactor_send_to_closed_peer :: proc(t: ^testing.T) { proactor_nil_callback_rejected :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -247,7 +299,10 @@ proactor_token_encoding :: proc(t: ^testing.T) { proactor_slot_reuse :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } a := uring_op_alloc_slot(&loop, proactor_on_recv, nil, nil) idx := uring_op_token_index(a) @@ -279,10 +334,15 @@ Ring_Rec :: struct { ring_on_recv :: proc(loop: ^Loop, ud: rawptr, res: i32, bid: u16, has_buf: bool, more: bool) { rec := cast(^Ring_Rec)ud rec.res, rec.has_buf, rec.more = res, has_buf, more + if has_buf && res > 0 { rec.got_len = copy(rec.got[:], recv_ring_buf(loop, bid, int(res))) // copy BEFORE recycle } - if has_buf do recv_ring_recycle(loop, bid) + + if has_buf { + recv_ring_recycle(loop, bid) + } + rec.done = true } @@ -292,7 +352,10 @@ ring_pump :: proc(t: ^testing.T, loop: ^Loop, rec: ^Ring_Rec, peer: linux.Fd, ms _, _ = linux.send(peer, transmute([]u8)msg, {}) arm_watchdog(loop) for _ in 0 ..< 64 { - if rec.done do break + if rec.done { + break + } + run_once(loop) } } @@ -301,10 +364,15 @@ ring_pump :: proc(t: ^testing.T, loop: ^Loop, rec: ^Ring_Rec, peer: linux.Fd, ms proactor_ring_recv_recycle :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !bufring_available(&loop) do return // ring unsupported on this kernel — skip + + if !bufring_available(&loop) {return} // ring unsupported on this kernel — skip sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -337,7 +405,10 @@ proactor_ring_recv_recycle :: proc(t: ^testing.T) { testing.expect(t, cancel_op(&loop, id), "cancel of a live multishot must report a queued cancel") arm_watchdog(&loop) for _ in 0 ..< 64 { - if loop.active_io_count == 0 do break + if loop.active_io_count == 0 { + break + } + run_once(&loop) } } else { @@ -348,6 +419,7 @@ proactor_ring_recv_recycle :: proc(t: ^testing.T) { ring_pump(t, &loop, &rec, sv[1], "world") testing.expect_value(t, string(rec.got[:rec.got_len]), "world") } + testing.expect_value(t, loop.active_io_count, 0) } @@ -360,10 +432,17 @@ proactor_ring_recv_recycle :: proc(t: ^testing.T) { proactor_ring_forced_single_shot :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !bufring_available(&loop) do return + + if !bufring_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -394,11 +473,19 @@ ring_fairness_timer :: proc(loop: ^Loop, ud: rawptr) {(cast(^bool)ud)^ = true} proactor_ring_drain_fairness :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !bufring_available(&loop) do return - if !recv_ring_multishot(&loop) do return // the monopolization concern is multishot-specific + + if !bufring_available(&loop) { + return + } + + if !recv_ring_multishot(&loop) {return} // the monopolization concern is multishot-specific sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -408,11 +495,16 @@ proactor_ring_drain_fairness :: proc(t: ^testing.T) { fired := false set_timeout(&loop, ring_fairness_timer, 0, &fired) // already due - for _ in 0 ..< 8 do _, _ = linux.send(sv[1], transmute([]u8)string("ping"), {}) + for _ in 0 ..< 8 { + _, _ = linux.send(sv[1], transmute([]u8)string("ping"), {}) + } arm_watchdog(&loop) for _ in 0 ..< 64 { - if fired && rec.done do break + if fired && rec.done { + break + } + run_once(&loop) } testing.expect(t, rec.done, "multishot recv must deliver under the bounded drain") @@ -421,7 +513,10 @@ proactor_ring_drain_fairness :: proc(t: ^testing.T) { cancel_op(&loop, id) arm_watchdog(&loop) for _ in 0 ..< 64 { - if loop.active_io_count == 0 do break + if loop.active_io_count == 0 { + break + } + run_once(&loop) } testing.expect_value(t, loop.active_io_count, 0) @@ -434,12 +529,19 @@ proactor_ring_drain_fairness :: proc(t: ^testing.T) { proactor_cancel_reports_queued :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } testing.expect(t, !cancel_op(&loop, OP_ID_INVALID), "cancel of OP_ID_INVALID must report no-op") sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -450,7 +552,10 @@ proactor_cancel_reports_queued :: proc(t: ^testing.T) { arm_watchdog(&loop) // drain the terminal -ECANCELED so the slot releases for _ in 0 ..< 64 { - if rec.recv_done do break + if rec.recv_done { + break + } + run_once(&loop) } testing.expect(t, !cancel_op(&loop, id), "cancel of an already-completed op must report no-op") @@ -472,17 +577,27 @@ sendzc_on_complete :: proc(loop: ^Loop, ud: rawptr, res: i32, more: bool) { rec := cast(^Send_Rec)ud rec.calls += 1 rec.last_res = res - if !more do rec.saw_terminal = true + + if !more { + rec.saw_terminal = true + } } @(test) proactor_send_zc_routes_and_accounts :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } sv, sp_ok := make_socketpair(t) - if !sp_ok do return + + if !sp_ok { + return + } + defer linux.close(sv[0]) defer linux.close(sv[1]) @@ -493,9 +608,10 @@ proactor_send_zc_routes_and_accounts :: proc(t: ^testing.T) { testing.expect_value(t, loop.active_io_count, 1) // counted once at submit arm_watchdog(&loop) for _ in 0 ..< 64 { - if loop.active_io_count == 0 do break // drained to the terminal (F_MORE clear) + if loop.active_io_count == 0 {break} // drained to the terminal (F_MORE clear) run_once(&loop) } + testing.expect(t, rec.calls >= 1, "send_cb fired (routed to send_cb, not recv_cb/callback)") testing.expect(t, rec.saw_terminal, "a terminal (more=false) CQE fired") testing.expect_value(t, loop.active_io_count, 0) // released exactly once on the terminal @@ -507,7 +623,10 @@ proactor_send_zc_routes_and_accounts :: proc(t: ^testing.T) { proactor_send_zc_disable :: proc(t: ^testing.T) { loop := init() defer destroy(&loop) - if !proactor_available(&loop) do return + + if !proactor_available(&loop) { + return + } disable_zc(&loop) testing.expect(t, !send_zc_ok(&loop), "disable_zc clears zc_ok") diff --git a/pkg/runtime/eventloop/eventloop_test.odin b/pkg/runtime/eventloop/eventloop_test.odin index 1aad0a7c..4f0e262b 100644 --- a/pkg/runtime/eventloop/eventloop_test.odin +++ b/pkg/runtime/eventloop/eventloop_test.odin @@ -57,6 +57,7 @@ record_and_schedule_immediate :: proc(loop: ^Loop, user_data: rawptr) { record_interval_and_clear_after_two_ticks :: proc(loop: ^Loop, user_data: rawptr) { rec := cast(^Recorder)user_data append(&rec.events, 1) + if len(rec.events) == 2 { clear_interval(loop, rec.interval_id) } @@ -626,7 +627,10 @@ pool_test_work :: proc(user_data: rawptr) { // pool_test_done runs ON the loop thread and records the off-loop result. pool_test_done :: proc(loop: ^Loop, user_data: rawptr) { job := cast(^Pool_Test_Job)user_data - if job.rec != nil do append(&job.rec.events, job.computed) + + if job.rec != nil { + append(&job.rec.events, job.computed) + } } @(test) @@ -705,23 +709,31 @@ threadpool_ring_preserves_fifo_across_grow_and_wrap :: proc(t: ^testing.T) { // region is wrapped (the unwrap-copy path). Every job must dequeue exactly once in // submit order. (pool_ring_* are pointer-only; no Loop/threads needed.) pool := Thread_Pool{} - defer if pool.pending != nil do delete(pool.pending) + defer if pool.pending != nil { + delete(pool.pending) + } jobs: [20]Pool_Job expect := 0 pushed := 0 // Grow 0 -> 8 and fill. - for ; pushed < 8; pushed += 1 do pool_ring_push(&pool, &jobs[pushed], context.allocator) + for ; pushed < 8; pushed += 1 { + pool_ring_push(&pool, &jobs[pushed], context.allocator) + } // Drain 6: head advances to 6, two live entries remain. for _ in 0 ..< 6 { testing.expect(t, pool_ring_pop(&pool) == &jobs[expect], "fifo before wrap") expect += 1 } // Refill to capacity: the live region now wraps past the end of the 8-slot backing. - for ; pushed < 14; pushed += 1 do pool_ring_push(&pool, &jobs[pushed], context.allocator) + for ; pushed < 14; pushed += 1 { + pool_ring_push(&pool, &jobs[pushed], context.allocator) + } // Push past capacity: growth happens while the live region is wrapped (8 -> 16). - for ; pushed < 20; pushed += 1 do pool_ring_push(&pool, &jobs[pushed], context.allocator) + for ; pushed < 20; pushed += 1 { + pool_ring_push(&pool, &jobs[pushed], context.allocator) + } // Drain everything: exactly once, still in submit order. for pool.pending_count > 0 { testing.expect(t, pool_ring_pop(&pool) == &jobs[expect], "fifo after wrap+grow") @@ -907,18 +919,33 @@ io_probe_cb :: proc(loop: ^Loop, user_data: rawptr) { watch_fd_fires_on_readable_socket :: proc(t: ^testing.T) { // A connected loopback TCP pair: write on the client, watch the server end. listener, lerr := net.listen_tcp(net.Endpoint{address = net.IP4_Loopback, port = 0}) - if !testing.expect_value(t, lerr, nil) do return + + if !testing.expect_value(t, lerr, nil) { + return + } + defer net.close(listener) bound, berr := net.bound_endpoint(listener) - if !testing.expect_value(t, berr, nil) do return + + if !testing.expect_value(t, berr, nil) { + return + } client, cerr := net.dial_tcp_from_endpoint(net.Endpoint{address = net.IP4_Loopback, port = bound.port}) - if !testing.expect_value(t, cerr, nil) do return + + if !testing.expect_value(t, cerr, nil) { + return + } + defer net.close(client) server, _, aerr := net.accept_tcp(listener) - if !testing.expect_value(t, aerr, nil) do return + + if !testing.expect_value(t, aerr, nil) { + return + } + defer net.close(server) loop := init(real_time = true) @@ -938,12 +965,16 @@ watch_fd_fires_on_readable_socket :: proc(t: ^testing.T) { if !testing.expect(t, watch_fd(&loop, &watcher), "watch_fd should accept the socket") { return } + testing.expect_value(t, loop.active_io_count, 1) // Make the server end readable, then drive the loop. The callback fires and // unwatches, dropping active_io_count to 0 so run_until_idle returns. _, serr := net.send_tcp(client, {42}) - if !testing.expect_value(t, serr, nil) do return + + if !testing.expect_value(t, serr, nil) { + return + } run_until_idle(&loop) @@ -957,16 +988,27 @@ watch_fd_fires_on_readable_socket :: proc(t: ^testing.T) { // caller closes client and server. ok=false (sockets zeroed) on any setup failure. connect_loopback_pair :: proc(t: ^testing.T) -> (client, server: net.TCP_Socket, ok: bool) { listener, lerr := net.listen_tcp(net.Endpoint{address = net.IP4_Loopback, port = 0}) - if !testing.expect_value(t, lerr, nil) do return + + if !testing.expect_value(t, lerr, nil) { + return + } + defer net.close(listener) bound, berr := net.bound_endpoint(listener) - if !testing.expect_value(t, berr, nil) do return + + if !testing.expect_value(t, berr, nil) { + return + } dialed, cerr := net.dial_tcp_from_endpoint(net.Endpoint{address = net.IP4_Loopback, port = bound.port}) - if !testing.expect_value(t, cerr, nil) do return + + if !testing.expect_value(t, cerr, nil) { + return + } accepted, _, aerr := net.accept_tcp(listener) + if !testing.expect_value(t, aerr, nil) { net.close(dialed) return @@ -988,7 +1030,11 @@ noop_io_cb :: proc(loop: ^Loop, user_data: rawptr) {} @(test) io_count_accounting_is_idempotent :: proc(t: ^testing.T) { client, server, ok := connect_loopback_pair(t) - if !ok do return + + if !ok { + return + } + defer net.close(client) defer net.close(server) @@ -1026,6 +1072,7 @@ Immediate_Starvation :: struct { starvation_immediate_cb :: proc(loop: ^Loop, user_data: rawptr) { st := cast(^Immediate_Starvation)user_data st.chain_len += 1 + // Keep an immediate perpetually pending until the I/O watcher fires. If a // did_work tick skips the poll phase entirely (the pre-fix behavior), the // watcher never fires and this chain never ends. @@ -1048,7 +1095,11 @@ starvation_io_cb :: proc(loop: ^Loop, user_data: rawptr) { @(test) immediate_chain_does_not_starve_io :: proc(t: ^testing.T) { client, server, ok := connect_loopback_pair(t) - if !ok do return + + if !ok { + return + } + defer net.close(client) defer net.close(server) @@ -1066,12 +1117,18 @@ immediate_chain_does_not_starve_io :: proc(t: ^testing.T) { } st.watcher = &w - if !testing.expect(t, watch_fd(&loop, &w)) do return + if !testing.expect(t, watch_fd(&loop, &w)) { + return + } // Make the server end readable, then give the loopback byte time to land so the // very first non-blocking poll observes it. _, serr := net.send_tcp(client, {7}) - if !testing.expect_value(t, serr, nil) do return + + if !testing.expect_value(t, serr, nil) { + return + } + time.sleep(20 * time.Millisecond) set_immediate(&loop, starvation_immediate_cb, &st) @@ -1159,7 +1216,11 @@ stop_watch_cb :: proc(loop: ^Loop, user_data: rawptr) { @(test) unwatch_fd_drops_stale_io_completion :: proc(t: ^testing.T) { client, server, ok := connect_loopback_pair(t) - if !ok do return + + if !ok { + return + } + defer net.close(client) defer net.close(server) @@ -1174,13 +1235,20 @@ unwatch_fd_drops_stale_io_completion :: proc(t: ^testing.T) { user_data = &counter, } - if !testing.expect(t, watch_fd(&loop, &w)) do return + if !testing.expect(t, watch_fd(&loop, &w)) { + return + } + testing.expect_value(t, loop.active_io_count, 1) // Make the watched fd readable, but do NOT drive the loop: the completion is now // pending in the backend but unobserved. _, serr := net.send_tcp(client, {1}) - if !testing.expect_value(t, serr, nil) do return + + if !testing.expect_value(t, serr, nil) { + return + } + time.sleep(20 * time.Millisecond) // Unwatch before the completion is drained, leaving the callback set. @@ -1202,7 +1270,11 @@ unwatch_fd_drops_stale_io_completion :: proc(t: ^testing.T) { @(test) rewatch_after_unwatch_dispatches_live_watcher :: proc(t: ^testing.T) { client, server, ok := connect_loopback_pair(t) - if !ok do return + + if !ok { + return + } + defer net.close(client) defer net.close(server) @@ -1217,9 +1289,16 @@ rewatch_after_unwatch_dispatches_live_watcher :: proc(t: ^testing.T) { user_data = &stale, } - if !testing.expect(t, watch_fd(&loop, &w)) do return + if !testing.expect(t, watch_fd(&loop, &w)) { + return + } + _, serr := net.send_tcp(client, {1}) - if !testing.expect_value(t, serr, nil) do return + + if !testing.expect_value(t, serr, nil) { + return + } + time.sleep(20 * time.Millisecond) // Pause: clear the callback (as the fetch transport does) and unwatch, then drain @@ -1238,7 +1317,10 @@ rewatch_after_unwatch_dispatches_live_watcher :: proc(t: ^testing.T) { w.callback = stop_watch_cb w.user_data = &live w.mode = .Read - if !testing.expect(t, watch_fd(&loop, &w)) do return + + if !testing.expect(t, watch_fd(&loop, &w)) { + return + } run_until_idle(&loop, 64) @@ -1253,7 +1335,11 @@ rewatch_after_unwatch_dispatches_live_watcher :: proc(t: ^testing.T) { @(test) repeated_unwatch_never_dispatches_stale :: proc(t: ^testing.T) { client, server, ok := connect_loopback_pair(t) - if !ok do return + + if !ok { + return + } + defer net.close(client) defer net.close(server) @@ -1269,11 +1355,18 @@ repeated_unwatch_never_dispatches_stale :: proc(t: ^testing.T) { } _, serr := net.send_tcp(client, {1}) - if !testing.expect_value(t, serr, nil) do return + + if !testing.expect_value(t, serr, nil) { + return + } + time.sleep(20 * time.Millisecond) for _ in 0 ..< 8 { - if !testing.expect(t, watch_fd(&loop, &w)) do return + if !testing.expect(t, watch_fd(&loop, &w)) { + return + } + testing.expect(t, unwatch_fd(&loop, &w)) platform_poll(&loop, 5) } @@ -1300,10 +1393,12 @@ rearm_self_cb :: proc(loop: ^Loop, user_data: rawptr) { s := cast(^Rearm_Self)user_data s.fired += 1 unwatch_fd(loop, s.watcher) + if s.fired >= s.limit { s.watcher.callback = nil // stop: no re-watch, loop drains to idle return } + watch_fd(loop, s.watcher) } @@ -1314,7 +1409,11 @@ rearm_self_cb :: proc(loop: ^Loop, user_data: rawptr) { @(test) rewatch_within_callback_keeps_watcher_live :: proc(t: ^testing.T) { client, server, ok := connect_loopback_pair(t) - if !ok do return + + if !ok { + return + } + defer net.close(client) defer net.close(server) @@ -1324,7 +1423,11 @@ rewatch_within_callback_keeps_watcher_live :: proc(t: ^testing.T) { // Make the fd permanently readable (the byte is never consumed), so each fresh // poll completes and the watcher keeps firing until it stops itself. _, serr := net.send_tcp(client, {1}) - if !testing.expect_value(t, serr, nil) do return + + if !testing.expect_value(t, serr, nil) { + return + } + time.sleep(20 * time.Millisecond) s := Rearm_Self { @@ -1339,7 +1442,10 @@ rewatch_within_callback_keeps_watcher_live :: proc(t: ^testing.T) { } s.watcher = &w - if !testing.expect(t, watch_fd(&loop, &w)) do return + if !testing.expect(t, watch_fd(&loop, &w)) { + return + } + run_until_idle(&loop, 256) testing.expect_value(t, s.fired, 3) // fired exactly limit times across re-arms @@ -1382,7 +1488,9 @@ timer_index_consistent_after_siftup_and_cancel :: proc(t: ^testing.T) { ids: [8]Timer_ID // Descending delays: each insert is the new minimum, sifting to the root and pushing // the rest down — every insert moves existing entries. - for k in 0 ..< 8 do ids[k] = set_timeout(&loop, record, u64((8 - k) * 1000), &rec, count_dispose) + for k in 0 ..< 8 { + ids[k] = set_timeout(&loop, record, u64((8 - k) * 1000), &rec, count_dispose) + } check_timer_index(t, &loop) testing.expect_value(t, len(loop.timers), 8) @@ -1406,11 +1514,15 @@ timer_cancel_removes_eagerly_bounding_memory :: proc(t: ^testing.T) { N :: 200 ids: [N]Timer_ID - for k in 0 ..< N do ids[k] = set_timeout(&loop, record, 1_000_000, &rec, count_dispose) + for k in 0 ..< N { + ids[k] = set_timeout(&loop, record, 1_000_000, &rec, count_dispose) + } testing.expect_value(t, len(loop.timers), N) testing.expect_value(t, len(loop.timer_index), N) - for k in 0 ..< N do testing.expect(t, clear_timeout(&loop, ids[k])) + for k in 0 ..< N { + testing.expect(t, clear_timeout(&loop, ids[k])) + } testing.expect_value(t, len(loop.timers), 0) // not N tombstones testing.expect_value(t, len(loop.timer_index), 0) testing.expect_value(t, rec.dispose_count, N) @@ -1427,7 +1539,7 @@ interval_rearm_then_external_cancel :: proc(t: ^testing.T) { defer delete(rec.events) id := set_interval(&loop, record, 0, &rec, count_dispose) - for _ in 0 ..< 3 do run_once(&loop) // fire + re-arm a few times + for _ in 0 ..< 3 {run_once(&loop)} // fire + re-arm a few times testing.expect(t, len(rec.events) >= 1) check_timer_index(t, &loop) @@ -1452,6 +1564,7 @@ timer_index_invariant_under_random_churn :: proc(t: ^testing.T) { for _ in 0 ..< 1500 { r := test_lcg(&seed) + if len(live) == 0 || (r & 1) == 0 { id := set_timeout(&loop, record, u64(r % 100000 + 1), &rec, count_dispose) append(&live, id) @@ -1460,6 +1573,7 @@ timer_index_invariant_under_random_churn :: proc(t: ^testing.T) { testing.expect(t, clear_timeout(&loop, live[pick])) unordered_remove(&live, pick) } + if len(loop.timers) != len(loop.timer_index) { testing.expect_value(t, len(loop.timer_index), len(loop.timers)) return @@ -1467,7 +1581,9 @@ timer_index_invariant_under_random_churn :: proc(t: ^testing.T) { } check_timer_index(t, &loop) testing.expect_value(t, len(loop.timers), len(live)) - for id in live do clear_timeout(&loop, id) + for id in live { + clear_timeout(&loop, id) + } testing.expect_value(t, len(loop.timers), 0) testing.expect_value(t, len(loop.timer_index), 0) } diff --git a/pkg/runtime/eventloop/loop.odin b/pkg/runtime/eventloop/loop.odin index a955dd1e..e6daa2d3 100644 --- a/pkg/runtime/eventloop/loop.odin +++ b/pkg/runtime/eventloop/loop.odin @@ -215,7 +215,11 @@ init :: proc(allocator := context.allocator, real_time := false) -> Loop { // started. Only meaningful in real_time mode. real_now_ms :: proc(loop: ^Loop) -> u64 { elapsed := time.duration_milliseconds(time.tick_since(loop.start_tick)) - if elapsed < 0 do return 0 + + if elapsed < 0 { + return 0 + } + return u64(elapsed) } @@ -338,16 +342,23 @@ close_ready :: proc(loop: ^Loop) -> bool { // calling thread itself, since Odin sets `Done` after the thread proc returns. close_detach :: proc(loop: ^Loop) -> (detached: bool) { pool := &loop.pool + if pool.started { sync.lock(&pool.mutex) + if pool.exited < len(pool.threads) { pool.detached = true detached = true } + // From the unlock on, the last worker may free the loop at any moment. sync.unlock(&pool.mutex) } - if !detached do close_finish(loop) + + if !detached { + close_finish(loop) + } + return } @@ -423,7 +434,10 @@ async_cancel :: proc(loop: ^Loop) { // (passed to init) must therefore be thread-safe — the default heap allocator is. // Do not back a loop with a non-thread-safe arena if any worker calls post_async. post_async :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil) { - if callback == nil do return + if callback == nil { + return + } + sync.lock(&loop.async_mutex) append(&loop.async_queue, Task{callback = callback, user_data = user_data}) sync.unlock(&loop.async_mutex) @@ -434,10 +448,12 @@ post_async :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil) { // in-flight count per completion. Returns true if any ran. drain_async :: proc(loop: ^Loop) -> bool { sync.lock(&loop.async_mutex) + if len(loop.async_queue) == 0 { sync.unlock(&loop.async_mutex) return false } + // Swap producer queue with the scratch buffer (O(1)) so callbacks — which may // post more async work — run without holding the lock. loop.async_queue, loop.async_scratch = loop.async_scratch, loop.async_queue @@ -536,6 +552,7 @@ queue_next_tick :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil if callback == nil { return } + append(&loop.next_ticks, Task{callback = callback, user_data = user_data, seq = next_sequence(loop)}) } @@ -543,6 +560,7 @@ queue_microtask :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil if callback == nil { return } + append(&loop.microtasks, Task{callback = callback, user_data = user_data, seq = next_sequence(loop)}) } @@ -570,6 +588,7 @@ set_immediate :: proc(loop: ^Loop, callback: Callback, user_data: rawptr = nil, if callback == nil { return 0 } + id := next_handle_id(loop) append( &loop.immediates, @@ -590,6 +609,7 @@ queue_io_callback :: proc( if callback == nil { return 0 } + id := next_handle_id(loop) append( &loop.io_callbacks, @@ -604,6 +624,7 @@ queue_close_callback :: proc(loop: ^Loop, callback: Callback, user_data: rawptr if callback == nil { return } + id := next_handle_id(loop) append(&loop.close_callbacks, Task{id = id, callback = callback, user_data = user_data, seq = next_sequence(loop)}) } @@ -616,6 +637,7 @@ timer_ref :: proc(loop: ^Loop, id: Timer_ID) { if loop.timers[idx].unreffed && !loop.timers[idx].cancelled { loop.reffed_timer_count += 1 } + loop.timers[idx].unreffed = false } } @@ -626,6 +648,7 @@ timer_unref :: proc(loop: ^Loop, id: Timer_ID) { if !loop.timers[idx].unreffed && !loop.timers[idx].cancelled { loop.reffed_timer_count -= 1 } + loop.timers[idx].unreffed = true } } @@ -679,6 +702,7 @@ clear_timeout :: proc(loop: ^Loop, id: Timer_ID) -> bool { if !loop.timers[idx].unreffed { loop.reffed_timer_count -= 1 } + run_dispose(loop.timers[idx].dispose, loop.timers[idx].user_data) timer_heap_remove_at(loop, idx) return true @@ -728,9 +752,11 @@ drain_microtasks :: proc(loop: ^Loop) { for len(loop.next_ticks) > 0 { drain_task_queue(loop, &loop.next_ticks, &loop.next_ticks_scratch) } + if len(loop.microtasks) == 0 { break } + drain_task_queue(loop, &loop.microtasks, &loop.microtasks_scratch) } } @@ -743,14 +769,18 @@ drain_microtasks :: proc(loop: ^Loop) { drain_io_callbacks :: proc(loop: ^Loop, limit: u64) -> (did_work: bool) { for { index := next_io_callback_index(loop, limit) + if index < 0 { break } + task := loop.io_callbacks[index] ordered_remove(&loop.io_callbacks, index) + if task.cancelled || is_cancel_requested(loop, task.id) { continue } + did_work = true loop.running_id = task.id task.callback(loop, task.user_data) @@ -781,11 +811,17 @@ run_once :: proc(loop: ^Loop) -> bool { // condition then returns. if !loop.shutdown_observed && sync.atomic_load(&loop.stop_requested) { loop.shutdown_observed = true - if loop.on_shutdown != nil do loop.on_shutdown(loop, loop.on_shutdown_data) + + if loop.on_shutdown != nil { + loop.on_shutdown(loop, loop.on_shutdown_data) + } } + // Forced: skip this tick's blocking poll and return at once so run()'s condition can exit. Covers // both a hook that drained immediately (force_exit set just above) and a prior tick's drain driver. - if loop.force_exit do return false + if loop.force_exit { + return false + } // Sample the real clock first so the timer phase fires every timer whose // deadline has actually elapsed (no-op in virtual-clock mode). @@ -801,6 +837,7 @@ run_once :: proc(loop: ^Loop) -> bool { if len(loop.next_ticks) > 0 || len(loop.microtasks) > 0 { did_work = true } + drain_microtasks(loop) // Phase 3: timers @@ -819,11 +856,18 @@ run_once :: proc(loop: ^Loop) -> bool { } root := loop.timers[0] - if root.seq >= timer_phase_sequence_limit do break - if root.due_ms > loop.now_ms do break + + if root.seq >= timer_phase_sequence_limit { + break + } + + if root.due_ms > loop.now_ms { + break + } timer := timer_heap_pop_min(loop) did_work = true + // A one-shot cannot re-arm, so it leaves the active set the instant it is // popped — drop its ref now, before the callback, not after. This keeps // has_pending_work honest *while the callback runs* (a running task is not @@ -836,6 +880,7 @@ run_once :: proc(loop: ^Loop) -> bool { if !timer.repeating && !timer.unreffed { loop.reffed_timer_count -= 1 } + loop.running_id = timer.id timer.callback(loop, timer.user_data) // Drain microtasks while running_id still names this timer: a task the @@ -856,6 +901,7 @@ run_once :: proc(loop: ^Loop) -> bool { // here — and drop the ref it kept across the fire. A one-shot freed its // binding when it fired and dropped its ref above, so neither applies. run_dispose(timer.dispose, timer.user_data) + if !timer.unreffed { loop.reffed_timer_count -= 1 } @@ -888,6 +934,7 @@ run_once :: proc(loop: ^Loop) -> bool { // queued. The blocking wait below is only for when there is nothing else to do. io_before := loop.io_events platform_poll(loop, 0) + if loop.io_events != io_before { did_work = true } @@ -895,11 +942,13 @@ run_once :: proc(loop: ^Loop) -> bool { if has_nothing_to_do { timeout_ms := get_next_timer_timeout(loop) + // With no timers but pending I/O, block indefinitely until an fd is ready // rather than spinning (get_next_timer_timeout returns -1 in that case). if timeout_ms != 0 || loop.active_io_count > 0 || loop.active_async > 0 { io_before := loop.io_events platform_poll(loop, timeout_ms) + if loop.io_events != io_before { // A fired I/O callback counts as progress so the run-until-idle // driver does not treat an I/O-only tick as "nothing happened". @@ -914,6 +963,7 @@ run_once :: proc(loop: ^Loop) -> bool { if !loop.real_time { advance_time(loop, u64(timeout_ms)) } + did_work = true } } @@ -941,12 +991,14 @@ run_once :: proc(loop: ^Loop) -> bool { immediate_phase_sequence_limit := loop.next_sequence for { index := next_immediate_index(loop, immediate_phase_sequence_limit) + if index < 0 { break } immediate := loop.immediates[index] ordered_remove(&loop.immediates, index) + if immediate.cancelled || is_cancel_requested(loop, immediate.id) { continue } @@ -962,12 +1014,14 @@ run_once :: proc(loop: ^Loop) -> bool { close_phase_sequence_limit := loop.next_sequence for { index := next_close_index(loop, close_phase_sequence_limit) + if index < 0 { break } cb := loop.close_callbacks[index] ordered_remove(&loop.close_callbacks, index) + if cb.cancelled { continue } @@ -1005,6 +1059,7 @@ run_next :: proc(loop: ^Loop) -> bool { } next_due, ok := next_timer_due(loop) + if !ok { return false } @@ -1062,8 +1117,10 @@ run_until_idle :: proc(loop: ^Loop, max_iterations := 1024) -> bool { if loop.active_io_count == 0 && loop.active_async == 0 { return did_work } + continue } + did_work = true } @@ -1091,12 +1148,15 @@ run :: proc(loop: ^Loop) { // Returns 0 if a timer is already due, -1 if there are no timers. get_next_timer_timeout :: proc(loop: ^Loop) -> int { next_due, ok := next_timer_due(loop) + if !ok { return -1 } + if next_due <= loop.now_ms { return 0 } + return int(next_due - loop.now_ms) } @@ -1117,6 +1177,7 @@ drain_task_queue :: proc(loop: ^Loop, queue: ^[dynamic]Task, scratch: ^[dynamic] if task.cancelled || (task.id != 0 && is_cancel_requested(loop, task.id)) { continue } + task.callback(loop, task.user_data) } clear(scratch) @@ -1142,6 +1203,7 @@ is_cancel_requested :: proc(loop: ^Loop, id: Timer_ID) -> bool { if id == 0 { return false } + return loop.cancelled_ids[id] } @@ -1177,9 +1239,11 @@ timer_heap_sift_up :: proc(loop: ^Loop, start: int) { i := start for i > 0 { parent := (i - 1) / 2 + if !timer_less(&loop.timers[i], &loop.timers[parent]) { break } + timer_heap_swap(loop, i, parent) i = parent } @@ -1193,14 +1257,17 @@ timer_heap_sift_up :: proc(loop: ^Loop, start: int) { timer_heap_remove_at :: proc(loop: ^Loop, idx: int) { delete_key(&loop.timer_index, loop.timers[idx].id) last := len(loop.timers) - 1 + if idx == last { ordered_remove(&loop.timers, last) // removing the tail: nothing to re-heap return } + moved := loop.timers[last] ordered_remove(&loop.timers, last) loop.timers[idx] = moved loop.timer_index[moved.id] = idx + // The moved tail can violate the heap upward or downward, never both: sift the // direction it needs. if idx > 0 && timer_less(&loop.timers[idx], &loop.timers[(idx - 1) / 2]) { @@ -1218,11 +1285,13 @@ timer_heap_pop_min :: proc(loop: ^Loop) -> Timer { delete_key(&loop.timer_index, root.id) last := loop.timers[n - 1] ordered_remove(&loop.timers, n - 1) // pop the tail (O(1) on the last element) + if n - 1 > 0 { loop.timers[0] = last loop.timer_index[last.id] = 0 timer_heap_sift_down(loop, 0) } + return root } @@ -1233,15 +1302,19 @@ timer_heap_sift_down :: proc(loop: ^Loop, start: int) { left := 2 * i + 1 right := 2 * i + 2 smallest := i + if left < n && timer_less(&loop.timers[left], &loop.timers[smallest]) { smallest = left } + if right < n && timer_less(&loop.timers[right], &loop.timers[smallest]) { smallest = right } + if smallest == i { break } + timer_heap_swap(loop, i, smallest) i = smallest } @@ -1264,12 +1337,15 @@ has_due_timer :: proc(loop: ^Loop) -> bool { next_immediate_index :: proc(loop: ^Loop, sequence_limit: u64) -> int { for i in 0 ..< len(loop.immediates) { immediate := loop.immediates[i] + if immediate.cancelled || is_cancel_requested(loop, immediate.id) { continue } + if immediate.seq >= sequence_limit { continue } + return i } return -1 @@ -1278,12 +1354,15 @@ next_immediate_index :: proc(loop: ^Loop, sequence_limit: u64) -> int { next_io_callback_index :: proc(loop: ^Loop, sequence_limit: u64) -> int { for i in 0 ..< len(loop.io_callbacks) { task := loop.io_callbacks[i] + if task.cancelled || is_cancel_requested(loop, task.id) { continue } + if task.seq >= sequence_limit { continue } + return i } return -1 @@ -1292,12 +1371,15 @@ next_io_callback_index :: proc(loop: ^Loop, sequence_limit: u64) -> int { next_close_index :: proc(loop: ^Loop, sequence_limit: u64) -> int { for i in 0 ..< len(loop.close_callbacks) { cb := loop.close_callbacks[i] + if cb.cancelled { continue } + if cb.seq >= sequence_limit { continue } + return i } return -1 @@ -1307,9 +1389,11 @@ next_close_index :: proc(loop: ^Loop, sequence_limit: u64) -> int { // any cancelled timers off it), or false if no timer is pending. next_timer_due :: proc(loop: ^Loop) -> (u64, bool) { timer_heap_clean_root(loop) + if len(loop.timers) == 0 { return 0, false } + return loop.timers[0].due_ms, true } @@ -1330,6 +1414,7 @@ discard_cancelled_immediates :: proc(loop: ^Loop) { ordered_remove(&loop.immediates, i) continue } + i += 1 } } @@ -1341,7 +1426,10 @@ discard_cancelled_immediates :: proc(loop: ^Loop) { // forever) has no deadline to track and is returned unchanged; a finite timeout // returns max(0, timeout_ms - elapsed). Shared by the epoll and kqueue backends. poll_remaining_ms :: proc(start: time.Tick, timeout_ms: int) -> int { - if timeout_ms <= 0 do return timeout_ms + if timeout_ms <= 0 { + return timeout_ms + } + elapsed := int(time.duration_milliseconds(time.tick_since(start))) return max(0, timeout_ms - elapsed) } @@ -1358,25 +1446,38 @@ poll_remaining_ms :: proc(start: time.Tick, timeout_ms: int) -> int { // watcher (watched == false), so a false return can only mean the backend failed. // fetch_set_watch_mode relies on this: it unwatch_fd's first, clearing the flag. watch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { - if watcher == nil || watcher.callback == nil do return false + if watcher == nil || watcher.callback == nil { + return false + } + // Already in the registered set: a re-arm, not a new watcher. Do not call the // backend again (io_uring would over-count by arming a duplicate poll) or bump // active_io_count a second time. - if watcher.watched do return false + if watcher.watched { + return false + } + if platform_watch_fd(loop, watcher) { watcher.watched = true loop.active_io_count += 1 return true } + return false } unwatch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { - if watcher == nil do return false + if watcher == nil { + return false + } + // Only a watcher that is actually registered may decrement the count. A no-op // unwatch (never watched, or already unwatched) must not drift active_io_count // down — a spurious decrement can let the loop exit with I/O still pending. - if !watcher.watched do return false + if !watcher.watched { + return false + } + // The platform op is best-effort: a failed EPOLL_CTL_DEL (fd already closed → // the kernel auto-removed it) or io_uring's logical-only unwatch must still drop // the count, or has_pending_work stays true forever and the loop parks. The @@ -1451,9 +1552,16 @@ submit_recv_ring :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> Op_ID { - if cb == nil do return OP_ID_INVALID + if cb == nil { + return OP_ID_INVALID + } + token := platform_submit_recv_ring(loop, fd, cb, dispose, user_data) - if token != 0 do loop.active_io_count += 1 + + if token != 0 { + loop.active_io_count += 1 + } + return Op_ID(token) } @@ -1495,9 +1603,13 @@ submit_recv :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> Op_ID { - if cb == nil do return OP_ID_INVALID // exactly-once completion has no observer; refuse + if cb == nil {return OP_ID_INVALID} // exactly-once completion has no observer; refuse token := platform_submit_recv(loop, fd, buf, cb, dispose, user_data) - if token != 0 do loop.active_io_count += 1 + + if token != 0 { + loop.active_io_count += 1 + } + return Op_ID(token) } @@ -1513,9 +1625,16 @@ submit_send :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> Op_ID { - if cb == nil do return OP_ID_INVALID + if cb == nil { + return OP_ID_INVALID + } + token := platform_submit_send(loop, fd, buf, cb, dispose, user_data) - if token != 0 do loop.active_io_count += 1 + + if token != 0 { + loop.active_io_count += 1 + } + return Op_ID(token) } @@ -1528,7 +1647,10 @@ submit_send :: proc( // unavailable, the slot already completed, or the SQ was momentarily full), so a caller // suppressing duplicate cancels can distinguish a real cancel from a no-op. cancel_op :: proc(loop: ^Loop, id: Op_ID) -> bool { - if id == OP_ID_INVALID do return false + if id == OP_ID_INVALID { + return false + } + return platform_cancel_op(loop, u64(id)) } @@ -1551,7 +1673,11 @@ set_shutdown_hook :: proc(loop: ^Loop, hook: Shutdown_Hook, user_data: rawptr) { request_shutdown :: proc(loop: ^Loop) { sync.lock(&loop.shutdown_mutex) defer sync.unlock(&loop.shutdown_mutex) - if loop.destroyed do return + + if loop.destroyed { + return + } + sync.atomic_store(&loop.stop_requested, true) platform_wakeup(loop) } diff --git a/pkg/runtime/eventloop/loop_darwin.odin b/pkg/runtime/eventloop/loop_darwin.odin index 55ead8c7..1f9b1b05 100644 --- a/pkg/runtime/eventloop/loop_darwin.odin +++ b/pkg/runtime/eventloop/loop_darwin.odin @@ -21,9 +21,11 @@ platform_init :: proc(loop: ^Loop) -> bool { loop.platform.wakeup_pipe = {-1, -1} kq, kq_err := kqueue.kqueue() + if kq_err != .NONE { return false } + loop.platform.kq = kq if posix.pipe(&loop.platform.wakeup_pipe) != .OK { @@ -49,6 +51,7 @@ platform_init :: proc(loop: ^Loop) -> bool { flags = {.Add, .Enable}, } _, err := kqueue.kevent(loop.platform.kq, {ev}, nil, nil) + if err != .NONE { posix.close(loop.platform.wakeup_pipe[0]) posix.close(loop.platform.wakeup_pipe[1]) @@ -76,6 +79,7 @@ platform_close_wakeup :: proc(loop: ^Loop) { posix.close(loop.platform.wakeup_pipe[0]) loop.platform.wakeup_pipe[0] = -1 } + if loop.platform.wakeup_pipe[1] >= 0 { posix.close(loop.platform.wakeup_pipe[1]) loop.platform.wakeup_pipe[1] = -1 @@ -122,6 +126,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { for { ts: posix.timespec timeout: ^posix.timespec = nil + if timeout_ms >= 0 { remaining := poll_remaining_ms(poll_start, timeout_ms) ts.tv_sec = posix.time_t(remaining / 1000) @@ -130,9 +135,11 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { } res, err := kqueue.kevent(loop.platform.kq, nil, events[:], timeout) + if err == .EINTR { continue } + // Any other error is fatal (e.g. EBADF on a closed kqueue fd): flag it so the // run drivers stop instead of busy-spinning on a syscall that can never // make progress. @@ -140,9 +147,11 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { loop.backend_error = true return } + n = res break } + if n == 0 { return } @@ -157,6 +166,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { } watcher := cast(^IO_Watcher)ev.udata + if watcher != nil && watcher.callback != nil { loop.io_events += 1 watcher.callback(loop, watcher.user_data) diff --git a/pkg/runtime/eventloop/loop_linux.odin b/pkg/runtime/eventloop/loop_linux.odin index 0501222e..8bce93d1 100644 --- a/pkg/runtime/eventloop/loop_linux.odin +++ b/pkg/runtime/eventloop/loop_linux.odin @@ -117,6 +117,7 @@ platform_name :: proc(loop: ^Loop) -> string { if loop.platform.use_uring { return "linux-io_uring" } + return "linux-epoll" } @@ -129,6 +130,7 @@ platform_init :: proc(loop: ^Loop) -> bool { } params := uring.DEFAULT_PARAMS + if !force_readiness_backend && uring.init(&loop.platform.ring, ¶ms, 256) == nil { loop.platform.use_uring = true // Gate the proactor on an actual RECV/SEND opcode probe (see proactor_ok): a successful @@ -160,6 +162,7 @@ platform_init :: proc(loop: ^Loop) -> bool { } fd, err := linux.epoll_create1({.FDCLOEXEC}) + if err != nil { linux.close(loop.platform.wakeup_pipe[0]) linux.close(loop.platform.wakeup_pipe[1]) @@ -174,6 +177,7 @@ platform_init :: proc(loop: ^Loop) -> bool { loop.platform.wakeup_pipe = {-1, -1} return false } + loop.platform.epoll_fd = fd ev: linux.EPoll_Event @@ -198,9 +202,16 @@ platform_close_backend :: proc(loop: ^Loop) { // {callback, dispose} runs per op; here it is dispose. uring.destroy(&loop.platform.ring) for &slot in loop.platform.op_slots { - if !slot.in_use do continue + if !slot.in_use { + continue + } + loop.active_io_count = max(0, loop.active_io_count - 1) - if slot.dispose != nil do slot.dispose(slot.user_data) + + if slot.dispose != nil { + slot.dispose(slot.user_data) + } + slot.in_use = false } // The io_uring fd is now closed (uring.destroy), which implicitly deregistered the buf_ring @@ -234,6 +245,7 @@ platform_close_wakeup :: proc(loop: ^Loop) { linux.close(loop.platform.wakeup_pipe[0]) loop.platform.wakeup_pipe[0] = -1 } + if loop.platform.wakeup_pipe[1] >= 0 { linux.close(loop.platform.wakeup_pipe[1]) loop.platform.wakeup_pipe[1] = -1 @@ -248,7 +260,10 @@ platform_wakeup :: proc(loop: ^Loop) { // `loop^ = Loop{}`): a cross-thread request_shutdown that races teardown past the // shutdown-mutex guard must never write a closed/zeroed fd. The real pipe fd is // always > 2 (stdin/out/err precede it), so this never skips a live wakeup. - if loop.platform.wakeup_pipe[1] <= 0 do return + if loop.platform.wakeup_pipe[1] <= 0 { + return + } + b := [1]u8{1} linux.write(loop.platform.wakeup_pipe[1], b[:]) } @@ -270,12 +285,16 @@ drain_wakeup :: proc(loop: ^Loop) { buf: [64]u8 for { n, err := linux.read(loop.platform.wakeup_pipe[0], buf[:]) - if err != nil || n <= 0 do break + + if err != nil || n <= 0 { + break + } } } platform_watch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { fd := linux.Fd(watcher.fd) + if loop.platform.use_uring { events: linux.Fd_Poll_Events = {.IN} if watcher.mode == .Read else {.OUT} // Allocate a fresh table slot and arm the poll under its generation token @@ -284,12 +303,14 @@ platform_watch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { // without ever dereferencing the watcher. The loop-level watch_fd wrapper only // reaches here for a NOT-yet-watched watcher, so each call is one new slot. token := uring_alloc_slot(loop, watcher) + if arm_uring_poll(loop, u64(watcher.fd), token, events) { // Record the slot on the watcher so unwatch_fd reaches it in O(1) without // scanning the table. watcher.backend_slot = uring_token_index(token) return true } + // Arm failed even after arm_uring_poll's submit-and-retry (the SQ ring is still // full): release the slot so it is not stranded in_use. uring_release_slot(loop, uring_token_index(token)) @@ -323,8 +344,10 @@ platform_unwatch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { // not the kernel result, drives active_io_count, and a best-effort cancel that // could not get an SQE is still covered by the generation check. index := watcher.backend_slot + if int(index) < len(loop.platform.watch_slots) { slot := loop.platform.watch_slots[index] + // Guard the O(1) lookup against a stale backend_slot: act only if the slot // still holds THIS watcher (it always does while watched, but this keeps a // desync from cancelling/releasing an unrelated slot). @@ -333,6 +356,7 @@ platform_unwatch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { uring_release_slot(loop, index) } } + return true } @@ -347,7 +371,9 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { return } - if loop.platform.epoll_fd < 0 do return + if loop.platform.epoll_fd < 0 { + return + } events: [32]linux.EPoll_Event n: int @@ -360,6 +386,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { for { res: i32 errno: linux.Errno + if timeout_ms < 0 { res, errno = linux.epoll_wait(loop.platform.epoll_fd, raw_data(events[:]), i32(len(events)), -1) } else { @@ -374,6 +401,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { if errno == .EINTR { continue } + // Any other error is fatal (e.g. EBADF on a closed epoll fd): flag it so the // run drivers stop instead of busy-spinning on a syscall that can never make // progress. @@ -381,11 +409,14 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { loop.backend_error = true return } + n = int(res) break } - if n <= 0 do return + if n <= 0 { + return + } for i in 0 ..< n { ev := events[i] @@ -397,6 +428,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { // A registered socket / file-descriptor event. watcher := cast(^IO_Watcher)ev.data.ptr + if watcher != nil && watcher.callback != nil { loop.io_events += 1 watcher.callback(loop, watcher.user_data) @@ -414,6 +446,7 @@ platform_poll_uring :: proc(loop: ^Loop, timeout_ms: int) { if uring.sq_ready(&loop.platform.ring) > 0 { uring.submit(&loop.platform.ring, 0, nil) } + drain_uring_completions(loop) return } @@ -426,6 +459,7 @@ platform_poll_uring :: proc(loop: ^Loop, timeout_ms: int) { // of the spurious-wake sources behind the premature-exit class (#72). ts: linux.Time_Spec ts_ptr: ^linux.Time_Spec = nil + if timeout_ms > 0 { ts = linux.Time_Spec { time_sec = uint(timeout_ms / 1000), @@ -457,7 +491,11 @@ drain_uring_completions :: proc(loop: ^Loop) { processed := 0 for processed < URING_DRAIN_CAP { n, err := uring.copy_cqes(&loop.platform.ring, loop.platform.cqes[:], 0) - if err != nil || n == 0 do return + + if err != nil || n == 0 { + return + } + processed += int(n) for i in 0 ..< int(n) { @@ -489,6 +527,7 @@ drain_uring_completions :: proc(loop: ^Loop) { if cqe.user_data & URING_OP_DOMAIN != 0 { index := uring_op_token_index(cqe.user_data) gen := uring_op_token_generation(cqe.user_data) + if uring_op_slot_live(loop, index, gen) { slot := loop.platform.op_slots[index] loop.io_events += 1 @@ -501,10 +540,12 @@ drain_uring_completions :: proc(loop: ^Loop) { // SEND_ZC's result CQE, whose notification (F_MORE clear) is the terminal (3b) — so // the count/slot lifetime is driven by F_MORE alone, uniformly, for both. more := .MORE in cqe.flags + if !more { loop.active_io_count = max(0, loop.active_io_count - 1) uring_op_release_slot(loop, index) } + // Dispatch by callback KIND (mutually exclusive: a slot carries exactly one of // recv_cb/send_cb/callback). Order recv → send → plain; a SEND_ZC CQE never reaches // the recv arm (no recv_cb), so its high flag bits are never misread as a buffer id. @@ -520,6 +561,7 @@ drain_uring_completions :: proc(loop: ^Loop) { slot.callback(loop, slot.user_data, cqe.res) } } + continue } @@ -529,10 +571,16 @@ drain_uring_completions :: proc(loop: ^Loop) { // already be freed — this is the core stale-poll safety guarantee. index := uring_token_index(cqe.user_data) gen := uring_token_generation(cqe.user_data) - if !uring_slot_live(loop, index, gen) do continue + + if !uring_slot_live(loop, index, gen) { + continue + } watcher := loop.platform.watch_slots[index].watcher - if watcher == nil || watcher.callback == nil do continue + + if watcher == nil || watcher.callback == nil { + continue + } loop.io_events += 1 watcher.callback(loop, watcher.user_data) @@ -542,9 +590,15 @@ drain_uring_completions :: proc(loop: ^Loop) { // the slot), or unwatched then re-watched (a different slot now owns a // fresh poll) — re-validating index+generation catches both, so we never // re-arm a freed or reassigned slot. A re-watch is left to its own poll. - if !uring_slot_live(loop, index, gen) do continue + if !uring_slot_live(loop, index, gen) { + continue + } + watcher = loop.platform.watch_slots[index].watcher - if watcher == nil || watcher.callback == nil do continue + + if watcher == nil || watcher.callback == nil { + continue + } events: linux.Fd_Poll_Events = {.IN} if watcher.mode == .Read else {.OUT} // arm_uring_poll retries once if the SQ ring is momentarily full rather than @@ -556,6 +610,7 @@ drain_uring_completions :: proc(loop: ^Loop) { arm_uring_poll :: proc(loop: ^Loop, fd: u64, user_data: u64, events: linux.Fd_Poll_Events) -> bool { sqe, ok := uring.get_sqe(&loop.platform.ring) + if !ok { // SQ ring momentarily full: submit to flush staged entries to the kernel // (which frees SQEs), then retry once. Every caller — the fresh watch in @@ -563,7 +618,10 @@ arm_uring_poll :: proc(loop: ^Loop, fd: u64, user_data: u64, events: linux.Fd_Po // this so a transient full ring never strands an fd with no kernel poll. uring.submit(&loop.platform.ring, 0, nil) sqe, ok = uring.get_sqe(&loop.platform.ring) - if !ok do return false + + if !ok { + return false + } } // Defensive zero: do not depend on get_sqe clearing the recycled ring entry. @@ -604,7 +662,10 @@ uring_token_generation :: proc(token: u64) -> u32 { // (or reused at a newer generation) by unwatch_fd, so the completion must be // dropped without touching the watcher it once referenced. uring_slot_live :: proc(loop: ^Loop, index: u32, generation: u32) -> bool { - if int(index) >= len(loop.platform.watch_slots) do return false + if int(index) >= len(loop.platform.watch_slots) { + return false + } + slot := loop.platform.watch_slots[index] return slot.in_use && slot.generation == generation } @@ -623,6 +684,7 @@ uring_alloc_slot :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> u64 { slot.in_use = true return uring_encode_token(index, slot.generation) } + append(&loop.platform.watch_slots, Uring_Watch_Slot{watcher = watcher, generation = 1, in_use = true}) return uring_encode_token(u32(len(loop.platform.watch_slots) - 1), 1) } @@ -633,15 +695,26 @@ uring_alloc_slot :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> u64 { // generation 0 on wrap keeps tokens out of the sentinel range. Idempotent: a slot // already free is left alone, so its index is never double-pushed onto free_slots. uring_release_slot :: proc(loop: ^Loop, index: u32) { - if int(index) >= len(loop.platform.watch_slots) do return + if int(index) >= len(loop.platform.watch_slots) { + return + } + slot := &loop.platform.watch_slots[index] - if !slot.in_use do return + + if !slot.in_use { + return + } + slot.in_use = false slot.watcher = nil slot.generation += 1 + // Keep generations within 31 bits so a watcher token (generation << 32 | index) never // sets bit 63 — that bit is the op-token domain marker. Skip 0 on wrap (sentinel range). - if slot.generation == 0 || slot.generation >= u32(1) << 31 do slot.generation = 1 + if slot.generation == 0 || slot.generation >= u32(1) << 31 { + slot.generation = 1 + } + append(&loop.platform.free_slots, index) } @@ -654,12 +727,17 @@ uring_release_slot :: proc(loop: ^Loop, index: u32) { // so a caller suppressing duplicate cancels knows whether one is genuinely pending. uring_cancel_poll :: proc(loop: ^Loop, target_token: u64) -> bool { sqe, ok := uring.get_sqe(&loop.platform.ring) + if !ok { // SQ ring momentarily full: submit to free slots, then retry once. uring.submit(&loop.platform.ring, 0, nil) sqe, ok = uring.get_sqe(&loop.platform.ring) - if !ok do return false + + if !ok { + return false + } } + // Zero the recycled SQE slot — get_sqe does not clear it (mirrors arm_uring_poll). sqe^ = {} sqe.opcode = .ASYNC_CANCEL @@ -716,12 +794,14 @@ Uring_Probe :: struct { uring_probe_proactor :: proc(ring_fd: linux.Fd) -> (proactor: bool, zc: bool) { probe := Uring_Probe{} // zero-initialized: the kernel requires the whole buffer to be zero. + // nr_args is the number of ops[] slots offered; the kernel caps its fill to the opcodes it // knows. REGISTER_PROBE itself postdates RECV/SEND, so an error here means an old kernel // without the proactor opcodes — report unsupported and let callers use the readiness path. if errno := linux.io_uring_register(ring_fd, .REGISTER_PROBE, &probe, u32(len(probe.ops))); errno != nil { return false, false } + proactor = uring_probe_supports(&probe, .RECV) && uring_probe_supports(&probe, .SEND) // SEND_ZC (Slice 3b) is a real OPCODE, so it is probeable here exactly like RECV/SEND — unlike 2b's // RECV_MULTISHOT, which is an ioprio flag and could only be detected via a runtime -EINVAL. Probing @@ -733,7 +813,8 @@ uring_probe_proactor :: proc(ring_fd: linux.Fd) -> (proactor: bool, zc: bool) { uring_probe_supports :: proc(probe: ^Uring_Probe, op: linux.IO_Uring_OP) -> bool { idx := u8(op) - if idx > probe.last_op do return false // opcode beyond what this kernel reports + + if idx > probe.last_op {return false} // opcode beyond what this kernel reports return (probe.ops[idx].flags & URING_OP_SUPPORTED) != 0 } @@ -747,9 +828,16 @@ platform_submit_recv :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> u64 { - if !loop.platform.proactor_ok do return 0 + if !loop.platform.proactor_ok { + return 0 + } + token := uring_op_alloc_slot(loop, cb, dispose, user_data) - if uring_arm_rw(loop, .RECV, fd, buf, token, {}) do return token + + if uring_arm_rw(loop, .RECV, fd, buf, token, {}) { + return token + } + uring_op_release_slot(loop, uring_op_token_index(token)) return 0 } @@ -762,11 +850,18 @@ platform_submit_send :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> u64 { - if !loop.platform.proactor_ok do return 0 + if !loop.platform.proactor_ok { + return 0 + } + token := uring_op_alloc_slot(loop, cb, dispose, user_data) + // NOSIGNAL: a send to a peer that has closed surfaces as -EPIPE in the completion rather // than raising SIGPIPE (which would kill the process). - if uring_arm_rw(loop, .SEND, fd, buf, token, {.NOSIGNAL}) do return token + if uring_arm_rw(loop, .SEND, fd, buf, token, {.NOSIGNAL}) { + return token + } + uring_op_release_slot(loop, uring_op_token_index(token)) return 0 } @@ -776,10 +871,14 @@ platform_submit_send :: proc( // pending op (e.g. a RECV on a fd being closed) tear down promptly instead of lingering. The // generation check avoids issuing a cancel against a slot already reused for a new op. platform_cancel_op :: proc(loop: ^Loop, token: u64) -> bool { - if !loop.platform.proactor_ok do return false + if !loop.platform.proactor_ok { + return false + } + if uring_op_slot_live(loop, uring_op_token_index(token), uring_op_token_generation(token)) { return uring_cancel_poll(loop, token) // ASYNC_CANCEL(addr=token); its own CQE is ignored } + return false } @@ -795,11 +894,16 @@ uring_arm_rw :: proc( flags: linux.Socket_Msg, ) -> bool { sqe, ok := uring.get_sqe(&loop.platform.ring) + if !ok { uring.submit(&loop.platform.ring, 0, nil) sqe, ok = uring.get_sqe(&loop.platform.ring) - if !ok do return false + + if !ok { + return false + } } + sqe^ = {} sqe.opcode = opcode sqe.fd = cast(linux.Fd)fd @@ -828,7 +932,10 @@ uring_op_token_generation :: proc(token: u64) -> u32 { } uring_op_slot_live :: proc(loop: ^Loop, index: u32, generation: u32) -> bool { - if int(index) >= len(loop.platform.op_slots) do return false + if int(index) >= len(loop.platform.op_slots) { + return false + } + slot := loop.platform.op_slots[index] return slot.in_use && slot.generation == generation } @@ -843,6 +950,7 @@ uring_op_alloc_slot :: proc(loop: ^Loop, cb: Op_Completion, dispose: Op_Dispose, slot.in_use = true return uring_op_encode_token(index, slot.generation) } + append( &loop.platform.op_slots, Uring_Op_Slot{callback = cb, dispose = dispose, user_data = user_data, generation = 1, in_use = true}, @@ -851,9 +959,16 @@ uring_op_alloc_slot :: proc(loop: ^Loop, cb: Op_Completion, dispose: Op_Dispose, } uring_op_release_slot :: proc(loop: ^Loop, index: u32) { - if int(index) >= len(loop.platform.op_slots) do return + if int(index) >= len(loop.platform.op_slots) { + return + } + slot := &loop.platform.op_slots[index] - if !slot.in_use do return + + if !slot.in_use { + return + } + slot.in_use = false slot.callback = nil slot.recv_cb = nil @@ -861,7 +976,11 @@ uring_op_release_slot :: proc(loop: ^Loop, index: u32) { slot.dispose = nil slot.user_data = nil slot.generation += 1 - if slot.generation == 0 || slot.generation >= u32(1) << 31 do slot.generation = 1 + + if slot.generation == 0 || slot.generation >= u32(1) << 31 { + slot.generation = 1 + } + append(&loop.platform.op_free, index) } @@ -918,6 +1037,7 @@ platform_bufring_ok :: proc(loop: ^Loop) -> bool { loop.platform.bufring_tried = true buf_ring_init(loop) } + return loop.platform.bufring_ok } @@ -930,9 +1050,16 @@ platform_submit_recv_ring :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> u64 { - if !loop.platform.bufring_ok do return 0 + if !loop.platform.bufring_ok { + return 0 + } + token := uring_op_alloc_slot_recv(loop, cb, dispose, user_data) - if uring_arm_recv_ring(loop, fd, token) do return token + + if uring_arm_recv_ring(loop, fd, token) { + return token + } + uring_op_release_slot(loop, uring_op_token_index(token)) return 0 } @@ -940,7 +1067,10 @@ platform_submit_recv_ring :: proc( // platform_buf_ring_recycle returns buffer `bid` to the ring. The caller MUST have already copied // any bytes it needs out of the buffer — once the tail is published the kernel may overwrite it. platform_buf_ring_recycle :: proc(loop: ^Loop, bid: u16) { - if !loop.platform.bufring_ok || int(bid) >= URING_BUFRING_ENTRIES do return + if !loop.platform.bufring_ok || int(bid) >= URING_BUFRING_ENTRIES { + return + } + off := int(bid) * URING_BUFRING_BUFSIZE buf_ring_add( loop, @@ -955,7 +1085,10 @@ platform_buf_ring_recycle :: proc(loop: ^Loop, bid: u16) { // platform_buf_ring_buf returns the kernel-selected bytes for `bid` (the caller copies, does NOT retain). platform_buf_ring_buf :: proc(loop: ^Loop, bid: u16, n: int) -> []byte { - if !loop.platform.bufring_ok || int(bid) >= URING_BUFRING_ENTRIES || n <= 0 do return nil + if !loop.platform.bufring_ok || int(bid) >= URING_BUFRING_ENTRIES || n <= 0 { + return nil + } + off := int(bid) * URING_BUFRING_BUFSIZE m := min(n, URING_BUFRING_BUFSIZE) return loop.platform.bufring_pool[off:off + m] @@ -992,16 +1125,28 @@ buf_ring_publish_tail :: proc(loop: ^Loop) { // ring mmap fails, or REGISTER_PBUF_RING errors. bufring_ok gates the whole ring-recv path. @(private = "file") buf_ring_init :: proc(loop: ^Loop) -> bool { - if !loop.platform.proactor_ok do return false - if .NODROP not_in loop.platform.ring.features do return false + if !loop.platform.proactor_ok { + return false + } + + if .NODROP not_in loop.platform.ring.features { + return false + } + pool := make([]byte, URING_BUFRING_ENTRIES * URING_BUFRING_BUFSIZE, loop.allocator) - if pool == nil do return false + + if pool == nil { + return false + } + ring_size := uint(URING_BUFRING_ENTRIES * size_of(Uring_Buf)) ring_ptr, mmap_err := linux.mmap(0, ring_size, {.READ, .WRITE}, {.PRIVATE, .ANONYMOUS}) + if mmap_err != .NONE { delete(pool, loop.allocator) return false } + loop.platform.bufring = ring_ptr loop.platform.bufring_size = ring_size loop.platform.bufring_pool = pool @@ -1017,6 +1162,7 @@ buf_ring_init :: proc(loop: ^Loop) -> bool { ring_entries = u32(URING_BUFRING_ENTRIES), bgid = URING_BUFRING_BGID, } + if errno := linux.io_uring_register(loop.platform.ring.fd, .REGISTER_PBUF_RING, ®, 1); errno != .NONE { linux.munmap(ring_ptr, ring_size) delete(pool, loop.allocator) @@ -1024,6 +1170,7 @@ buf_ring_init :: proc(loop: ^Loop) -> bool { loop.platform.bufring_pool = nil return false } + loop.platform.bufring_ok = true // Attempt multishot (2b) by default: RECV_MULTISHOT is an ioprio flag, not a probeable opcode, // so a kernel with buffer rings (5.19) but without multishot recv (added 6.0) accepts the SQE @@ -1040,10 +1187,12 @@ buf_ring_destroy :: proc(loop: ^Loop) { linux.munmap(loop.platform.bufring, loop.platform.bufring_size) loop.platform.bufring = nil } + if loop.platform.bufring_pool != nil { delete(loop.platform.bufring_pool, loop.allocator) loop.platform.bufring_pool = nil } + loop.platform.bufring_ok = false } @@ -1052,17 +1201,23 @@ buf_ring_destroy :: proc(loop: ^Loop) { @(private = "file") uring_arm_recv_ring :: proc(loop: ^Loop, fd: uintptr, token: u64) -> bool { sqe, ok := uring.get_sqe(&loop.platform.ring) + if !ok { uring.submit(&loop.platform.ring, 0, nil) sqe, ok = uring.get_sqe(&loop.platform.ring) - if !ok do return false + + if !ok { + return false + } } + sqe^ = {} sqe.opcode = .RECV sqe.fd = cast(linux.Fd)fd sqe.addr = 0 sqe.flags = {.BUFFER_SELECT} sqe.buf_group = URING_BUFRING_BGID + if loop.platform.multishot_ok { // Multishot (2b): RECV_MULTISHOT lives in ioprio (aliased here as sq_send_recv_flags), NOT // msg_flags; one submission then yields many CQEs (each F_MORE-set until it ends). The @@ -1077,6 +1232,7 @@ uring_arm_recv_ring :: proc(loop: ^Loop, fd: uintptr, token: u64) -> bool { // kernel reports the actual bytes in cqe.res (<= this cap). sqe.len = u32(URING_BUFRING_BUFSIZE) } + sqe.user_data = token return true } @@ -1120,12 +1276,17 @@ submit_send_zc :: proc( dispose: Op_Dispose, user_data: rawptr, ) -> Op_ID { - if cb == nil || !loop.platform.proactor_ok do return OP_ID_INVALID + if cb == nil || !loop.platform.proactor_ok { + return OP_ID_INVALID + } + token := uring_op_alloc_slot_send(loop, cb, dispose, user_data) + if !uring_arm_rw(loop, .SEND_ZC, fd, buf, token, {.NOSIGNAL}) { uring_op_release_slot(loop, uring_op_token_index(token)) return OP_ID_INVALID } + loop.active_io_count += 1 return Op_ID(token) } diff --git a/pkg/runtime/eventloop/loop_windows.odin b/pkg/runtime/eventloop/loop_windows.odin index 59fc6b59..9fd6743b 100644 --- a/pkg/runtime/eventloop/loop_windows.odin +++ b/pkg/runtime/eventloop/loop_windows.odin @@ -37,9 +37,11 @@ platform_init :: proc(loop: ^Loop) -> bool { loop.platform.wake_send = windows.INVALID_SOCKET wsadata: windows.WSADATA + if windows.WSAStartup(windows.MAKEWORD(2, 2), &wsadata) != 0 { return false } + loop.platform.started = true if !make_wakeup_pair(loop) { @@ -60,7 +62,11 @@ platform_init :: proc(loop: ^Loop) -> bool { @(private = "file") make_wakeup_pair :: proc(loop: ^Loop) -> bool { listener := windows.socket(windows.AF_INET, windows.SOCK_STREAM, 0) - if listener == windows.INVALID_SOCKET do return false + + if listener == windows.INVALID_SOCKET { + return false + } + defer windows.closesocket(listener) addr := windows.sockaddr_in { @@ -68,25 +74,35 @@ make_wakeup_pair :: proc(loop: ^Loop) -> bool { sin_port = 0, // ask the kernel for an ephemeral port sin_addr = {s_addr = transmute(u32)[4]u8{127, 0, 0, 1}}, } + if windows.bind(listener, cast(^windows.SOCKADDR_STORAGE_LH)&addr, size_of(addr)) == windows.SOCKET_ERROR { return false } - if windows.listen(listener, 1) == windows.SOCKET_ERROR do return false + + if windows.listen(listener, 1) == windows.SOCKET_ERROR { + return false + } // Recover the bound ephemeral port to connect back to. bound: windows.sockaddr_in bound_len := i32(size_of(bound)) + if windows.getsockname(listener, cast(^windows.SOCKADDR_STORAGE_LH)&bound, &bound_len) == windows.SOCKET_ERROR { return false } send_sock := windows.socket(windows.AF_INET, windows.SOCK_STREAM, 0) - if send_sock == windows.INVALID_SOCKET do return false + + if send_sock == windows.INVALID_SOCKET { + return false + } + connect_addr := windows.sockaddr_in { sin_family = u16(windows.AF_INET), sin_port = bound.sin_port, sin_addr = {s_addr = transmute(u32)[4]u8{127, 0, 0, 1}}, } + if windows.connect(send_sock, cast(^windows.SOCKADDR_STORAGE_LH)&connect_addr, size_of(connect_addr)) == windows.SOCKET_ERROR { windows.closesocket(send_sock) @@ -94,6 +110,7 @@ make_wakeup_pair :: proc(loop: ^Loop) -> bool { } recv_sock := windows.accept(listener, nil, nil) + if recv_sock == windows.INVALID_SOCKET { windows.closesocket(send_sock) return false @@ -137,10 +154,12 @@ platform_close_wakeup :: proc(loop: ^Loop) { windows.closesocket(loop.platform.wake_recv) loop.platform.wake_recv = windows.INVALID_SOCKET } + if loop.platform.wake_send != windows.INVALID_SOCKET { windows.closesocket(loop.platform.wake_send) loop.platform.wake_send = windows.INVALID_SOCKET } + if loop.platform.started { windows.WSACleanup() loop.platform.started = false @@ -167,10 +186,14 @@ platform_wakeup :: proc(loop: ^Loop) { // reject (honestly, returning false) once the set is full, rather than silently // dropping a watcher that could then never fire. platform_watch_fd :: proc(loop: ^Loop, watcher: ^IO_Watcher) -> bool { - if len(loop.platform.watchers) >= windows.FD_SETSIZE - 1 do return false + if len(loop.platform.watchers) >= windows.FD_SETSIZE - 1 { + return false + } + for w in loop.platform.watchers { - if w == watcher do return false // already registered, already counted + if w == watcher {return false} // already registered, already counted } + append(&loop.platform.watchers, watcher) return true } @@ -199,7 +222,9 @@ fd_set_add :: proc(set: ^windows.fd_set, sock: windows.SOCKET) { @(private = "file") fd_set_has :: proc(set: ^windows.fd_set, sock: windows.SOCKET) -> bool { for i in 0 ..< set.fd_count { - if set.fd_array[i] == sock do return true + if set.fd_array[i] == sock { + return true + } } return false } @@ -212,11 +237,13 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { for w in loop.platform.watchers { sock := windows.SOCKET(w.fd) + if w.mode == .Read { fd_set_add(&readfds, sock) } else { fd_set_add(&writefds, sock) } + // A socket error (incl. a failed non-blocking connect) shows in exceptfds; // surface it as readiness so the watcher's callback runs and handles it. fd_set_add(&exceptfds, sock) @@ -224,6 +251,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { tv: windows.timeval timeout: ^windows.timeval = nil + if timeout_ms >= 0 { tv.tv_sec = windows.c_long(timeout_ms / 1000) tv.tv_usec = windows.c_long((timeout_ms % 1000) * 1000) @@ -239,11 +267,13 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { cast([^]windows.fd_set)&exceptfds, timeout, ) + if n == windows.SOCKET_ERROR { loop.backend_error = true return } - if n == 0 do return // timeout + + if n == 0 {return} // timeout // Drain the wakeup byte(s); the read end is non-blocking. if fd_set_has(&readfds, loop.platform.wake_recv) { @@ -257,6 +287,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { count := 0 for w in loop.platform.watchers { sock := windows.SOCKET(w.fd) + if fd_set_has(&readfds, sock) || fd_set_has(&writefds, sock) || fd_set_has(&exceptfds, sock) { if count < len(ready) { ready[count] = w @@ -266,6 +297,7 @@ platform_poll :: proc(loop: ^Loop, timeout_ms: int) { } for i in 0 ..< count { w := ready[i] + if w.callback != nil { loop.io_events += 1 w.callback(loop, w.user_data) diff --git a/pkg/runtime/eventloop/threadpool.odin b/pkg/runtime/eventloop/threadpool.odin index 295e6ff3..7b9b6068 100644 --- a/pkg/runtime/eventloop/threadpool.odin +++ b/pkg/runtime/eventloop/threadpool.odin @@ -138,7 +138,10 @@ pool_init :: proc(pool: ^Thread_Pool, allocator: mem.Allocator) { pool_destroy :: proc(pool: ^Thread_Pool, allocator: mem.Allocator) { delete(pool.threads) delete(pool.outstanding) - if pool.pending != nil do delete(pool.pending, allocator) + + if pool.pending != nil { + delete(pool.pending, allocator) + } } // pool_ring_push appends a job at the ring's tail, growing (doubling) when full. @@ -152,10 +155,15 @@ pool_ring_push :: proc(pool: ^Thread_Pool, job: ^Pool_Job, allocator: mem.Alloca for i in 0 ..< pool.pending_count { ns[i] = pool.pending[(pool.pending_head + i) % len(pool.pending)] } - if pool.pending != nil do delete(pool.pending, allocator) + + if pool.pending != nil { + delete(pool.pending, allocator) + } + pool.pending = ns pool.pending_head = 0 } + tail := (pool.pending_head + pool.pending_count) % len(pool.pending) pool.pending[tail] = job pool.pending_count += 1 @@ -183,12 +191,16 @@ pool_submit :: proc( dispose: Pool_Dispose = nil, cancel: Pool_Cancel = nil, ) -> bool { - if loop == nil || work == nil do return false + if loop == nil || work == nil { + return false + } + pool := &loop.pool // Keep the loop alive (and blocking in poll) until the completion is posted. // Undone if the pool can't be started, so the loop is not pinned forever. async_begin(loop) + if !pool_ensure_started(loop) { async_cancel(loop) return false @@ -218,7 +230,11 @@ pool_submit :: proc( @(private = "file") pool_ensure_started :: proc(loop: ^Loop) -> bool { pool := &loop.pool - if pool.started do return true + + if pool.started { + return true + } + pool.stopping = false pool.exited = 0 // Workers receive the loop pointer and reach the pool through loop.pool; the loop @@ -227,13 +243,21 @@ pool_ensure_started :: proc(loop: ^Loop) -> bool { context.allocator = loop.allocator for _ in 0 ..< THREADPOOL_SIZE { th := thread.create(pool_worker) - if th == nil do continue + + if th == nil { + continue + } + th.data = loop thread.start(th) append(&pool.threads, th) } + // As long as one worker started, the pool can make progress. - if len(pool.threads) == 0 do return false + if len(pool.threads) == 0 { + return false + } + pool.started = true return true } @@ -247,26 +271,33 @@ pool_worker :: proc(self: ^thread.Thread) { for pool.pending_count == 0 && !pool.stopping { sync.cond_wait(&pool.wake, &pool.mutex) } + if pool.stopping && pool.pending_count == 0 { // Count out under the mutex, so close_detach and the last worker agree on // who finishes a detached loop: whichever of them sees the other's write. exited := sync.atomic_add(&pool.exited, 1) + 1 last_of_detached := pool.detached && exited == len(pool.threads) sync.unlock(&pool.mutex) + if last_of_detached { pool_release_detached(loop, self) return } + // Wake a driver waiting to reap this loop (close_ready moved). Safe after // the unlock: the pipe closes only after this thread is joined. wakeup(loop) return } + job := pool_ring_pop(pool) // FIFO from the ring head, O(1) job.running = true sync.unlock(&pool.mutex) - if job.work != nil do job.work(job.user_data) + if job.work != nil { + job.work(job.user_data) + } + // Release any per-job scratch the work left on this worker's temp arena. free_all(context.temp_allocator) // Hand back to the loop thread. After this the worker must not touch the job — @@ -287,7 +318,9 @@ pool_worker :: proc(self: ^thread.Thread) { pool_release_detached :: proc(loop: ^Loop, self: ^thread.Thread) { pool := &loop.pool for th in pool.threads { - if th != self do thread.destroy(th) + if th != self { + thread.destroy(th) + } } clear(&pool.threads) sync.atomic_or(&self.flags, {.Self_Cleanup}) @@ -308,7 +341,10 @@ pool_complete :: proc(loop: ^Loop, user_data: rawptr) { done := job.done ud := job.user_data pool_release_job(loop, job) - if done != nil do done(loop, ud) + + if done != nil { + done(loop, ud) + } } @(private = "file") @@ -341,7 +377,11 @@ pool_release_job :: proc(loop: ^Loop, job: ^Pool_Job) { // only; a no-op when the pool never started. pool_stop :: proc(loop: ^Loop) -> (busy: bool) { pool := &loop.pool - if !pool.started do return false + + if !pool.started { + return false + } + sync.lock(&pool.mutex) pool.stopping = true // Drop the queued backlog (the jobs stay in `outstanding`, settled below). @@ -354,14 +394,23 @@ pool_stop :: proc(loop: ^Loop) -> (busy: bool) { i := 0 for i < len(pool.outstanding) { job := pool.outstanding[i] + if job.running { - if job.cancel != nil do job.cancel(job.user_data) + if job.cancel != nil { + job.cancel(job.user_data) + } + busy = true i += 1 continue } + unordered_remove(&pool.outstanding, i) - if job.dispose != nil do job.dispose(job.user_data) + + if job.dispose != nil { + job.dispose(job.user_data) + } + free(job, loop.allocator) } return @@ -371,8 +420,12 @@ pool_stop :: proc(loop: ^Loop) -> (busy: bool) { // as long as a job's `work` does; close_ready says when it will not. close_finish only. pool_join :: proc(loop: ^Loop) { pool := &loop.pool - if !pool.started do return - for th in pool.threads do thread.destroy(th) // joins, then frees through loop.allocator + + if !pool.started { + return + } + + for th in pool.threads {thread.destroy(th)} // joins, then frees through loop.allocator clear(&pool.threads) pool.started = false } @@ -384,7 +437,10 @@ pool_join :: proc(loop: ^Loop) { pool_dispose_outstanding :: proc(loop: ^Loop) { pool := &loop.pool for job in pool.outstanding { - if job.dispose != nil do job.dispose(job.user_data) + if job.dispose != nil { + job.dispose(job.user_data) + } + free(job, loop.allocator) } clear(&pool.outstanding) diff --git a/pkg/runtime/fetch.odin b/pkg/runtime/fetch.odin index 16a4a2b9..77a3b0f5 100644 --- a/pkg/runtime/fetch.odin +++ b/pkg/runtime/fetch.odin @@ -232,9 +232,11 @@ fetch_cancel_fn_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() req := cast(^Fetch_Request)jsc.JSObjectGetPrivate(function) + if req != nil && !req.settled { fetch_request_finish(req) } + return jsc.JSValueMakeUndefined(ctx) } @@ -262,9 +264,11 @@ fetch_resume_fn_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() req := cast(^Fetch_Request)jsc.JSObjectGetPrivate(function) + if req != nil { fetch_resume_read(req) } + return jsc.JSValueMakeUndefined(ctx) } @@ -302,11 +306,13 @@ fetch_push_fn_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() req := cast(^Fetch_Request)jsc.JSObjectGetPrivate(function) + if req != nil && !req.settled && argument_count >= 1 { if view, ok := typed_array_view(ctx, arguments[0]); ok { fetch_push_body(req, view) } } + return jsc.JSValueMakeUndefined(ctx) } @@ -323,17 +329,22 @@ fetch_end_fn_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() req := cast(^Fetch_Request)jsc.JSObjectGetPrivate(function) + if req != nil && !req.settled { is_error := argument_count >= 1 && !jsc.JSValueIsNull(ctx, arguments[0]) && !jsc.JSValueIsUndefined(ctx, arguments[0]) + if is_error { msg, alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if alloc do delete(msg, context.allocator) + defer if alloc { + delete(msg, context.allocator) + } fetch_settle_error(req, msg) } else { fetch_end_body(req) } } + return jsc.JSValueMakeUndefined(ctx) } @@ -346,13 +357,19 @@ fetch_end_fn_cb :: proc "c" ( // Unlike the per-pull async_begin in fetch_body_go_idle, this hold has no matching // post_async, so it is released directly with async_cancel. fetch_body_hold_loop :: proc(req: ^Fetch_Request) { - if req.body_loop_held do return + if req.body_loop_held { + return + } + req.body_loop_held = true eventloop.async_begin(req.loop) } fetch_body_release_loop :: proc(req: ^Fetch_Request) { - if !req.body_loop_held do return + if !req.body_loop_held { + return + } + req.body_loop_held = false eventloop.async_cancel(req.loop) } @@ -396,12 +413,16 @@ fetch_request_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 8 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 8 { + return jsc.JSValueMakeUndefined(ctx) + } on_response := callback_arg(ctx, arguments[4]) on_error := callback_arg(ctx, arguments[5]) on_chunk := callback_arg(ctx, arguments[6]) on_end := callback_arg(ctx, arguments[7]) + if on_response == nil || on_error == nil || on_chunk == nil || on_end == nil { return jsc.JSValueMakeUndefined(ctx) } @@ -410,30 +431,43 @@ fetch_request_cb :: proc "c" ( // arguments[3] carries no bytes — chunks arrive later via push_body_fn. stream_body := argument_count >= 9 && jsc.JSValueToBoolean(ctx, arguments[8]) on_body_drain: jsc.JSObjectRef = nil - if argument_count >= 10 do on_body_drain = callback_arg(ctx, arguments[9]) + + if argument_count >= 10 { + on_body_drain = callback_arg(ctx, arguments[9]) + } + if stream_body && on_body_drain == nil { fetch_reject_now(ctx, on_error, "fetch: streaming body requires a drain callback") return jsc.JSValueMakeUndefined(ctx) } method, method_alloc := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if method_alloc do delete(method, context.allocator) + defer if method_alloc { + delete(method, context.allocator) + } url, url_alloc := jsc_value_to_string_or_default(ctx, arguments[1]) - defer if url_alloc do delete(url, context.allocator) + defer if url_alloc { + delete(url, context.allocator) + } header_lines, header_alloc := jsc_value_to_string_or_default(ctx, arguments[2]) - defer if header_alloc do delete(header_lines, context.allocator) + defer if header_alloc { + delete(header_lines, context.allocator) + } host, port, path, scheme, ok := parse_http_url(url) + if !ok { fetch_reject_now(ctx, on_error, "fetch: invalid URL") return jsc.JSValueMakeUndefined(ctx) } + if scheme != "http" && scheme != "https" { fetch_reject_now(ctx, on_error, "fetch: unsupported URL scheme") return jsc.JSValueMakeUndefined(ctx) } loop := get_loop_from_ctx(ctx) + if loop == nil { fetch_reject_now(ctx, on_error, "fetch: no event loop is bound to this context") return jsc.JSValueMakeUndefined(ctx) @@ -445,15 +479,23 @@ fetch_request_cb :: proc "c" ( // preserves the historical default-heap behavior. state := get_state_from_ctx(ctx) alloc := context.allocator - if state != nil do alloc = state.allocator + + if state != nil { + alloc = state.allocator + } // Reclaim any prior settled requests now that we are safely past the loop // iterations that settled them. - if state != nil do fetch_reclaim_pending(state) + if state != nil { + fetch_reclaim_pending(state) + } body: []byte + if !stream_body { - if view, has_body := typed_array_view(ctx, arguments[3]); has_body do body = view + if view, has_body := typed_array_view(ctx, arguments[3]); has_body { + body = view + } } req := new(Fetch_Request, alloc) @@ -503,15 +545,20 @@ fetch_request_cb :: proc "c" ( // no-ops once their private back-pointer is nulled), so the controls object can // still expose them. push_fn, end_fn: jsc.JSObjectRef + if stream_body { push_fn = jsc.JSObjectMake(ctx, fetch_get_push_class(), req) js_root_set(ctx, &req.push_body_fn, push_fn) end_fn = jsc.JSObjectMake(ctx, fetch_get_end_class(), req) js_root_set(ctx, &req.end_body_fn, end_fn) } - if state != nil do fetch_track_active(state, req) + + if state != nil { + fetch_track_active(state, req) + } started, err := fetch_transport_start(req, host, port) + if !started { fetch_settle_error(req, err) } @@ -523,10 +570,12 @@ fetch_request_cb :: proc "c" ( controls := jsc.JSObjectMake(ctx, nil, nil) set_named(ctx, controls, "cancel", cast(jsc.JSValueRef)cancel_fn) set_named(ctx, controls, "resume", cast(jsc.JSValueRef)resume_fn) + if stream_body { set_named(ctx, controls, "pushBody", cast(jsc.JSValueRef)push_fn) set_named(ctx, controls, "endBody", cast(jsc.JSValueRef)end_fn) } + return cast(jsc.JSValueRef)controls } @@ -557,17 +606,24 @@ parse_http_url :: proc(url: string) -> (host: string, port: int, path: string, s auth_end := len(rest) for i in 0 ..< len(rest) { c := rest[i] + if c == '/' || c == '?' || c == '#' { auth_end = i break } } + if auth_end < len(rest) { authority = rest[:auth_end] target := rest[auth_end:] - if hash := strings.index_byte(target, '#'); hash >= 0 do target = target[:hash] + + if hash := strings.index_byte(target, '#'); hash >= 0 { + target = target[:hash] + } + path = target if len(target) > 0 else "/" } + // Drop any userinfo (user:pass@host). if at := strings.last_index_byte(authority, '@'); at >= 0 { authority = authority[at + 1:] @@ -575,32 +631,56 @@ parse_http_url :: proc(url: string) -> (host: string, port: int, path: string, s host = authority port = 443 if scheme == "https" else 80 + if len(authority) > 0 && authority[0] == '[' { // IPv6 literal (RFC 3986 §3.2.2): the address itself contains colons, so // the host is the bytes inside the brackets and a ":port" suffix can only // follow the closing ']'. Strip the brackets here — the connect path wants // the bare address; build_http_request re-wraps it for the Host header. rb := strings.index_byte(authority, ']') - if rb < 0 do return "", 0, "", "", false + + if rb < 0 { + return "", 0, "", "", false + } + host = authority[1:rb] rest_after := authority[rb + 1:] + if len(rest_after) > 0 { // Only a ":port" may follow the IPv6 literal's closing ']' (RFC 3986 // §3.2.2); any other trailing bytes ("[::1]foo") are malformed. new URL() // rejects these, so this parser must too — defense in depth for callers // that reach it directly. - if rest_after[0] != ':' do return "", 0, "", "", false + if rest_after[0] != ':' { + return "", 0, "", "", false + } + p, p_ok := parse_authority_port(rest_after[1:]) - if !p_ok do return "", 0, "", "", false - if p >= 0 do port = p + + if !p_ok { + return "", 0, "", "", false + } + + if p >= 0 { + port = p + } } } else if colon := strings.last_index_byte(authority, ':'); colon >= 0 { host = authority[:colon] p, p_ok := parse_authority_port(authority[colon + 1:]) - if !p_ok do return "", 0, "", "", false - if p >= 0 do port = p + + if !p_ok { + return "", 0, "", "", false + } + + if p >= 0 { + port = p + } + } + + if len(host) == 0 { + return "", 0, "", "", false } - if len(host) == 0 do return "", 0, "", "", false ok = true return @@ -614,12 +694,21 @@ parse_http_url :: proc(url: string) -> (host: string, port: int, path: string, s // falling back to port 80/443. The JS layer already validates through `new URL`, // so this is defense in depth for any caller that reaches the native parser. parse_authority_port :: proc(s: string) -> (port: int, ok: bool) { - if len(s) == 0 do return -1, true + if len(s) == 0 { + return -1, true + } + for c in transmute([]byte)s { - if c < '0' || c > '9' do return -1, false + if c < '0' || c > '9' { + return -1, false + } } p, p_ok := strconv.parse_int(s) - if !p_ok || p < 0 || p > 65535 do return -1, false + + if !p_ok || p < 0 || p > 65535 { + return -1, false + } + return p, true } @@ -630,7 +719,10 @@ parse_authority_port :: proc(s: string) -> (port: int, ok: bool) { // non-hex byte (so a sign or stray space fails), and a value that would overflow a // positive int. Returns (size, true) only for a well-formed non-negative size. fetch_parse_chunk_size :: proc(s: string) -> (size: int, ok: bool) { - if len(s) == 0 do return 0, false + if len(s) == 0 { + return 0, false + } + v: u64 limit := u64(max(int)) for c in transmute([]byte)s { @@ -645,9 +737,13 @@ fetch_parse_chunk_size :: proc(s: string) -> (size: int, ok: bool) { case: return 0, false // non-hex byte (sign, space, etc.) } + // Reject a size past the positive int range; such a chunk never legitimately // occurs and would otherwise wrap to a negative chunk_remaining. - if v > (limit - d) / 16 do return 0, false + if v > (limit - d) / 16 { + return 0, false + } + v = v * 16 + d } return int(v), true @@ -674,9 +770,13 @@ build_http_request :: proc( b := strings.builder_make(alloc) strings.write_string(&b, method) strings.write_byte(&b, ' ') + // Origin-form request target always begins with '/': a query-only path // ("?x=1", from http://host?x=1) gets the slash prepended here. - if len(path) == 0 || path[0] != '/' do strings.write_byte(&b, '/') + if len(path) == 0 || path[0] != '/' { + strings.write_byte(&b, '/') + } + strings.write_string(&b, path) strings.write_string(&b, " HTTP/1.1\r\n") @@ -684,16 +784,26 @@ build_http_request :: proc( // An IPv6 literal host arrives bracket-stripped (it is the only host that can // contain a colon); RFC 7230 §5.4 requires the Host header to re-wrap it in []. host_is_ip6 := strings.index_byte(host, ':') >= 0 - if host_is_ip6 do strings.write_byte(&b, '[') + + if host_is_ip6 { + strings.write_byte(&b, '[') + } + strings.write_string(&b, host) - if host_is_ip6 do strings.write_byte(&b, ']') + + if host_is_ip6 { + strings.write_byte(&b, ']') + } + // Omit the port when it is the scheme's default (Node sends `Host: host`, not // `host:80` / `host:443`, when the default port was implicit in the URL). default_port := is_https ? 443 : 80 + if port != default_port { strings.write_byte(&b, ':') strings.write_int(&b, port) } + strings.write_string(&b, "\r\n") strings.write_string(&b, header_lines) // each line already ends with \r\n @@ -712,8 +822,12 @@ build_http_request :: proc( strings.write_int(&b, len(body)) strings.write_string(&b, "\r\n") } + strings.write_string(&b, "\r\n") - if len(body) > 0 do strings.write_bytes(&b, body) + + if len(body) > 0 { + strings.write_bytes(&b, body) + } return b.buf[:] } @@ -737,6 +851,7 @@ fetch_on_recv :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, data: []byte) req.head_last_len, ) req.head_last_len = len(req.response) + if res == .Partial { // A server that never terminates the head must not grow req.response // without bound — reject once it crosses the cap. @@ -744,23 +859,30 @@ fetch_on_recv :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, data: []byte) fetch_settle_error(req, "fetch: response head too large") return false } + return true // head still incomplete — read more } + if res == .Error { fetch_settle_error(req, "fetch: malformed HTTP response") return false } + if !fetch_deliver_headers(req, status, status_text, headers, is_chunked, content_length) { return false // settled with an error } - if req.settled do return false // a consumer cancelled inside on_response + + if req.settled {return false} // a consumer cancelled inside on_response + if req.no_body { fetch_finish_body(req, "") // HEAD / 204 / 304 — settle with a null body return false } + // Body bytes that arrived in the same read as the head. return fetch_feed_body(loop, req, req.response[consumed:]) } + return fetch_feed_body(loop, req, data) } @@ -769,16 +891,22 @@ fetch_on_recv :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, data: []byte) // Content-Length met) and on backpressure (the consumer signalled it is full). fetch_feed_body :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, data: []byte) -> (keep: bool) { fetch_stream_feed(req, data) - if req.settled do return false + + if req.settled { + return false + } + if req.body_done { fetch_finish_body(req, "") // clean end of body return false } + if req.want_pause { req.want_pause = false fetch_pause_read(loop, req) return false } + return true } @@ -810,10 +938,12 @@ fetch_deliver_headers :: proc( arg := cast(jsc.JSValueRef)result exception: jsc.JSValueRef invoke_user_callback(req.ctx, req.on_response, &arg, 1, &exception) + if exception != nil { report_uncaught(req.ctx, exception) mark_async_failed(req.ctx) } + return true } @@ -821,7 +951,10 @@ fetch_deliver_headers :: proc( // and any response to HEAD carry no message body. Used to deliver a null // response.body and settle without waiting for body bytes (Node parity). fetch_status_has_no_body :: proc(method: string, status: int) -> bool { - if method == "HEAD" do return true + if method == "HEAD" { + return true + } + switch status { case 101, 103, 204, 205, 304: return true @@ -834,17 +967,22 @@ fetch_status_has_no_body :: proc(method: string, status: int) -> bool { // the read loop can suspend when the consumer is saturated. The copy is required // because `bytes` aliases the transient socket / carry buffer. fetch_deliver_chunk :: proc(req: ^Fetch_Request, bytes: []byte) { - if len(bytes) == 0 do return + if len(bytes) == 0 { + return + } + copy_buf := make([]byte, len(bytes), runtime.heap_allocator()) // freed by jsc_buffer_deallocator, on the heap copy(copy_buf, bytes) arg := make_uint8_array(req.ctx, copy_buf) exception: jsc.JSValueRef result := invoke_user_callback(req.ctx, req.on_chunk, &arg, 1, &exception) + if exception != nil { report_uncaught(req.ctx, exception) mark_async_failed(req.ctx) return } + // A falsey return (desiredSize <= 0) asks the transport to apply backpressure. if result != nil && !bool(jsc.JSValueToBoolean(req.ctx, result)) { req.want_pause = true @@ -855,17 +993,22 @@ fetch_deliver_chunk :: proc(req: ^Fetch_Request, bytes: []byte) { // a clean completion, the message string on a failure (which errors the JS body // stream) — then tears the request down. message == "" is the clean case. fetch_finish_body :: proc(req: ^Fetch_Request, message: string) { - if req.settled do return + if req.settled { + return + } + arg: jsc.JSValueRef = len(message) == 0 ? jsc.JSValueMakeNull(req.ctx) : js_string_value(req.ctx, message) exception: jsc.JSValueRef // Callback BEFORE finish, preserving the async-count invariant: the socket is // still watched here, so a chained fetch() inside the body's consumer keeps the // loop's in-flight count ≥ 1 across the teardown. invoke_user_callback(req.ctx, req.on_end, &arg, 1, &exception) + if exception != nil { report_uncaught(req.ctx, exception) mark_async_failed(req.ctx) } + fetch_request_finish(req) } @@ -874,11 +1017,15 @@ fetch_finish_body :: proc(req: ^Fetch_Request, message: string) { // clean end; a close mid-body under a declared length or chunked framing is a // truncation that Node surfaces as "terminated". fetch_eof :: proc(req: ^Fetch_Request) { - if req.settled do return + if req.settled { + return + } + if !req.headers_done { fetch_settle_error(req, "fetch: connection closed before headers") return } + switch { case req.body_is_chunked: fetch_finish_body(req, req.body_done ? "" : "fetch: terminated") @@ -898,17 +1045,21 @@ fetch_settle_error :: proc(req: ^Fetch_Request, message: string) { fetch_request_finish(req) return } + if req.headers_done { fetch_finish_body(req, message) return } + arg := js_string_value(req.ctx, message) exception: jsc.JSValueRef invoke_user_callback(req.ctx, req.on_error, &arg, 1, &exception) + if exception != nil { report_uncaught(req.ctx, exception) mark_async_failed(req.ctx) } + fetch_request_finish(req) } @@ -918,7 +1069,10 @@ fetch_settle_error :: proc(req: ^Fetch_Request, message: string) { // stops keeping the loop alive — matching Node, where an abandoned response body // does not pin the process. fetch_resume_read re-arms when the consumer drains. fetch_pause_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { - if req.read_paused || !req.has_fd do return + if req.read_paused || !req.has_fd { + return + } + req.read_paused = true req.watcher.callback = nil eventloop.unwatch_fd(loop, &req.watcher) @@ -930,7 +1084,10 @@ fetch_pause_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // buffered in the TLS layer — which raise no fresh socket-readable event — are // flushed. A no-op unless actually paused, so the stream may call it on every read. fetch_resume_read :: proc(req: ^Fetch_Request) { - if req.settled || !req.read_paused || !req.has_fd do return + if req.settled || !req.read_paused || !req.has_fd { + return + } + req.read_paused = false req.watcher.callback = fetch_watcher_cb req.watcher.mode = .Read @@ -950,10 +1107,21 @@ fetch_resume_read :: proc(req: ^Fetch_Request) { // only touches the socket when the request is still actively reading. fetch_drive_read_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { req := cast(^Fetch_Request)user_data - if req == nil do return + + if req == nil { + return + } + req.drive_pending -= 1 - if req.settled || req.read_paused do return - if !req.has_fd || req.phase != .Reading do return + + if req.settled || req.read_paused { + return + } + + if !req.has_fd || req.phase != .Reading { + return + } + fetch_watcher_cb(loop, req) } @@ -975,19 +1143,26 @@ fetch_reject_now :: proc(ctx: jsc.JSContextRef, on_error: jsc.JSObjectRef, messa // fetch_reclaim_pending). Clearing req.watcher.callback below makes the request // inert immediately; unwatch_fd then truly cancels the io_uring poll (#183). fetch_request_finish :: proc(req: ^Fetch_Request) { - if req.settled do return + if req.settled { + return + } + // A DNS lookup may still be outstanding on the pool. We do NOT block to join it // (the pool owns the worker lifetime); the request stays pinned via drive_pending // — bumped at submit — so the pending completion finds live memory, sees // req.settled, and reclaims it. See fetch_dns.odin. If the lookup is still // queued, cancel it so the worker skips the blocking resolve rather than doing // network work for an aborted fetch (and holding the loop alive until it returns). - if req.dns_job != nil do fetch_dns_cancel_job(req.dns_job) + if req.dns_job != nil { + fetch_dns_cancel_job(req.dns_job) + } + req.settled = true // Stamp the settle iteration so fetch_reclaim_pending holds this request a couple // of loop ticks — past the in-flight platform_poll batch that may still carry a // readiness event for it on the pointer-based backends. req.settle_tick = eventloop.iteration_count(req.loop) + if state := get_state_from_ctx(req.ctx); state != nil { fetch_untrack_active(state, req) } @@ -997,6 +1172,7 @@ fetch_request_finish :: proc(req: ^Fetch_Request) { req.watcher.callback = nil // Free the TLS session (if any) before closing the fd it was bound to. fetch_tls_cleanup(req) + if req.has_fd { eventloop.unwatch_fd(req.loop, &req.watcher) fetch_close_fd(req.fd) @@ -1030,12 +1206,18 @@ fetch_request_finish :: proc(req: ^Fetch_Request) { } fetch_track_active :: proc(state: ^Runtime_State, req: ^Fetch_Request) { - if state == nil || req == nil do return + if state == nil || req == nil { + return + } + append(&state.active_fetches, req) } fetch_untrack_active :: proc(state: ^Runtime_State, req: ^Fetch_Request) { - if state == nil || req == nil do return + if state == nil || req == nil { + return + } + for i in 0 ..< len(state.active_fetches) { if state.active_fetches[i] == req { // active_fetches is an unordered bag (membership only — used for teardown), @@ -1058,7 +1240,10 @@ fetch_untrack_active :: proc(state: ^Runtime_State, req: ^Fetch_Request) { // deferred teardown, destroy_runtime_state, and fetch_destroy_pending): each // fetch_request_finish untracks its request, so a second pass sees an empty set. fetch_shutdown_active :: proc(state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + for len(state.active_fetches) > 0 { req := state.active_fetches[0] fetch_request_finish(req) @@ -1077,7 +1262,11 @@ fetch_free_request :: proc(req: ^Fetch_Request) { delete(req.url, req.allocator) delete(req.host, req.allocator) delete(req.path, req.allocator) - if req.request_bytes != nil do delete(req.request_bytes, req.allocator) + + if req.request_bytes != nil { + delete(req.request_bytes, req.allocator) + } + delete(req.response) delete(req.carry) delete(req.body_out) @@ -1107,11 +1296,13 @@ fetch_reclaim_pending :: proc(state: ^Runtime_State) { kept := 0 for req in state.pending_free { within_stale_window := eventloop.iteration_count(req.loop) - req.settle_tick < 2 + if req.drive_pending > 0 || within_stale_window { state.pending_free[kept] = req kept += 1 continue } + fetch_free_request(req) } resize(&state.pending_free, kept) @@ -1155,7 +1346,10 @@ parse_http_head :: proc( raw: [pico.MAX_HEADERS]pico.Header n_consumed, code, msg, n, res := pico.parse_response(buf, last_len, raw[:]) result = res - if res != .Complete do return + + if res != .Complete { + return + } consumed = n_consumed status = code @@ -1168,6 +1362,7 @@ parse_http_head :: proc( last_val_idx := -1 for i in 0 ..< n { h := raw[i] + if h.name == "" { // RFC 7230 obs-fold continuation: append (single space) to the previous // value rather than drop it. Deprecated, but unfolding avoids silent @@ -1179,8 +1374,10 @@ parse_http_head :: proc( context.temp_allocator, ) } + continue } + value := strings.trim_space(h.value) append(&hdr_list, h.name) append(&hdr_list, value) @@ -1190,9 +1387,14 @@ parse_http_head :: proc( // allocates nothing); only the rare Transfer-Encoding value is lowercased. if strings.equal_fold(h.name, "transfer-encoding") { lvalue := strings.to_lower(value, context.temp_allocator) - if strings.contains(lvalue, "chunked") do is_chunked = true + + if strings.contains(lvalue, "chunked") { + is_chunked = true + } } else if strings.equal_fold(h.name, "content-length") { - if cl, cl_ok := strconv.parse_int(value); cl_ok do content_length = cl + if cl, cl_ok := strconv.parse_int(value); cl_ok { + content_length = cl + } } } headers = hdr_list[:] @@ -1209,20 +1411,30 @@ fetch_stream_feed :: proc(req: ^Fetch_Request, data: []byte) { fetch_feed_chunked(req, data) return } + remaining := data + if req.body_len >= 0 { want := req.body_len - req.body_seen + if want <= 0 { req.body_done = true return } - if len(remaining) > want do remaining = remaining[:want] + + if len(remaining) > want { + remaining = remaining[:want] + } } + if len(remaining) > 0 { fetch_deliver_chunk(req, remaining) req.body_seen += len(remaining) } - if req.body_len >= 0 && req.body_seen >= req.body_len do req.body_done = true + + if req.body_len >= 0 && req.body_seen >= req.body_len { + req.body_done = true + } } // fetch_feed_chunked is the incremental Transfer-Encoding: chunked decoder. It @@ -1246,6 +1458,7 @@ fetch_feed_chunked :: proc(req: ^Fetch_Request, data: []byte) { break } } + if line_end < 0 { // A chunk-size line that never terminates must not grow carry // without bound — fail the body as a framing violation. @@ -1253,46 +1466,64 @@ fetch_feed_chunked :: proc(req: ^Fetch_Request, data: []byte) { fetch_finish_body(req, "fetch: terminated") return } + break loop // size line not complete yet } + size_str := string(buf[pos:line_end]) - if semi := strings.index_byte(size_str, ';'); semi >= 0 do size_str = size_str[:semi] + + if semi := strings.index_byte(size_str, ';'); semi >= 0 { + size_str = size_str[:semi] + } + size, size_ok := fetch_parse_chunk_size(strings.trim_space(size_str)) + if !size_ok { // Malformed chunk size (non-hex, signed, empty, or overflowing) — // fail the body stream as a truncation. fetch_finish_body(req, "fetch: terminated") return } + pos = line_end + 2 + if size == 0 { req.body_done = true req.chunk_state = .Done break loop } + req.chunk_remaining = size req.chunk_state = .Data case .Data: avail := len(buf) - pos take := min(avail, req.chunk_remaining) + if take > 0 { fetch_deliver_chunk(req, buf[pos:pos + take]) - if req.settled do return + + if req.settled { + return + } + pos += take req.chunk_remaining -= take } - if req.chunk_remaining > 0 do break loop // need more data + + if req.chunk_remaining > 0 {break loop} // need more data req.chunk_state = .Data_CRLF case .Data_CRLF: - if len(buf) - pos < 2 do break loop // CRLF not fully arrived + if len(buf) - pos < 2 {break loop} // CRLF not fully arrived + // RFC 7230: chunk data is always followed by CRLF. A different byte pair // means the framing is corrupt — fail rather than resync on garbage. if buf[pos] != '\r' || buf[pos + 1] != '\n' { fetch_finish_body(req, "fetch: terminated") return } + pos += 2 // skip the chunk-terminating CRLF req.chunk_state = .Size diff --git a/pkg/runtime/fetch_darwin.odin b/pkg/runtime/fetch_darwin.odin index 7239e448..9fc856e2 100644 --- a/pkg/runtime/fetch_darwin.odin +++ b/pkg/runtime/fetch_darwin.odin @@ -29,12 +29,18 @@ fetch_close_fd :: proc(fd: uintptr) { @(private = "file") fetch_new_socket :: proc(family: posix.AF) -> posix.FD { fd := posix.socket(family, .STREAM) - if fd < 0 do return -1 + + if fd < 0 { + return -1 + } + if posix.fcntl(fd, .SETFL, posix.O_Flags{.NONBLOCK}) == -1 { posix.close(fd) return -1 } + one: c.int = 1 + if posix.setsockopt( fd, c.int(posix.SOL_SOCKET), @@ -46,6 +52,7 @@ fetch_new_socket :: proc(family: posix.AF) -> posix.FD { posix.close(fd) return -1 } + return fd } @@ -55,28 +62,39 @@ fetch_new_socket :: proc(family: posix.AF) -> posix.FD { // expected; any other failure rejects. Both run on the loop thread. fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) -> (ok: bool, err: string) { fd := fetch_new_socket(.INET) - if fd < 0 do return false, "fetch: could not create socket" + + if fd < 0 { + return false, "fetch: could not create socket" + } + addr := posix.sockaddr_in { sin_len = size_of(posix.sockaddr_in), sin_family = cast(posix.sa_family_t)posix.AF.INET, sin_port = u16be(port), sin_addr = {s_addr = transmute(posix.in_addr_t)ip4}, } + if posix.connect(fd, cast(^posix.sockaddr)&addr, posix.socklen_t(size_of(addr))) != .OK { // EINPROGRESS (and EINTR, a signal interrupting the call) both mean the // connect proceeds asynchronously; anything else is a hard failure. e := posix.errno() + if e != .EINPROGRESS && e != .EINTR { posix.close(fd) return false, "fetch: connect failed" } } + return fetch_register_socket(req, uintptr(fd)) } fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) -> (ok: bool, err: string) { fd := fetch_new_socket(.INET6) - if fd < 0 do return false, "fetch: could not create socket" + + if fd < 0 { + return false, "fetch: could not create socket" + } + // IP6_Address is [8]u16be, whose memory layout is already the 16 network-order // bytes sin6_addr expects. addr := posix.sockaddr_in6 { @@ -85,15 +103,18 @@ fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) sin6_port = u16be(port), } addr.sin6_addr.s6_addr = transmute([16]u8)ip6 + if posix.connect(fd, cast(^posix.sockaddr)&addr, posix.socklen_t(size_of(addr))) != .OK { // EINPROGRESS (and EINTR, a signal interrupting the call) both mean the // connect proceeds asynchronously; anything else is a hard failure. e := posix.errno() + if e != .EINPROGRESS && e != .EINTR { posix.close(fd) return false, "fetch: connect failed" } } + return fetch_register_socket(req, uintptr(fd)) } @@ -110,7 +131,10 @@ fetch_connect_succeeded :: proc(req: ^Fetch_Request) -> bool { // suppressed via SO_NOSIGPIPE, so a reset peer surfaces as EPIPE here. fetch_raw_send :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetch_IO_Result) { sent := posix.send(posix.FD(req.fd), raw_data(chunk), len(chunk), {}) - if sent >= 0 do return int(sent), .Ok + + if sent >= 0 { + return int(sent), .Ok + } #partial switch posix.errno() { case .EAGAIN: // == EWOULDBLOCK on Darwin @@ -127,8 +151,14 @@ fetch_raw_send :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetc // close (.Closed); EAGAIN means wait for more data. fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_IO_Result) { got := posix.recv(posix.FD(req.fd), raw_data(buf), len(buf), {}) - if got > 0 do return int(got), .Ok - if got == 0 do return 0, .Closed + + if got > 0 { + return int(got), .Ok + } + + if got == 0 { + return 0, .Closed + } #partial switch posix.errno() { case .EAGAIN: // == EWOULDBLOCK on Darwin @@ -146,7 +176,10 @@ fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_ // explicit unwatch + rewatch to flip the EVFILT_READ/EVFILT_WRITE interest; a // no-op when the mode is unchanged. fetch_set_watch_mode :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, mode: eventloop.Poll_Mode) -> bool { - if req.watcher.mode == mode do return true + if req.watcher.mode == mode { + return true + } + eventloop.unwatch_fd(loop, &req.watcher) req.watcher.mode = mode return eventloop.watch_fd(loop, &req.watcher) diff --git a/pkg/runtime/fetch_dns.odin b/pkg/runtime/fetch_dns.odin index 6fc47645..5b09acc8 100644 --- a/pkg/runtime/fetch_dns.odin +++ b/pkg/runtime/fetch_dns.odin @@ -55,12 +55,14 @@ fetch_dns_submit :: proc(req: ^Fetch_Request, host: string) -> bool { job.host = strings.clone(host, job.allocator) job.req = req req.dns_job = job // back-pointer so an abort before the completion can cancel it + if !eventloop.pool_submit(req.loop, dns_resolve_work, dns_resolve_done, job, dns_resolve_dispose) { req.dns_job = nil delete(job.host, job.allocator) free(job, job.allocator) return false } + return true } @@ -71,7 +73,11 @@ fetch_dns_submit :: proc(req: ^Fetch_Request, host: string) -> bool { @(private = "file") dns_resolve_work :: proc(user_data: rawptr) { job := cast(^DNS_Job)user_data - if sync.atomic_load(&job.cancelled) do return + + if sync.atomic_load(&job.cancelled) { + return + } + if ep4, ep6, dns_err := net.resolve(job.host); dns_err == nil { if ip4, ip_ok := ep4.address.(net.IP4_Address); ip_ok { job.addrs[job.addr_count] = Fetch_Addr { @@ -80,6 +86,7 @@ dns_resolve_work :: proc(user_data: rawptr) { } job.addr_count += 1 } + if ip6, ip_ok := ep6.address.(net.IP6_Address); ip_ok { job.addrs[job.addr_count] = Fetch_Addr { is_v6 = true, @@ -99,16 +106,26 @@ dns_resolve_done :: proc(loop: ^eventloop.Loop, user_data: rawptr) { req := job.req addrs := job.addrs addr_count := job.addr_count - if req != nil do req.dns_job = nil // drop the back-pointer before the job is freed + + if req != nil {req.dns_job = nil} // drop the back-pointer before the job is freed delete(job.host, job.allocator) free(job, job.allocator) - if req == nil do return + + if req == nil { + return + } + req.drive_pending -= 1 - if req.settled do return + + if req.settled { + return + } + if addr_count == 0 { fetch_settle_error(req, "fetch: could not resolve host") return } + // Hand the resolved list to the request and connect to the first address; // fetch_advance_connect falls through to the next on a connect failure (#145). req.addrs = addrs diff --git a/pkg/runtime/fetch_linux.odin b/pkg/runtime/fetch_linux.odin index 26511890..bdaa6a43 100644 --- a/pkg/runtime/fetch_linux.odin +++ b/pkg/runtime/fetch_linux.odin @@ -19,13 +19,18 @@ fetch_close_fd :: proc(fd: uintptr) { // == connect completion). Both run on the loop thread. fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) -> (ok: bool, err: string) { sock_fd, sock_err := linux.socket(.INET, .STREAM, {.NONBLOCK}, .TCP) - if sock_err != .NONE do return false, "fetch: could not create socket" + + if sock_err != .NONE { + return false, "fetch: could not create socket" + } + // net.IP4_Address is [4]u8 in network order — exactly the bytes sin_addr wants. addr := linux.Sock_Addr_In { sin_family = .INET, sin_port = u16be(port), sin_addr = transmute([4]u8)ip4, } + // EINTR: a signal interrupted connect() before it could report EINPROGRESS; // the connection still proceeds asynchronously, so treat it like EINPROGRESS // rather than a hard failure. @@ -33,12 +38,17 @@ fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) linux.close(sock_fd) return false, "fetch: connect failed" } + return fetch_register_socket(req, uintptr(sock_fd)) } fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) -> (ok: bool, err: string) { sock_fd, sock_err := linux.socket(.INET6, .STREAM, {.NONBLOCK}, .TCP) - if sock_err != .NONE do return false, "fetch: could not create socket" + + if sock_err != .NONE { + return false, "fetch: could not create socket" + } + // IP6_Address is [8]u16be, whose memory layout is already the 16 network-order // bytes sin6_addr expects. addr := linux.Sock_Addr_In6 { @@ -46,6 +56,7 @@ fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) sin6_port = u16be(port), sin6_addr = transmute([16]u8)ip6, } + // EINTR: a signal interrupted connect() before it could report EINPROGRESS; // the connection still proceeds asynchronously, so treat it like EINPROGRESS // rather than a hard failure. @@ -53,6 +64,7 @@ fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) linux.close(sock_fd) return false, "fetch: connect failed" } + return fetch_register_socket(req, uintptr(sock_fd)) } @@ -116,11 +128,15 @@ fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_ // mutating the field is enough; epoll needs an explicit re-registration. A no-op // when the mode is unchanged. fetch_set_watch_mode :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, mode: eventloop.Poll_Mode) -> bool { - if req.watcher.mode == mode do return true + if req.watcher.mode == mode { + return true + } + if loop.platform.use_uring { req.watcher.mode = mode return true } + eventloop.unwatch_fd(loop, &req.watcher) req.watcher.mode = mode return eventloop.watch_fd(loop, &req.watcher) diff --git a/pkg/runtime/fetch_tls.odin b/pkg/runtime/fetch_tls.odin index 8a4fecd5..f3f110a0 100644 --- a/pkg/runtime/fetch_tls.odin +++ b/pkg/runtime/fetch_tls.odin @@ -34,10 +34,12 @@ fetch_tls_cleanup :: proc(req: ^Fetch_Request) { // setup failure it settles the request with an error. fetch_tls_start_handshake :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { ssl := tls_new_client(req.fd, req.host) + if ssl == nil { fetch_settle_error(req, "fetch: TLS setup failed") return } + req.tls = rawptr(ssl) req.phase = .TLS_Handshake fetch_tls_handshake(loop, req) // try the handshake immediately @@ -79,11 +81,13 @@ fetch_tls_classify :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, ret: c.in // An EOF mid-handshake is fatal — there is no response to complete yet. fetch_tls_handshake :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { ret := SSL_connect(cast(SSL)req.tls) + if ret == 1 { req.phase = .Writing fetch_write(loop, req) return } + if fetch_tls_classify(loop, req, ret) != .Pending { fetch_settle_error(req, "fetch: TLS handshake failed") } @@ -95,14 +99,17 @@ fetch_tls_write :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { for req.write_offset < len(req.request_bytes) { chunk := req.request_bytes[req.write_offset:] n := SSL_write(cast(SSL)req.tls, raw_data(chunk), c.int(len(chunk))) + if n <= 0 { // An EOF while still sending the request is a failure, not completion, // so .Eof falls in with .Fatal here. if fetch_tls_classify(loop, req, n) != .Pending { fetch_settle_error(req, "fetch: TLS write failed") } + return } + req.write_offset += int(n) } fetch_after_write_head(loop, req) @@ -118,7 +125,11 @@ fetch_tls_write :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // peer's renegotiation bytes can only be read. fetch_tls_send_chunk :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetch_IO_Result, want_read: bool) { ret := SSL_write(cast(SSL)req.tls, raw_data(chunk), c.int(len(chunk))) - if ret > 0 do return int(ret), .Ok, false + + if ret > 0 { + return int(ret), .Ok, false + } + switch SSL_get_error(cast(SSL)req.tls, ret) { case SSL_ERROR_WANT_READ: return 0, .Would_Block, true @@ -141,6 +152,7 @@ fetch_tls_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { buf: [16384]byte for { n := SSL_read(cast(SSL)req.tls, raw_data(buf[:]), c.int(len(buf))) + if n <= 0 { switch fetch_tls_classify(loop, req, n) { case .Pending: @@ -151,6 +163,9 @@ fetch_tls_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { } return } - if !fetch_on_recv(loop, req, buf[:int(n)]) do return + + if !fetch_on_recv(loop, req, buf[:int(n)]) { + return + } } } diff --git a/pkg/runtime/fetch_tls_darwin.odin b/pkg/runtime/fetch_tls_darwin.odin index 0c0bd3e6..00cfeab1 100644 --- a/pkg/runtime/fetch_tls_darwin.odin +++ b/pkg/runtime/fetch_tls_darwin.odin @@ -33,10 +33,12 @@ fetch_tls_cleanup :: proc(req: ^Fetch_Request) { // it settles the request with an error. fetch_tls_start_handshake :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { sess := darwin_tls_new_client(req.fd, req.host) + if sess == nil { fetch_settle_error(req, "fetch: TLS setup failed") return } + req.tls = rawptr(sess) req.phase = .TLS_Handshake fetch_tls_handshake(loop, req) // try the handshake immediately @@ -80,11 +82,13 @@ fetch_tls_handshake :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { sess := cast(^Darwin_TLS_Session)req.tls for { status := SSLHandshake(sess.ctx) + if status == errSecSuccess { req.phase = .Writing fetch_write(loop, req) return } + if status == errSSLPeerAuthCompleted { // The server cert is in hand; verify it (fail closed), then re-drive the // handshake to completion. @@ -92,11 +96,14 @@ fetch_tls_handshake :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { fetch_settle_error(req, "fetch: TLS certificate verification failed") return } + continue } + if fetch_tls_classify(loop, req, status) != .Pending { fetch_settle_error(req, "fetch: TLS handshake failed") } + return } } @@ -123,18 +130,22 @@ fetch_tls_handshake :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { @(private = "file") darwin_tls_write_chunk :: proc(sess: ^Darwin_TLS_Session, buf: []byte) -> (consumed: int, status: OSStatus) { skip := sess.write_skip - if skip > len(buf) do skip = len(buf) // defensive — buffer is stable across retries + + if skip > len(buf) {skip = len(buf)} // defensive — buffer is stable across retries tail := buf[skip:] processed: c.size_t st := SSLWrite(sess.ctx, raw_data(tail), c.size_t(len(tail)), &processed) + if st == errSecSuccess { sess.write_skip = 0 return len(buf), errSecSuccess } + if st == errSSLWouldBlock { sess.write_skip = skip + int(processed) return 0, errSSLWouldBlock } + return 0, st } @@ -146,13 +157,16 @@ fetch_tls_write :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { for req.write_offset < len(req.request_bytes) { chunk := req.request_bytes[req.write_offset:] n, status := darwin_tls_write_chunk(sess, chunk) + if status != errSecSuccess { // An EOF/close while still sending the request is a failure, not completion. if fetch_tls_classify(loop, req, status) != .Pending { fetch_settle_error(req, "fetch: TLS write failed") } + return } + req.write_offset += n } fetch_after_write_head(loop, req) @@ -193,9 +207,13 @@ fetch_tls_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { for { processed: c.size_t status := SSLRead(sess.ctx, raw_data(buf[:]), c.size_t(len(buf)), &processed) + if processed > 0 { - if !fetch_on_recv(loop, req, buf[:int(processed)]) do return + if !fetch_on_recv(loop, req, buf[:int(processed)]) { + return + } } + if status == errSecSuccess { if processed == 0 { // Defensive: success with no data should not happen for a non-empty @@ -203,10 +221,13 @@ fetch_tls_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { if !fetch_set_watch_mode(loop, req, .Read) { fetch_settle_error(req, "fetch: event loop watch failed") } + return } + continue // drain any further buffered records } + switch fetch_tls_classify(loop, req, status) { case .Pending: case .Eof: diff --git a/pkg/runtime/fetch_transport.odin b/pkg/runtime/fetch_transport.odin index 269ff432..a6934c94 100644 --- a/pkg/runtime/fetch_transport.odin +++ b/pkg/runtime/fetch_transport.odin @@ -41,7 +41,11 @@ fetch_transport_start :: proc(req: ^Fetch_Request, host: string, port: int) -> ( // parse_http_url and is the only host that can contain a colon. if strings.index_byte(host, ':') >= 0 { ip6, ip_ok := net.parse_ip6_address(host) - if !ip_ok do return false, "fetch: could not resolve host" + + if !ip_ok { + return false, "fetch: could not resolve host" + } + return fetch_connect_ip6(req, ip6, port) } @@ -56,10 +60,12 @@ fetch_transport_start :: proc(req: ^Fetch_Request, host: string, port: int) -> ( // does its own async_begin loop keep-alive (and undoes it on a start failure), so we only unwind // our own drive_pending pin here. req.drive_pending += 1 + if !fetch_dns_submit(req, host) { req.drive_pending -= 1 return false, "fetch: could not start DNS resolver" } + return true, "" } @@ -76,11 +82,13 @@ fetch_register_socket :: proc(req: ^Fetch_Request, fd: uintptr) -> (ok: bool, er callback = fetch_watcher_cb, user_data = req, } + if !eventloop.watch_fd(req.loop, &req.watcher) { fetch_close_fd(fd) req.has_fd = false return false, "fetch: could not register socket with the event loop" } + return true, "" } @@ -98,19 +106,23 @@ fetch_advance_connect :: proc(req: ^Fetch_Request) { fetch_close_fd(req.fd) req.has_fd = false } + for req.addr_index < req.addr_count { a := req.addrs[req.addr_index] req.addr_index += 1 connected: bool + if a.is_v6 { connected, _ = fetch_connect_ip6(req, a.v6, req.port) } else { connected, _ = fetch_connect_ip4(req, a.v4, req.port) } - if connected do return // connect initiated; wait for the writable event + + if connected {return} // connect initiated; wait for the writable event // A synchronous connect failure (socket create / immediate connect error) // closed its own socket — fall through to the next address. } + fetch_settle_error(req, "fetch: could not connect to host") } @@ -119,7 +131,10 @@ fetch_advance_connect :: proc(req: ^Fetch_Request) { // settle. EAGAIN / WANT_* means "not ready, wait for the next event". fetch_watcher_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { req := cast(^Fetch_Request)user_data - if req == nil || req.settled do return + + if req == nil || req.settled { + return + } switch req.phase { case .Connecting: @@ -129,12 +144,14 @@ fetch_watcher_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { fetch_advance_connect(req) return } + if req.is_https { // TLS is a platform-swappable backend: set up the session and run the first // handshake step, settling on its own error if unsupported. fetch_tls_start_handshake(loop, req) return } + req.phase = .Writing fetch_write(loop, req) // socket is writable now, try sending immediately @@ -160,6 +177,7 @@ fetch_write :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { fetch_tls_write(loop, req) return } + for req.write_offset < len(req.request_bytes) { chunk := req.request_bytes[req.write_offset:] n, res := fetch_raw_send(req, chunk) @@ -169,12 +187,17 @@ fetch_write :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { if !fetch_set_watch_mode(loop, req, .Write) { fetch_settle_error(req, "fetch: event loop watch failed") } + return // wait for the next writable event case .Closed, .Failed: fetch_settle_error(req, "fetch: send failed") return } - if n <= 0 do return + + if n <= 0 { + return + } + req.write_offset += n } fetch_after_write_head(loop, req) @@ -190,16 +213,20 @@ fetch_read :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { fetch_tls_read(loop, req) return } + buf: [16384]byte for { n, res := fetch_raw_recv(req, buf[:]) switch res { case .Ok: - if !fetch_on_recv(loop, req, buf[:n]) do return + if !fetch_on_recv(loop, req, buf[:n]) { + return + } case .Would_Block: if !fetch_set_watch_mode(loop, req, .Read) { fetch_settle_error(req, "fetch: event loop watch failed") } + return // wait for more data case .Closed: fetch_eof(req) // EOF — server closed @@ -246,9 +273,11 @@ fetch_after_write_head :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { fetch_settle_error(req, "fetch: event loop watch failed") return } + req.phase = .Reading // next readable event reads the response return } + req.phase = .Body_Write // Pin the loop for the whole upload so an in-flight chunked upload keeps the // process alive like Node's outgoing socket: while idle (awaiting the producer) @@ -263,7 +292,7 @@ fetch_after_write_head :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // writable. While idle (awaiting the producer) the fd is unwatched, so a delivered // event always has a partially-written frame to flush. fetch_write_body_event :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { - if req.body_idle do return // defensive: a stale completion while awaiting the producer + if req.body_idle {return} // defensive: a stale completion while awaiting the producer fetch_pump_body(loop, req) } @@ -271,12 +300,17 @@ fetch_write_body_event :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // pull/push protocol guarantees body_out is empty on entry (one chunk in flight). // Runs on the loop thread (push_body_fn, from the JS pump). fetch_push_body :: proc(req: ^Fetch_Request, data: []byte) { - if req.settled || !req.body_streaming || req.phase != .Body_Write do return + if req.settled || !req.body_streaming || req.phase != .Body_Write { + return + } + req.body_idle = false + if len(data) == 0 { fetch_body_go_idle(req) // an empty chunk frames to nothing — pull the next return } + fetch_frame_chunk(req, data) fetch_pump_body(req.loop, req) } @@ -285,9 +319,13 @@ fetch_push_body :: proc(req: ^Fetch_Request, data: []byte) { // Runs on the loop thread (end_body_fn) while idle, so body_out is empty; // fetch_pump_body appends and flushes the terminator, then flips to reading. fetch_end_body :: proc(req: ^Fetch_Request) { - if req.settled || !req.body_streaming || req.phase != .Body_Write do return + if req.settled || !req.body_streaming || req.phase != .Body_Write { + return + } + req.body_idle = false req.body_end_seen = true + // Idle ⇒ nothing pending: drive the terminator now. (If a frame were still in // flight, fetch_pump_body's drain would append the terminator itself.) if req.body_out_off >= len(req.body_out) { @@ -303,7 +341,8 @@ fetch_pump_body :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { for { for req.body_out_off < len(req.body_out) { n, res := fetch_body_send(req, req.body_out[req.body_out_off:]) - if req.settled do return // arming the watcher failed and settled the request + + if req.settled {return} // arming the watcher failed and settled the request switch res { case .Ok: if n <= 0 { @@ -314,6 +353,7 @@ fetch_pump_body :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { fetch_body_arm(req, .Write) return } + req.body_out_off += n case .Would_Block: return // fetch_body_send armed the fd for the right direction @@ -325,6 +365,7 @@ fetch_pump_body :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // The current frame is fully written. clear(&req.body_out) req.body_out_off = 0 + if req.body_term_written { // Upload complete: drop the body-phase loop hold and watch for the response. fetch_body_release_loop(req) @@ -332,11 +373,13 @@ fetch_pump_body :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { req.phase = .Reading return } + if req.body_end_seen { append(&req.body_out, '0', '\r', '\n', '\r', '\n') // terminating zero chunk req.body_term_written = true continue // loop to flush the terminator } + fetch_body_go_idle(req) // pull the next chunk from the producer return } @@ -349,14 +392,19 @@ fetch_pump_body :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request) { // the TLS backend. fetch_body_send :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetch_IO_Result) { want_read: bool + if req.is_https { n, res, want_read = fetch_tls_send_chunk(req, chunk) } else { n, res = fetch_raw_send(req, chunk) } + // Stay in .Body_Write whichever direction we arm: the readiness event re-enters // fetch_write_body_event, which retries the flush regardless of read/write wake. - if res == .Would_Block do fetch_body_arm(req, want_read ? .Read : .Write) + if res == .Would_Block { + fetch_body_arm(req, want_read ? .Read : .Write) + } + return } @@ -378,6 +426,7 @@ fetch_append_hex :: proc(buf: ^[dynamic]byte, value: int) { append(buf, '0') return } + digits := "0123456789abcdef" tmp: [16]byte n := value @@ -398,12 +447,17 @@ fetch_append_hex :: proc(buf: ^[dynamic]byte, value: int) { // microtask auto-drain; async_begin keeps the loop alive across the pull and // drive_pending pins the request against reclaim until the deferred pull has run. fetch_body_go_idle :: proc(req: ^Fetch_Request) { - if req.settled do return + if req.settled { + return + } + req.body_idle = true + if req.has_fd && req.watcher.watched { req.watcher.callback = nil eventloop.unwatch_fd(req.loop, &req.watcher) } + req.drive_pending += 1 eventloop.async_begin(req.loop) eventloop.post_async(req.loop, fetch_body_drain_cb, req) @@ -415,11 +469,20 @@ fetch_body_go_idle :: proc(req: ^Fetch_Request) { // pulls when still idle in the body-write phase. fetch_body_drain_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { req := cast(^Fetch_Request)user_data - if req == nil do return + + if req == nil { + return + } + req.drive_pending -= 1 - if req.settled || !req.body_idle || req.on_body_drain == nil do return + + if req.settled || !req.body_idle || req.on_body_drain == nil { + return + } + exception: jsc.JSValueRef invoke_user_callback(req.ctx, req.on_body_drain, nil, 0, &exception) + if exception != nil { report_uncaught(req.ctx, exception) mark_async_failed(req.ctx) @@ -432,14 +495,21 @@ fetch_body_drain_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // interest at the new direction. Drives the frame-flush write arm, the post-terminator // read arm, and a TLS renegotiation read arm mid-write. fetch_body_arm :: proc(req: ^Fetch_Request, mode: eventloop.Poll_Mode) { - if req.settled || !req.has_fd do return + if req.settled || !req.has_fd { + return + } + req.watcher.callback = fetch_watcher_cb ok: bool + if req.watcher.watched { ok = fetch_set_watch_mode(req.loop, req, mode) } else { req.watcher.mode = mode ok = eventloop.watch_fd(req.loop, &req.watcher) } - if !ok do fetch_settle_error(req, "fetch: event loop watch failed") + + if !ok { + fetch_settle_error(req, "fetch: event loop watch failed") + } } diff --git a/pkg/runtime/fetch_windows.odin b/pkg/runtime/fetch_windows.odin index 81921ac1..08491b52 100644 --- a/pkg/runtime/fetch_windows.odin +++ b/pkg/runtime/fetch_windows.odin @@ -24,14 +24,20 @@ fetch_close_fd :: proc(fd: uintptr) { @(private = "file") fetch_new_socket :: proc(family: windows.c_int) -> windows.SOCKET { sock := windows.socket(family, windows.SOCK_STREAM, 0) - if sock == windows.INVALID_SOCKET do return windows.INVALID_SOCKET + + if sock == windows.INVALID_SOCKET { + return windows.INVALID_SOCKET + } + nonblock: windows.c_ulong = 1 + // FIONBIO has its high bit set, so a checked cast to signed c_long overflows; // reinterpret the bits instead (same as the event loop's wakeup socket). if windows.ioctlsocket(sock, transmute(windows.c_long)windows.FIONBIO, &nonblock) == windows.SOCKET_ERROR { windows.closesocket(sock) return windows.INVALID_SOCKET } + return sock } @@ -55,6 +61,7 @@ fetch_start_connect :: proc( windows.closesocket(sock) return false, "fetch: connect failed" } + return fetch_register_socket(req, uintptr(sock)) } @@ -62,7 +69,11 @@ fetch_start_connect :: proc( // connect. Both run on the loop thread. fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) -> (ok: bool, err: string) { sock := fetch_new_socket(windows.AF_INET) - if sock == windows.INVALID_SOCKET do return false, "fetch: could not create socket" + + if sock == windows.INVALID_SOCKET { + return false, "fetch: could not create socket" + } + addr := windows.sockaddr_in { sin_family = windows.ADDRESS_FAMILY(windows.AF_INET), sin_port = u16be(port), @@ -73,7 +84,11 @@ fetch_connect_ip4 :: proc(req: ^Fetch_Request, ip4: net.IP4_Address, port: int) fetch_connect_ip6 :: proc(req: ^Fetch_Request, ip6: net.IP6_Address, port: int) -> (ok: bool, err: string) { sock := fetch_new_socket(windows.AF_INET6) - if sock == windows.INVALID_SOCKET do return false, "fetch: could not create socket" + + if sock == windows.INVALID_SOCKET { + return false, "fetch: could not create socket" + } + // net.IP6_Address is [8]u16be, whose memory layout is already the 16 // network-order bytes sin6_addr expects. addr := windows.sockaddr_in6 { @@ -102,8 +117,15 @@ fetch_connect_succeeded :: proc(req: ^Fetch_Request) -> bool { // fetch_raw_send writes one chunk to the plaintext socket. fetch_raw_send :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetch_IO_Result) { sent := windows.send(windows.SOCKET(req.fd), raw_data(chunk), windows.c_int(len(chunk)), 0) - if sent != windows.SOCKET_ERROR do return int(sent), .Ok - if windows.WSAGetLastError() == windows.WSAEWOULDBLOCK do return 0, .Would_Block + + if sent != windows.SOCKET_ERROR { + return int(sent), .Ok + } + + if windows.WSAGetLastError() == windows.WSAEWOULDBLOCK { + return 0, .Would_Block + } + return 0, .Failed } @@ -111,9 +133,19 @@ fetch_raw_send :: proc(req: ^Fetch_Request, chunk: []byte) -> (n: int, res: Fetc // close (.Closed); WSAEWOULDBLOCK means wait for more data. fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_IO_Result) { got := windows.recv(windows.SOCKET(req.fd), raw_data(buf), windows.c_int(len(buf)), 0) - if got > 0 do return int(got), .Ok - if got == 0 do return 0, .Closed - if windows.WSAGetLastError() == windows.WSAEWOULDBLOCK do return 0, .Would_Block + + if got > 0 { + return int(got), .Ok + } + + if got == 0 { + return 0, .Closed + } + + if windows.WSAGetLastError() == windows.WSAEWOULDBLOCK { + return 0, .Would_Block + } + return 0, .Failed } @@ -123,7 +155,10 @@ fetch_raw_recv :: proc(req: ^Fetch_Request, buf: []byte) -> (n: int, res: Fetch_ // builds each fd_set, but re-registering explicitly (like epoll/kqueue) keeps this // correct regardless of how the backend tracks interest. A no-op when unchanged. fetch_set_watch_mode :: proc(loop: ^eventloop.Loop, req: ^Fetch_Request, mode: eventloop.Poll_Mode) -> bool { - if req.watcher.mode == mode do return true + if req.watcher.mode == mode { + return true + } + eventloop.unwatch_fd(loop, &req.watcher) req.watcher.mode = mode return eventloop.watch_fd(loop, &req.watcher) diff --git a/pkg/runtime/fs.odin b/pkg/runtime/fs.odin index 1ced3ee8..b570722a 100644 --- a/pkg/runtime/fs.odin +++ b/pkg/runtime/fs.odin @@ -21,18 +21,25 @@ fs_read_file_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } data, read_err := os.read_entire_file(path_str, context.allocator) + if read_err != os.ERROR_NONE { if exception != nil { code, errno_val := fs_os_error_to_code(read_err) exception^ = fs_make_error(ctx, code, "open", path_str, errno_val) } + return jsc.JSValueMakeUndefined(ctx) } @@ -82,24 +89,30 @@ fs_read_file_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { if exception != nil { exception^ = make_js_error(ctx, "fs.readFile requires a path and a callback") } + return jsc.JSValueMakeUndefined(ctx) } args := arguments[:int(argument_count)] callback := callback_arg(ctx, args[argument_count - 1]) + if callback == nil { if exception != nil { exception^ = make_js_error(ctx, "fs.readFile callback must be a function") } + return jsc.JSValueMakeUndefined(ctx) } path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } // context is runtime.default_context here (proc "c"), so context.allocator is the // heap allocator — capture it so the off-loop worker and the completion agree, and @@ -113,6 +126,7 @@ fs_read_file_cb :: proc "c" ( jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)callback) loop := get_loop_from_ctx(ctx) + // Happy path: read off-loop on the pool. pool_submit keeps the loop alive until the // completion posts; fs_read_pool_done then re-queues onto the poll phase. if loop != nil && @@ -123,11 +137,13 @@ fs_read_file_cb :: proc "c" ( // Fallback (no loop, or the pool could not start): read synchronously here, then // deliver on the poll phase if there is a loop, else inline. fs_read_work(req) + if loop != nil { eventloop.queue_io_callback(loop, fs_read_complete_cb, req, fs_read_dispose) } else { fs_read_complete_cb(nil, req) } + return jsc.JSValueMakeUndefined(ctx) } @@ -138,6 +154,7 @@ fs_read_file_cb :: proc "c" ( fs_read_work :: proc(user_data: rawptr) { req := cast(^FS_Read_Request)user_data data, read_err := os.read_entire_file(req.path, req.allocator) + if read_err != os.ERROR_NONE { req.ok = false req.err_code, req.err_errno = fs_os_error_to_code(read_err) @@ -171,8 +188,15 @@ fs_read_pool_done :: proc(loop: ^eventloop.Loop, user_data: rawptr) { fs_read_dispose :: proc(user_data: rawptr) { context = runtime.default_context() req := cast(^FS_Read_Request)user_data - if req == nil do return - if req.callback != nil do jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + + if req == nil { + return + } + + if req.callback != nil { + jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + } + fs_read_request_free(req) } @@ -183,7 +207,11 @@ fs_read_dispose :: proc(user_data: rawptr) { fs_read_cancel :: proc(user_data: rawptr) { context = runtime.default_context() req := cast(^FS_Read_Request)user_data - if req.callback != nil do jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + + if req.callback != nil { + jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + } + req.callback = nil } @@ -191,9 +219,19 @@ fs_read_cancel :: proc(user_data: rawptr) { // it is still owned here (the Buffer success path hands it to JSC and nils it first). fs_read_request_free :: proc(req: ^FS_Read_Request) { a := req.allocator - if req.data != nil do delete(req.data, a) - if len(req.path) > 0 do delete(req.path, a) - if len(req.err_msg) > 0 do delete(req.err_msg, a) + + if req.data != nil { + delete(req.data, a) + } + + if len(req.path) > 0 { + delete(req.path, a) + } + + if len(req.err_msg) > 0 { + delete(req.err_msg, a) + } + free(req, a) } @@ -202,10 +240,15 @@ fs_read_request_free :: proc(req: ^FS_Read_Request) { fs_read_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { context = runtime.default_context() req := cast(^FS_Read_Request)user_data - if req == nil do return + + if req == nil { + return + } + ctx := req.ctx call_args: [2]jsc.JSValueRef + if req.ok { call_args[0] = jsc.JSValueMakeNull(ctx) // Async completion runs from the event loop (not a JSC callback), so this must go @@ -220,21 +263,25 @@ fs_read_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { req.data = nil } else { err := make_js_error(ctx, req.err_msg) + if jsc.JSValueIsObject(ctx, err) { err_obj := cast(jsc.JSObjectRef)err set_named(ctx, err_obj, "code", js_string_value(ctx, req.err_code)) set_named(ctx, err_obj, "path", js_string_value(ctx, req.path)) set_named(ctx, err_obj, "syscall", js_string_value(ctx, "open")) + if req.err_errno != 0 { set_named(ctx, err_obj, "errno", jsc.JSValueMakeNumber(ctx, f64(-req.err_errno))) } } + call_args[0] = err call_args[1] = jsc.JSValueMakeUndefined(ctx) } exception: jsc.JSValueRef invoke_user_callback(ctx, req.callback, raw_data(call_args[:]), 2, &exception) + if exception != nil { report_uncaught(ctx, exception) mark_async_failed(ctx) @@ -251,21 +298,29 @@ fs_make_error :: proc(ctx: jsc.JSContextRef, code, syscall, path: string, errno_ // A path-less syscall (e.g. close, which operates on an fd) gets no "'path'" clause // and no `path` property — matching Node, whose close error reads "EBADF: ..., close". msg: string + if len(path) > 0 { msg = fmt.tprintf("%s: %s, %s '%s'", code, fs_errno_text(code), syscall, path) } else { msg = fmt.tprintf("%s: %s, %s", code, fs_errno_text(code), syscall) } + err := make_js_error(ctx, msg) + if jsc.JSValueIsObject(ctx, err) { obj := cast(jsc.JSObjectRef)err set_named(ctx, obj, "code", js_string_value(ctx, code)) set_named(ctx, obj, "syscall", js_string_value(ctx, syscall)) - if len(path) > 0 do set_named(ctx, obj, "path", js_string_value(ctx, path)) + + if len(path) > 0 { + set_named(ctx, obj, "path", js_string_value(ctx, path)) + } + if errno_val != 0 { set_named(ctx, obj, "errno", jsc.JSValueMakeNumber(ctx, f64(-errno_val))) } } + return err } @@ -279,16 +334,19 @@ fs_make_rename_error :: proc( ) -> jsc.JSValueRef { msg := fmt.tprintf("%s: %s, rename '%s' -> '%s'", code, fs_errno_text(code), old_path, new_path) err := make_js_error(ctx, msg) + if jsc.JSValueIsObject(ctx, err) { obj := cast(jsc.JSObjectRef)err set_named(ctx, obj, "code", js_string_value(ctx, code)) set_named(ctx, obj, "syscall", js_string_value(ctx, "rename")) set_named(ctx, obj, "path", js_string_value(ctx, old_path)) set_named(ctx, obj, "dest", js_string_value(ctx, new_path)) + if errno_val != 0 { set_named(ctx, obj, "errno", jsc.JSValueMakeNumber(ctx, f64(-errno_val))) } } + return err } @@ -350,25 +408,36 @@ fs_validate_int_arg :: proc( if !jsc.JSValueIsNumber(ctx, value) { return 0, err_invalid_arg_type(ctx, name, "number", value), false } + f := jsc.JSValueToNumber(ctx, value, nil) + // The (f >= 0 && f <= max) form rejects NaN (NaN compares false), -inf, and overflow // before the int() cast, so the cast below is always well-defined. if !(f >= 0 && f <= max) { rng := fmt.tprintf(">= 0 && <= %d", int(max)) return 0, err_out_of_range(ctx, name, rng, fs_render_number(f)), false } + out = int(f) + if f != f64(out) { return 0, err_out_of_range(ctx, name, "an integer", fs_render_number(f)), false } + return out, nil, true } // fs_render_number renders an offending numeric value for an ERR_OUT_OF_RANGE "Received …" // clause: an integer-valued f64 prints without a decimal, NaN as "NaN". fs_render_number :: proc(f: f64) -> string { - if f != f do return "NaN" - if f >= -9.2e18 && f <= 9.2e18 && f == f64(i64(f)) do return fmt.tprintf("%d", i64(f)) + if f != f { + return "NaN" + } + + if f >= -9.2e18 && f <= 9.2e18 && f == f64(i64(f)) { + return fmt.tprintf("%d", i64(f)) + } + return fmt.tprintf("%v", f) } @@ -450,9 +519,15 @@ fs_os_error_to_code :: proc(err: os.Error) -> (code: string, errno_val: int) { // which Node rejects and whose unchecked fields must not be fed to the slice below. is_data_view :: proc(ctx: jsc.JSContextRef, obj: jsc.JSObjectRef) -> bool { ctor := get_named(ctx, obj, "constructor") - if ctor == nil || !jsc.JSValueIsObject(ctx, ctor) do return false + + if ctor == nil || !jsc.JSValueIsObject(ctx, ctor) { + return false + } + name, allocated := value_to_string(ctx, get_named(ctx, cast(jsc.JSObjectRef)ctor, "name")) - defer if allocated do delete(name) + defer if allocated { + delete(name) + } return name == "DataView" } @@ -483,21 +558,32 @@ fs_resolve_write_payload :: proc( ok: bool, ) { t := jsc.JSValueGetTypedArrayType(ctx, value, nil) + // A bare ArrayBuffer is not a valid fs write payload (Node: ERR_INVALID_ARG_TYPE). - if t == .ArrayBuffer do return nil, false, false + if t == .ArrayBuffer { + return nil, false, false + } + if t != .None { // A real typed array (Buffer included); typed_array_view is byteOffset-aware, so // a Buffer.subarray(...) writes its window, not the whole backing. Borrowed. view, view_ok := typed_array_view(ctx, value) - if !view_ok do return nil, false, true + + if !view_ok { + return nil, false, true + } + return view, false, true } + // A DataView is an object whose `.buffer` is an ArrayBuffer; read its window directly // from the backing buffer (no C-API DataView accessor exists). if jsc.JSValueIsObject(ctx, value) { obj := cast(jsc.JSObjectRef)value + if is_data_view(ctx, obj) { buffer_val := get_named(ctx, obj, "buffer") + if buffer_val != nil && jsc.JSValueGetTypedArrayType(ctx, buffer_val, nil) == .ArrayBuffer { ab := cast(jsc.JSObjectRef)buffer_val // Read the claimed window FIRST, because these two reads are the only step @@ -516,21 +602,31 @@ fs_resolve_write_payload :: proc( // JSC API call (a GC/realloc can move it), so nothing may come between them // but the pure-Odin validation below. ab_len := f64(jsc.JSObjectGetArrayBufferByteLength(ctx, ab, nil)) + // NaN/Infinity fail every comparison, so an invalid window rejects to an empty // payload here rather than truncating to an undefined int. len_f > 0 also folds // the zero-length DataView into the empty-file path. - if !(off_f >= 0 && len_f > 0 && off_f + len_f <= ab_len) do return nil, false, true + if !(off_f >= 0 && len_f > 0 && off_f + len_f <= ab_len) { + return nil, false, true + } + base := jsc.JSObjectGetArrayBufferBytesPtr(ctx, ab, nil) - if base == nil do return nil, false, true + + if base == nil { + return nil, false, true + } + off, length := int(off_f), int(len_f) return (cast([^]byte)base)[off:off + length], false, true } } } + // String, or any other value coerced to its string form. The string buffer is already // owned on context.allocator, so hand it back as-is (owned=true) — no extra copy. str, salloc := jsc_value_to_string_or_default(ctx, value) - if !salloc do return nil, false, true // empty/unconvertible -> zero-length file + + if !salloc {return nil, false, true} // empty/unconvertible -> zero-length file return transmute([]byte)str, true, true } @@ -543,23 +639,36 @@ fs_write_file_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { - if exception != nil do exception^ = make_js_error(ctx, "fs.writeFileSync requires a path and data") + if exception != nil { + exception^ = make_js_error(ctx, "fs.writeFileSync requires a path and data") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } // The sync write completes within this native call while a borrowed TypedArray/DataView // window is still valid, so write straight from it — no marshalling copy (only a coerced // string is an owned buffer, freed below). write_bytes, owned, data_ok := fs_resolve_write_payload(ctx, args[1]) + if !data_ok { - if exception != nil do exception^ = err_invalid_arg_type(ctx, "data", "string or an instance of Buffer, TypedArray, or DataView", args[1]) + if exception != + nil {exception^ = err_invalid_arg_type(ctx, "data", "string or an instance of Buffer, TypedArray, or DataView", args[1])} + return jsc.JSValueMakeUndefined(ctx) } - defer if owned do delete(write_bytes, context.allocator) + + defer if owned { + delete(write_bytes, context.allocator) + } if write_err := os.write_entire_file_from_bytes(path_str, write_bytes); write_err != nil { if exception != nil { @@ -567,6 +676,7 @@ fs_write_file_sync_cb :: proc "c" ( exception^ = fs_make_error(ctx, code, "open", path_str, errno_val) } } + return jsc.JSValueMakeUndefined(ctx) } @@ -584,18 +694,30 @@ fs_write_file_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 3 { - if exception != nil do exception^ = make_js_error(ctx, "fs.writeFile requires a path, data and a callback") + if exception != nil { + exception^ = make_js_error(ctx, "fs.writeFile requires a path, data and a callback") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] callback := callback_arg(ctx, args[argument_count - 1]) + if callback == nil { - if exception != nil do exception^ = make_js_error(ctx, "fs.writeFile callback must be a function") + if exception != nil { + exception^ = make_js_error(ctx, "fs.writeFile callback must be a function") + } + return jsc.JSValueMakeUndefined(ctx) } + path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } // context.allocator is the heap allocator here (proc "c"); capture it so the owned // path/data outlive this call and the worker frees through the same allocator. @@ -603,15 +725,20 @@ fs_write_file_cb :: proc "c" ( // Resolve the payload NOW (JSC access is loop-thread only). An invalid payload (a bare // ArrayBuffer) is a synchronous throw, like Node — before anything is allocated. payload, owned, data_ok := fs_resolve_write_payload(ctx, args[1]) + if !data_ok { - if exception != nil do exception^ = err_invalid_arg_type(ctx, "data", "string or an instance of Buffer, TypedArray, or DataView", args[1]) + if exception != + nil {exception^ = err_invalid_arg_type(ctx, "data", "string or an instance of Buffer, TypedArray, or DataView", args[1])} + return jsc.JSValueMakeUndefined(ctx) } + // The worker writes off-loop, so it must own its bytes. A coerced string is already an // owned heap buffer on `alloc` — take it as-is; a borrowed TypedArray/DataView window // must be copied here (it aliases JSC memory). No JSC call between the resolve and this // copy, per fs_resolve_write_payload's borrowing contract. write_data: []byte + if owned { write_data = payload } else if len(payload) > 0 { @@ -629,17 +756,20 @@ fs_write_file_cb :: proc "c" ( jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)callback) loop := get_loop_from_ctx(ctx) + if loop != nil && eventloop.pool_submit(loop, fs_write_work, fs_write_pool_done, req, fs_write_dispose, fs_write_cancel) { return jsc.JSValueMakeUndefined(ctx) } fs_write_work(req) + if loop != nil { eventloop.queue_io_callback(loop, fs_op_complete_cb, req, fs_write_dispose) } else { fs_op_complete_cb(nil, req) } + return jsc.JSValueMakeUndefined(ctx) } @@ -648,6 +778,7 @@ fs_write_file_cb :: proc "c" ( fs_write_work :: proc(user_data: rawptr) { req := cast(^FS_Op_Request)user_data write_err := os.write_entire_file_from_bytes(req.path, req.write_data) + if write_err == nil { req.ok = true } else { @@ -666,8 +797,15 @@ fs_write_pool_done :: proc(loop: ^eventloop.Loop, user_data: rawptr) { fs_write_dispose :: proc(user_data: rawptr) { context = runtime.default_context() req := cast(^FS_Op_Request)user_data - if req == nil do return - if req.callback != nil do jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + + if req == nil { + return + } + + if req.callback != nil { + jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + } + fs_op_request_free(req) } @@ -676,15 +814,26 @@ fs_write_dispose :: proc(user_data: rawptr) { fs_write_cancel :: proc(user_data: rawptr) { context = runtime.default_context() req := cast(^FS_Op_Request)user_data - if req.callback != nil do jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + + if req.callback != nil { + jsc.JSValueUnprotect(req.ctx, cast(jsc.JSValueRef)req.callback) + } + req.callback = nil } // fs_op_request_free releases everything an FS_Op_Request owns. fs_op_request_free :: proc(req: ^FS_Op_Request) { a := req.allocator - if req.write_data != nil do delete(req.write_data, a) - if len(req.path) > 0 do delete(req.path, a) + + if req.write_data != nil { + delete(req.write_data, a) + } + + if len(req.path) > 0 { + delete(req.path, a) + } + free(req, a) } @@ -707,10 +856,15 @@ FS_Op_Request :: struct { fs_op_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { context = runtime.default_context() req := cast(^FS_Op_Request)user_data - if req == nil do return + + if req == nil { + return + } + ctx := req.ctx call_args: [1]jsc.JSValueRef + if req.ok { call_args[0] = jsc.JSValueMakeNull(ctx) } else { @@ -719,6 +873,7 @@ fs_op_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { exception: jsc.JSValueRef invoke_user_callback(ctx, req.callback, raw_data(call_args[:]), 1, &exception) + if exception != nil { report_uncaught(ctx, exception) mark_async_failed(ctx) @@ -730,20 +885,40 @@ fs_op_complete_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // fs_options_recursive reads `options.recursive === true` from an options arg. fs_options_recursive :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> bool { - if value == nil || !jsc.JSValueIsObject(ctx, value) do return false + if value == nil || !jsc.JSValueIsObject(ctx, value) { + return false + } + r := get_named(ctx, cast(jsc.JSObjectRef)value, "recursive") - if r == nil do return false + + if r == nil { + return false + } + return bool(jsc.JSValueToBoolean(ctx, r)) } fs_mkdir_recursive :: proc(path: string) -> bool { - if len(path) == 0 do return false - if os.exists(path) do return os.is_dir(path) + if len(path) == 0 { + return false + } + + if os.exists(path) { + return os.is_dir(path) + } + parent := filepath.dir(path) + if parent != path && len(parent) > 0 && !os.exists(parent) { - if !fs_mkdir_recursive(parent) do return false + if !fs_mkdir_recursive(parent) { + return false + } + } + + if os.make_directory(path) == nil { + return true } - if os.make_directory(path) == nil do return true + return os.is_dir(path) } @@ -756,13 +931,20 @@ fs_mkdir_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.mkdirSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.mkdirSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } recursive := argument_count >= 2 && fs_options_recursive(ctx, args[1]) @@ -770,15 +952,20 @@ fs_mkdir_sync_cb :: proc "c" ( // Node: recursive mkdir on an existing dir is a no-op; non-recursive or // recursive on an existing *file* throws EEXIST. if !recursive || !os.is_dir(path_str) { - if exception != nil do exception^ = fs_make_error(ctx, "EEXIST", "mkdir", path_str, 17) + if exception != nil { + exception^ = fs_make_error(ctx, "EEXIST", "mkdir", path_str, 17) + } } + return jsc.JSValueMakeUndefined(ctx) } ok := recursive ? fs_mkdir_recursive(path_str) : (os.make_directory(path_str) == nil) + if !ok && exception != nil { exception^ = fs_make_error(ctx, "ENOENT", "mkdir", path_str) } + return jsc.JSValueMakeUndefined(ctx) } @@ -788,18 +975,23 @@ fs_remove_recursive :: proc(path: string) -> bool { // links, so the recursion used to walk INTO the link target and delete its // contents outside the removed tree (issue #88). Node removes only the link. is_real_dir := false + if info, stat_err := os.lstat(path, context.allocator); stat_err == nil { is_real_dir = info.type == .Directory os.file_info_delete(info, context.allocator) } + if is_real_dir { handle, open_err := os.open(path) + if open_err == nil { infos, read_err := os.read_directory(handle, -1, context.allocator) os.close(handle) + if read_err == nil { for info in infos { child, join_err := filepath.join({path, info.name}, context.allocator) + if join_err == nil { fs_remove_recursive(child) delete(child, context.allocator) @@ -809,6 +1001,7 @@ fs_remove_recursive :: proc(path: string) -> bool { } } } + return os.remove(path) == nil } @@ -821,21 +1014,32 @@ fs_rm_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.rmSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.rmSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } force := false recursive := false + if argument_count >= 2 && jsc.JSValueIsObject(ctx, args[1]) { opts := cast(jsc.JSObjectRef)args[1] recursive = fs_options_recursive(ctx, args[1]) f := get_named(ctx, opts, "force") - if f != nil do force = bool(jsc.JSValueToBoolean(ctx, f)) + + if f != nil { + force = bool(jsc.JSValueToBoolean(ctx, f)) + } } // Use lstat so a dangling symlink is visible (os.exists follows links and @@ -843,17 +1047,22 @@ fs_rm_sync_cb :: proc "c" ( lstat_info, lstat_err := os.lstat(path_str, context.allocator) path_missing := lstat_err != nil is_dir := !path_missing && lstat_info.type == .Directory - if lstat_err == nil do os.file_info_delete(lstat_info, context.allocator) + + if lstat_err == nil { + os.file_info_delete(lstat_info, context.allocator) + } if path_missing { if !force && exception != nil { exception^ = fs_make_error(ctx, "ENOENT", "stat", path_str, 2) } + return jsc.JSValueMakeUndefined(ctx) } if recursive { ok := fs_remove_recursive(path_str) + if !ok && !force && exception != nil { exception^ = fs_make_error(ctx, "ENOTEMPTY", "rmdir", path_str, 39) } @@ -861,15 +1070,21 @@ fs_rm_sync_cb :: proc "c" ( // Non-recursive on a directory: Node 22 throws ERR_FS_EISDIR regardless of // whether the dir is empty, because rm(1) requires --recursive/-r for dirs. if is_dir && !force { - if exception != nil do exception^ = fs_make_error(ctx, "ERR_FS_EISDIR", "rm", path_str, 21) + if exception != nil { + exception^ = fs_make_error(ctx, "ERR_FS_EISDIR", "rm", path_str, 21) + } + return jsc.JSValueMakeUndefined(ctx) } + remove_err := os.remove(path_str) + if remove_err != nil && !force && exception != nil { code, errno_val := fs_os_error_to_code(remove_err) exception^ = fs_make_error(ctx, code, "rm", path_str, errno_val) } } + return jsc.JSValueMakeUndefined(ctx) } @@ -886,38 +1101,60 @@ fs_open_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.openSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.openSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } flags := "r" flags_alloc := false + if argument_count >= 2 && jsc.JSValueIsString(ctx, args[1]) { flags, flags_alloc = jsc_value_to_string_or_default(ctx, args[1]) } - defer if flags_alloc do delete(flags, context.allocator) + + defer if flags_alloc { + delete(flags, context.allocator) + } mode := 0o666 + if argument_count >= 3 && jsc.JSValueIsNumber(ctx, args[2]) { // A provided numeric mode must be a non-negative 32-bit integer (Node's // validateUint32 via parseFileMode); a fractional/NaN/negative value throws. m, mode_err, mode_ok := fs_validate_int_arg(ctx, args[2], "mode", 0xffffffff) + if !mode_ok { - if exception != nil do exception^ = mode_err + if exception != nil { + exception^ = mode_err + } + return jsc.JSValueMakeUndefined(ctx) } + mode = m } fd, code, errno_val := fs_platform_open(path_str, flags, mode) + if code != "" { - if exception != nil do exception^ = fs_make_error(ctx, code, "open", path_str, errno_val) + if exception != nil { + exception^ = fs_make_error(ctx, code, "open", path_str, errno_val) + } + return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeNumber(ctx, f64(fd)) } @@ -931,21 +1168,35 @@ fs_close_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.closeSync requires a fd") + if exception != nil { + exception^ = make_js_error(ctx, "fs.closeSync requires a fd") + } + return jsc.JSValueMakeUndefined(ctx) } + // Validate the fd BEFORE the syscall: an unvalidated coercion (3.5 -> 3, NaN/object -> // garbage) would otherwise close an unrelated descriptor (stdin, the loop's epoll fd). fd, fd_err, fd_ok := fs_validate_int_arg(ctx, arguments[0], "fd", 0x7fffffff) + if !fd_ok { - if exception != nil do exception^ = fd_err + if exception != nil { + exception^ = fd_err + } + return jsc.JSValueMakeUndefined(ctx) } + code, errno_val := fs_platform_close(fd) + if code != "" { - if exception != nil do exception^ = fs_make_error(ctx, code, "close", "", errno_val) + if exception != nil { + exception^ = fs_make_error(ctx, code, "close", "", errno_val) + } } + return jsc.JSValueMakeUndefined(ctx) } @@ -966,24 +1217,35 @@ fs_unlink_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.unlinkSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.unlinkSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } info, lstat_err := os.lstat(path_str, context.allocator) + if lstat_err != nil { if exception != nil { code, errno_val := fs_os_error_to_code(lstat_err) exception^ = fs_make_error(ctx, code, "unlink", path_str, errno_val) } + return jsc.JSValueMakeUndefined(ctx) } + is_dir := info.type == .Directory os.file_info_delete(info, context.allocator) + if is_dir { if exception != nil { when ODIN_OS == .Linux { @@ -992,6 +1254,7 @@ fs_unlink_sync_cb :: proc "c" ( exception^ = fs_make_error(ctx, "EPERM", "unlink", path_str, 1) } } + return jsc.JSValueMakeUndefined(ctx) } @@ -999,6 +1262,7 @@ fs_unlink_sync_cb :: proc "c" ( code, errno_val := fs_os_error_to_code(remove_err) exception^ = fs_make_error(ctx, code, "unlink", path_str, errno_val) } + return jsc.JSValueMakeUndefined(ctx) } @@ -1018,24 +1282,35 @@ fs_rmdir_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.rmdirSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.rmdirSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } info, lstat_err := os.lstat(path_str, context.allocator) + if lstat_err != nil { if exception != nil { code, errno_val := fs_os_error_to_code(lstat_err) exception^ = fs_make_error(ctx, code, "rmdir", path_str, errno_val) } + return jsc.JSValueMakeUndefined(ctx) } + is_dir := info.type == .Directory os.file_info_delete(info, context.allocator) + if !is_dir { // rmdir of a non-directory: POSIX reports ENOTDIR, but on Windows // RemoveDirectoryW fails with ERROR_DIRECTORY, which libuv/Node surface as @@ -1047,6 +1322,7 @@ fs_rmdir_sync_cb :: proc "c" ( exception^ = fs_make_error(ctx, "ENOTDIR", "rmdir", path_str, 20) } } + return jsc.JSValueMakeUndefined(ctx) } @@ -1054,6 +1330,7 @@ fs_rmdir_sync_cb :: proc "c" ( code, errno_val := fs_os_error_to_code(remove_err) exception^ = fs_make_error(ctx, code, "rmdir", path_str, errno_val) } + return jsc.JSValueMakeUndefined(ctx) } @@ -1069,20 +1346,30 @@ fs_rename_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { - if exception != nil do exception^ = make_js_error(ctx, "fs.renameSync requires oldPath and newPath") + if exception != nil { + exception^ = make_js_error(ctx, "fs.renameSync requires oldPath and newPath") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] old_str, old_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if old_alloc do delete(old_str, context.allocator) + defer if old_alloc { + delete(old_str, context.allocator) + } new_str, new_alloc := jsc_value_to_string_or_default(ctx, args[1]) - defer if new_alloc do delete(new_str, context.allocator) + defer if new_alloc { + delete(new_str, context.allocator) + } if rename_err := os.rename(old_str, new_str); rename_err != nil && exception != nil { code, errno_val := fs_os_error_to_code(rename_err) exception^ = fs_make_rename_error(ctx, code, old_str, new_str, errno_val) } + return jsc.JSValueMakeUndefined(ctx) } @@ -1096,12 +1383,19 @@ fs_mkdtemp_alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123 // ('buffer' or { encoding: 'buffer' }); otherwise mkdtempSync returns a string. fs_mkdtemp_wants_buffer :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> bool { enc := value + if jsc.JSValueIsObject(ctx, value) { enc = get_named(ctx, cast(jsc.JSObjectRef)value, "encoding") } - if enc == nil || !jsc.JSValueIsString(ctx, enc) do return false + + if enc == nil || !jsc.JSValueIsString(ctx, enc) { + return false + } + s, alloc := jsc_value_to_string_or_default(ctx, enc) - defer if alloc do delete(s, context.allocator) + defer if alloc { + delete(s, context.allocator) + } return s == "buffer" } @@ -1122,13 +1416,20 @@ fs_mkdtemp_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.mkdtempSync requires a prefix") + if exception != nil { + exception^ = make_js_error(ctx, "fs.mkdtempSync requires a prefix") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] prefix_str, prefix_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if prefix_alloc do delete(prefix_str, context.allocator) + defer if prefix_alloc { + delete(prefix_str, context.allocator) + } as_buffer := argument_count >= 2 && fs_mkdtemp_wants_buffer(ctx, args[1]) @@ -1143,24 +1444,35 @@ fs_mkdtemp_sync_cb :: proc "c" ( } candidate := strings.concatenate({prefix_str, string(suffix[:])}, context.allocator) mk_err := os.make_directory(candidate) + if mk_err == nil { created = candidate created_ok = true break } + delete(candidate, context.allocator) // EEXIST → collision, try another suffix; anything else (e.g. ENOENT for a // missing parent) is terminal and reported with Node's mkdtemp semantics. code, errno_val := fs_os_error_to_code(mk_err) + if code != "EEXIST" { - if exception != nil do exception^ = fs_make_error(ctx, code, "mkdtemp", prefix_str, errno_val) + if exception != nil { + exception^ = fs_make_error(ctx, code, "mkdtemp", prefix_str, errno_val) + } + return jsc.JSValueMakeUndefined(ctx) } } + if !created_ok { - if exception != nil do exception^ = fs_make_error(ctx, "EEXIST", "mkdtemp", prefix_str, 17) + if exception != nil { + exception^ = fs_make_error(ctx, "EEXIST", "mkdtemp", prefix_str, 17) + } + return jsc.JSValueMakeUndefined(ctx) } + defer delete(created, context.allocator) if as_buffer { @@ -1170,6 +1482,7 @@ fs_mkdtemp_sync_cb :: proc "c" ( copy(bytes, created) return make_uint8_array(ctx, bytes) } + return js_string_value(ctx, created) } @@ -1179,7 +1492,11 @@ fs_time_ms :: proc(t: time.Time) -> f64 { stats_ftype :: proc(ctx: jsc.JSContextRef, obj: jsc.JSObjectRef) -> int { v := get_named(ctx, obj, "__lava_ftype") - if v == nil do return 0 + + if v == nil { + return 0 + } + return int(jsc.JSValueToNumber(ctx, v, nil)) } @@ -1258,19 +1575,31 @@ fs_stat_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.statSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.statSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } info, stat_err := os.stat(path_str, context.allocator) + if stat_err != nil { - if exception != nil do exception^ = fs_make_error(ctx, "ENOENT", "stat", path_str) + if exception != nil { + exception^ = fs_make_error(ctx, "ENOENT", "stat", path_str) + } + return jsc.JSValueMakeUndefined(ctx) } + defer os.file_info_delete(info, context.allocator) return fs_build_stats(ctx, info) @@ -1285,25 +1614,42 @@ fs_readdir_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "fs.readdirSync requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "fs.readdirSync requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] path_str, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path_str, context.allocator) + defer if path_alloc { + delete(path_str, context.allocator) + } handle, open_err := os.open(path_str) + if open_err != nil { - if exception != nil do exception^ = fs_make_error(ctx, "ENOENT", "scandir", path_str) + if exception != nil { + exception^ = fs_make_error(ctx, "ENOENT", "scandir", path_str) + } + return jsc.JSValueMakeUndefined(ctx) } + infos, read_err := os.read_directory(handle, -1, context.allocator) os.close(handle) + if read_err != nil { - if exception != nil do exception^ = fs_make_error(ctx, "ENOTDIR", "scandir", path_str) + if exception != nil { + exception^ = fs_make_error(ctx, "ENOTDIR", "scandir", path_str) + } + return jsc.JSValueMakeUndefined(ctx) } + defer os.file_info_slice_delete(infos, context.allocator) // Set each name as it is created — never park unrooted JSValueRefs in a temp_allocator @@ -1324,11 +1670,16 @@ fs_exists_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeBoolean(ctx, false) + + if argument_count < 1 { + return jsc.JSValueMakeBoolean(ctx, false) + } args := arguments[:int(argument_count)] path_str, alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if alloc do delete(path_str, context.allocator) + defer if alloc { + delete(path_str, context.allocator) + } return jsc.JSValueMakeBoolean(ctx, b32(module_file_exists(path_str))) } diff --git a/pkg/runtime/fs_fd_posix.odin b/pkg/runtime/fs_fd_posix.odin index 60a48f31..224f4e60 100644 --- a/pkg/runtime/fs_fd_posix.odin +++ b/pkg/runtime/fs_fd_posix.odin @@ -12,14 +12,19 @@ import "core:sys/posix" // fd on success or a Node error code (+ errno) on failure. fs_platform_open :: proc(path: string, flags_str: string, mode: int) -> (fd: int, err_code: string, errno_val: int) { flags, ok := fs_open_flags(flags_str) - if !ok do return -1, "EINVAL", 22 + + if !ok { + return -1, "EINVAL", 22 + } cpath := strings.clone_to_cstring(path, context.temp_allocator) res := posix.open(cpath, flags, fs_mode_t(mode)) + if i32(res) < 0 { e := posix.errno() return -1, fs_posix_errno_code(e), int(i32(e)) } + return int(res), "", 0 } @@ -27,18 +32,55 @@ fs_platform_open :: proc(path: string, flags_str: string, mode: int) -> (fd: int // (not a transmute) because _mode_t differs by platform (u32 on Linux, u16 on Darwin). fs_mode_t :: proc(mode: int) -> posix.mode_t { m: posix.mode_t - if mode & 0o400 != 0 do m += {.IRUSR} - if mode & 0o200 != 0 do m += {.IWUSR} - if mode & 0o100 != 0 do m += {.IXUSR} - if mode & 0o040 != 0 do m += {.IRGRP} - if mode & 0o020 != 0 do m += {.IWGRP} - if mode & 0o010 != 0 do m += {.IXGRP} - if mode & 0o004 != 0 do m += {.IROTH} - if mode & 0o002 != 0 do m += {.IWOTH} - if mode & 0o001 != 0 do m += {.IXOTH} - if mode & 0o4000 != 0 do m += {.ISUID} - if mode & 0o2000 != 0 do m += {.ISGID} - if mode & 0o1000 != 0 do m += {.ISVXT} + + if mode & 0o400 != 0 { + m += {.IRUSR} + } + + if mode & 0o200 != 0 { + m += {.IWUSR} + } + + if mode & 0o100 != 0 { + m += {.IXUSR} + } + + if mode & 0o040 != 0 { + m += {.IRGRP} + } + + if mode & 0o020 != 0 { + m += {.IWGRP} + } + + if mode & 0o010 != 0 { + m += {.IXGRP} + } + + if mode & 0o004 != 0 { + m += {.IROTH} + } + + if mode & 0o002 != 0 { + m += {.IWOTH} + } + + if mode & 0o001 != 0 { + m += {.IXOTH} + } + + if mode & 0o4000 != 0 { + m += {.ISUID} + } + + if mode & 0o2000 != 0 { + m += {.ISGID} + } + + if mode & 0o1000 != 0 { + m += {.ISVXT} + } + return m } @@ -47,6 +89,7 @@ fs_platform_close :: proc(fd: int) -> (err_code: string, errno_val: int) { e := posix.errno() return fs_posix_errno_code(e), int(i32(e)) } + return "", 0 } diff --git a/pkg/runtime/globals.odin b/pkg/runtime/globals.odin index 1edb786b..c50978d0 100644 --- a/pkg/runtime/globals.odin +++ b/pkg/runtime/globals.odin @@ -165,7 +165,10 @@ new_runtime_state :: proc(loop: ^eventloop.Loop) -> ^Runtime_State { } destroy_runtime_state :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + fetch_shutdown_active(state) fetch_destroy_pending(state) net_destroy_state(state) @@ -217,7 +220,10 @@ destroy_runtime_state :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { // exactly as the process.exit() fast path already does. Other platforms tear // down cleanly and keep unprotecting. unprotect_before_eval_exit :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) { - if value == nil do return + if value == nil { + return + } + when ODIN_OS != .Windows { jsc.JSValueUnprotect(ctx, value) } @@ -232,7 +238,11 @@ get_state_from_ctx :: proc(ctx: jsc.JSContextRef) -> ^Runtime_State { // Replaces the previous string-based __loop_ptr__ global. get_loop_from_ctx :: proc(ctx: jsc.JSContextRef) -> ^eventloop.Loop { state := get_state_from_ctx(ctx) - if state == nil do return nil + + if state == nil { + return nil + } + return state.loop } @@ -256,7 +266,10 @@ Cached_Module :: struct { } module_cache_get :: proc(state: ^Runtime_State, key: string) -> (jsc.JSValueRef, bool) { - if state == nil do return nil, false + if state == nil { + return nil, false + } + entry, ok := state.module_cache[key] return entry.value, ok } @@ -278,8 +291,13 @@ module_cache_get :: proc(state: ^Runtime_State, key: string) -> (jsc.JSValueRef, @(private = "file") module_cache_insert_new :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string, value: jsc.JSValueRef) { cloned, err := strings.clone(key, state.allocator) - if err != nil do return + + if err != nil { + return + } + jsc.JSValueProtect(ctx, value) + if map_insert(&state.module_cache, cloned, Cached_Module{value = value, key = cloned}) == nil { jsc.JSValueUnprotect(ctx, value) delete(cloned, state.allocator) @@ -287,8 +305,14 @@ module_cache_insert_new :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, ke } module_cache_put :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string, value: jsc.JSValueRef) { - if state == nil do return - if _, ok := state.module_cache[key]; ok do return + if state == nil { + return + } + + if _, ok := state.module_cache[key]; ok { + return + } + module_cache_insert_new(ctx, state, key, value) } @@ -298,9 +322,15 @@ module_cache_put :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: stri // exports) and again afterwards to store the final exports (the body may have // reassigned module.exports). Replacing re-points GC protection to the new value. module_cache_set :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string, value: jsc.JSValueRef) { - if state == nil do return + if state == nil { + return + } + if entry, ok := state.module_cache[key]; ok { - if entry.value == value do return + if entry.value == value { + return + } + jsc.JSValueProtect(ctx, value) // protect new before unprotecting old jsc.JSValueUnprotect(ctx, entry.value) entry.value = value // keep entry.key (the existing owned key string) @@ -310,6 +340,7 @@ module_cache_set :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: stri state.module_cache[key] = entry return } + module_cache_insert_new(ctx, state, key, value) } @@ -317,9 +348,16 @@ module_cache_set :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: stri // the owned key string. Used when a module throws while loading so a failed // module is not left cached as partial exports (matching Node, which re-loads). module_cache_remove :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State, key: string) { - if state == nil do return + if state == nil { + return + } + entry, ok := state.module_cache[key] - if !ok do return + + if !ok { + return + } + jsc.JSValueUnprotect(ctx, entry.value) // entry.key is the clone we own and used as the map key (Odin maps do not free // string-key backing memory). Free it after dropping the entry — O(1), no scan. @@ -359,9 +397,17 @@ capture_timer_args :: proc( allocator: runtime.Allocator, ) -> []jsc.JSValueRef { n := int(argument_count) - start - if n <= 0 do return nil + + if n <= 0 { + return nil + } + args, err := make([]jsc.JSValueRef, n, allocator) - if err != nil do return nil + + if err != nil { + return nil + } + for i in 0 ..< n { v := arguments[start + i] jsc.JSValueProtect(ctx, v) @@ -383,6 +429,7 @@ free_js_callback :: proc(cb: ^JS_Callback, release_roots := true) { jsc.JSValueUnprotect(cb.ctx, arg) } } + allocator := cb.allocator delete(cb.args, allocator) free(cb, allocator) @@ -412,10 +459,14 @@ should_release_fired_callback_roots :: proc(loop: ^eventloop.Loop) -> bool { js_callback_trampoline :: proc(loop: ^eventloop.Loop, user_data: rawptr) { cb := cast(^JS_Callback)user_data - if cb == nil do return + + if cb == nil { + return + } exception: jsc.JSValueRef invoke_user_callback(cb.ctx, cb.func, raw_data(cb.args), c.size_t(len(cb.args)), &exception) + if exception != nil { report_uncaught(cb.ctx, exception) mark_async_failed(cb.ctx) @@ -439,13 +490,19 @@ js_callback_trampoline :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // for the last time, or here when it is cancelled. js_callback_dispose :: proc(user_data: rawptr) { cb := cast(^JS_Callback)user_data - if cb == nil do return + + if cb == nil { + return + } + free_js_callback(cb) } report_uncaught :: proc(ctx: jsc.JSContextRef, exception: jsc.JSValueRef) { msg, allocated := jsc_value_to_string_or_default(ctx, exception) - defer if allocated do delete(msg, context.allocator) + defer if allocated { + delete(msg, context.allocator) + } process_write(os.stderr, "Uncaught ", msg, "\n") } @@ -472,9 +529,15 @@ unhandled_rejection_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() reason := jsc.JSValueMakeUndefined(ctx) - if argument_count >= 2 do reason = arguments[1] + + if argument_count >= 2 { + reason = arguments[1] + } + msg, allocated := jsc_value_to_string_or_default(ctx, reason) - defer if allocated do delete(msg, context.allocator) + defer if allocated { + delete(msg, context.allocator) + } process_write(os.stderr, "Uncaught (in promise) ", msg, "\n") mark_async_failed(ctx) return jsc.JSValueMakeUndefined(ctx) @@ -486,11 +549,17 @@ install_rejection_tracker :: proc(ctx: jsc.JSContextRef) { name := jsc.JSStringCreateWithUTF8CString("unhandledRejection") defer jsc.JSStringRelease(name) handler := jsc.JSObjectMakeFunctionWithCallback(ctx, name, unhandled_rejection_cb) - if handler == nil do return + + if handler == nil { + return + } + jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)handler) + if state := get_state_from_ctx(ctx); state != nil { state.rejection_handler = cast(jsc.JSValueRef)handler } + jsc.JSGlobalContextSetUnhandledRejectionCallback(cast(jsc.JSGlobalContextRef)ctx, handler, nil) } @@ -498,7 +567,11 @@ install_rejection_tracker :: proc(ctx: jsc.JSContextRef) { // set_named; used to read process.exitCode when resolving the exit code. get_named :: proc(ctx: jsc.JSContextRef, object: jsc.JSObjectRef, name: string) -> jsc.JSValueRef { c_name, err := strings.clone_to_cstring(name, context.temp_allocator) - if err != nil do return nil + + if err != nil { + return nil + } + js_name := jsc.JSStringCreateWithUTF8CString(c_name) defer jsc.JSStringRelease(js_name) return jsc.JSObjectGetProperty(ctx, object, js_name, nil) @@ -506,9 +579,16 @@ get_named :: proc(ctx: jsc.JSContextRef, object: jsc.JSObjectRef, name: string) // callback_arg returns the argument as a callable function object, or nil. callback_arg :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> jsc.JSObjectRef { - if !jsc.JSValueIsObject(ctx, value) do return nil + if !jsc.JSValueIsObject(ctx, value) { + return nil + } + obj := cast(jsc.JSObjectRef)value - if !jsc.JSObjectIsFunction(ctx, obj) do return nil + + if !jsc.JSObjectIsFunction(ctx, obj) { + return nil + } + return obj } @@ -531,7 +611,10 @@ MAX_SAFE_HANDLE_ID :: 9007199254740992.0 // I/O (and freezing the virtual clock), and the bounded value makes the u64() // conversion safe (float→int on NaN/Infinity/out-of-range is undefined in Odin). clamp_timer_delay :: proc(delay: f64) -> u64 { - if !(delay >= 1 && delay <= TIMER_MAX_MS) do return 1 + if !(delay >= 1 && delay <= TIMER_MAX_MS) { + return 1 + } + return u64(delay) } @@ -547,14 +630,24 @@ set_timeout_cb :: proc "c" ( // One state lookup serves both the loop and the binding allocator (see // JS_Callback.allocator); get_loop_from_ctx would repeat the two FFI crossings. state := get_state_from_ctx(ctx) - if state == nil || state.loop == nil || argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if state == nil || state.loop == nil || argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + loop, alloc := state.loop, state.allocator fn := callback_arg(ctx, arguments[0]) - if fn == nil do return jsc.JSValueMakeUndefined(ctx) + + if fn == nil { + return jsc.JSValueMakeUndefined(ctx) + } delay := 0.0 - if argument_count >= 2 do delay = jsc.JSValueToNumber(ctx, arguments[1], nil) + + if argument_count >= 2 { + delay = jsc.JSValueToNumber(ctx, arguments[1], nil) + } // Trailing args (setTimeout(fn, delay, ...args)) are forwarded on fire. cb := make_js_callback(ctx, fn, false, capture_timer_args(ctx, argument_count, arguments, 2, alloc), alloc) @@ -574,14 +667,24 @@ set_interval_cb :: proc "c" ( // One state lookup serves both the loop and the binding allocator (see // JS_Callback.allocator); get_loop_from_ctx would repeat the two FFI crossings. state := get_state_from_ctx(ctx) - if state == nil || state.loop == nil || argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if state == nil || state.loop == nil || argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + loop, alloc := state.loop, state.allocator fn := callback_arg(ctx, arguments[0]) - if fn == nil do return jsc.JSValueMakeUndefined(ctx) + + if fn == nil { + return jsc.JSValueMakeUndefined(ctx) + } interval := 0.0 - if argument_count >= 2 do interval = jsc.JSValueToNumber(ctx, arguments[1], nil) + + if argument_count >= 2 { + interval = jsc.JSValueToNumber(ctx, arguments[1], nil) + } // Trailing args (setInterval(fn, delay, ...args)) are forwarded on every fire. cb := make_js_callback(ctx, fn, true, capture_timer_args(ctx, argument_count, arguments, 2, alloc), alloc) @@ -601,11 +704,18 @@ set_immediate_cb :: proc "c" ( // One state lookup serves both the loop and the binding allocator (see // JS_Callback.allocator); get_loop_from_ctx would repeat the two FFI crossings. state := get_state_from_ctx(ctx) - if state == nil || state.loop == nil || argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if state == nil || state.loop == nil || argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + loop, alloc := state.loop, state.allocator fn := callback_arg(ctx, arguments[0]) - if fn == nil do return jsc.JSValueMakeUndefined(ctx) + + if fn == nil { + return jsc.JSValueMakeUndefined(ctx) + } // Trailing args (setImmediate(fn, ...args)) are forwarded on fire. cb := make_js_callback(ctx, fn, false, capture_timer_args(ctx, argument_count, arguments, 1, alloc), alloc) @@ -623,7 +733,10 @@ clear_timer_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() loop := get_loop_from_ctx(ctx) - if loop == nil || argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if loop == nil || argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } // clearTimeout/clearInterval(NaN) (and any non-finite/negative id) is a no-op in // Node — no handle can carry that id. Guard before u64(): float→int on NaN or an @@ -631,7 +744,11 @@ clear_timer_cb :: proc "c" ( // Handle ids start at 1 and grow unbounded, but stay f64-exact below 2^53, so the // upper bound is the exact-integer limit, not the timer-delay clamp. n := jsc.JSValueToNumber(ctx, arguments[0], nil) - if !(n >= 1 && n <= MAX_SAFE_HANDLE_ID) do return jsc.JSValueMakeUndefined(ctx) + + if !(n >= 1 && n <= MAX_SAFE_HANDLE_ID) { + return jsc.JSValueMakeUndefined(ctx) + } + eventloop.clear_timeout(loop, u64(n)) return jsc.JSValueMakeUndefined(ctx) } @@ -693,23 +810,34 @@ process_write_all :: proc(fd: ^os.File, data: []byte) -> (written: int, err: os. rest := data for len(rest) > 0 { n, werr := os.write(fd, rest) + if n > 0 { written += n rest = rest[n:] } + // A successful write of zero bytes would loop forever holding output_mutex. // Unreachable on Linux/darwin (core:os forces an error), but Windows' // WriteFile on a PIPE_NOWAIT handle returns TRUE with 0 written and // GetLastError() 0, which core:os maps to a nil error. Bail rather than spin. if werr == nil { - if n == 0 do return written, .Unexpected_EOF + if n == 0 { + return written, .Unexpected_EOF + } + continue } - if !stdio_retryable(werr) do return written, werr + + if !stdio_retryable(werr) { + return written, werr + } + // A retryable error with no progress means the fd is full (or a signal landed). // Wait for it to become writable instead of spinning; on the platforms where // this cannot be expressed the wait is a no-op and the loop simply retries. - if n == 0 do stdio_wait_writable(fd) + if n == 0 { + stdio_wait_writable(fd) + } } return written, nil } @@ -720,7 +848,10 @@ process_write_all :: proc(fd: ^os.File, data: []byte) -> (written: int, err: os. // retry loop — which is what keeps process.stdout.write and console.log from interleaving // mid-line under workers. process_write_bytes :: proc(fd: ^os.File, data: []byte) { - if len(data) == 0 do return + if len(data) == 0 { + return + } + sync.lock(&output_mutex) defer sync.unlock(&output_mutex) process_write_all(fd, data) @@ -739,7 +870,10 @@ process_write :: proc(fd: ^os.File, parts: ..string) { sync.lock(&output_mutex) defer sync.unlock(&output_mutex) for p in parts { - if len(p) == 0 do continue + if len(p) == 0 { + continue + } + process_write_all(fd, transmute([]byte)p) } } @@ -750,10 +884,16 @@ console_raw_write :: proc( argument_count: c.size_t, arguments: [^]jsc.JSValueRef, ) { - if argument_count < 1 do return + if argument_count < 1 { + return + } + text, allocated := jsc_value_to_string_or_default(ctx, arguments[0]) process_write(fd, text) - if allocated do delete(text, context.allocator) + + if allocated { + delete(text, context.allocator) + } } console_stdout_write_cb :: proc "c" ( @@ -797,19 +937,24 @@ process_exit_cb :: proc "c" ( // process.exitCode (Node parity). An explicit numeric code overrides it; a NaN // code is a RangeError (ERR_OUT_OF_RANGE) in Node, not a silent garbage exit. code := process_exit_code(ctx) + // JSValueGetType reads the value's type directly; JSValueIsUndefined is equally // ABI-safe now that it returns a 1-byte `bool` (see cmd/lava jsc_value_predicates, // #159 — the retired `b32` return was the old hazard). if argument_count >= 1 && jsc.JSValueGetType(ctx, arguments[0]) != .Undefined { n := jsc.JSValueToNumber(ctx, arguments[0], nil) + if n != n { if exception != nil { exception^ = err_out_of_range(ctx, "code", "an integer", "NaN") } + return jsc.JSValueMakeUndefined(ctx) } + code = int(n) } + os.exit(code) } @@ -823,7 +968,11 @@ process_cwd_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() dir, err := os.get_working_directory(context.temp_allocator) - if err != os.ERROR_NONE do return js_string_value(ctx, ".") + + if err != os.ERROR_NONE { + return js_string_value(ctx, ".") + } + return js_string_value(ctx, dir) } @@ -887,6 +1036,7 @@ install_globals :: proc(ctx: jsc.JSContextRef, loop: ^eventloop.Loop, surface: G install_performance(ctx, global) // process.nextTick + queueMicrotask are a JS shim (needs `process` to exist). install_microtasks(ctx, global, surface) + // process.stdout / process.stderr LAST of the process bits: the loader hands out a // closure rather than eager-requiring stdio, because stdio builds on `stream`, which // needs both the `process` global and `process.nextTick` to already be there. @@ -894,7 +1044,10 @@ install_globals :: proc(ctx: jsc.JSContextRef, loop: ^eventloop.Loop, surface: G // internal/stdio and the whole node-streams stack (node:stream, events, // internal/streams/*) for an object nothing can reach. console does not need it — // bootstrap/console.js writes through the native writers install_console hands it. - if surface == .Node do install_stdio(ctx, global) + if surface == .Node { + install_stdio(ctx, global) + } + install_rejection_tracker(ctx) } @@ -955,7 +1108,10 @@ performance_now_cb :: proc "c" ( // fact — and `.Web` appends no drain, so it simply never gets them. install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef, surface: Global_Surface = .Node) { process := get_named(ctx, global, "process") - if process == nil || !jsc.JSValueIsObject(ctx, process) do return + + if process == nil || !jsc.JSValueIsObject(ctx, process) { + return + } override_dir := js_override_dir() factory := eval_internal_source( @@ -965,17 +1121,24 @@ install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef, surfa "js/bootstrap/microtasks.js", MICROTASK_PRELUDE, ) - if factory == nil || !jsc.JSValueIsObject(ctx, factory) do return + + if factory == nil || !jsc.JSValueIsObject(ctx, factory) { + return + } // A throw from a nextTick/queueMicrotask callback is an uncaught exception // (not an unhandled rejection); the shim routes it here, the same path the // timer trampoline uses for async callbacks. report := make_native_function(ctx, "__lava_report_uncaught", microtask_report_uncaught_cb) - if report == nil do return + + if report == nil { + return + } args := [3]jsc.JSValueRef{cast(jsc.JSValueRef)global, process, cast(jsc.JSValueRef)report} exception: jsc.JSValueRef exports := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)factory, nil, 3, raw_data(args[:]), &exception) + if exception != nil { report_internal_exception(ctx, "lava:microtasks", exception) return @@ -985,16 +1148,24 @@ install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef, surfa // on Runtime_State; invoke_user_callback drives them so process.nextTick keeps // its priority over promise jobs across JSC's auto-draining promise queue (the // "why" is in js/bootstrap/microtasks.js). - if exports == nil || !jsc.JSValueIsObject(ctx, exports) do return + if exports == nil || !jsc.JSValueIsObject(ctx, exports) { + return + } + state := get_state_from_ctx(ctx) - if state == nil do return + + if state == nil { + return + } dispatch := get_named(ctx, cast(jsc.JSObjectRef)exports, "dispatch") drain := get_named(ctx, cast(jsc.JSObjectRef)exports, "drainNextTicks") + if dispatch != nil && jsc.JSValueIsObject(ctx, dispatch) { jsc.JSValueProtect(ctx, dispatch) state.dispatch_fn = dispatch } + if drain != nil && jsc.JSValueIsObject(ctx, drain) { jsc.JSValueProtect(ctx, drain) state.next_tick_drain = drain @@ -1034,6 +1205,7 @@ invoke_user_callback :: proc( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { state := get_state_from_ctx(ctx) + if state == nil || state.dispatch_fn == nil { return jsc.JSObjectCallAsFunction(ctx, fn, nil, argc, args, exception) } @@ -1064,16 +1236,23 @@ invoke_user_callback :: proc( // "drain nextTicks, run microtasks, repeat" loop. A throw cannot escape (the shim // runs nextTick callbacks guarded), but the exception arm is kept for safety. drain_next_ticks_settled :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) { - if state == nil || state.next_tick_drain == nil do return + if state == nil || state.next_tick_drain == nil { + return + } + for { exc: jsc.JSValueRef result := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)state.next_tick_drain, nil, 0, nil, &exc) + if exc != nil { report_uncaught(ctx, exc) mark_async_failed(ctx) return } - if result == nil || !bool(jsc.JSValueToBoolean(ctx, result)) do return + + if result == nil || !bool(jsc.JSValueToBoolean(ctx, result)) { + return + } } } @@ -1089,10 +1268,12 @@ microtask_report_uncaught_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count >= 1 { report_uncaught(ctx, arguments[0]) mark_async_failed(ctx) } + return jsc.JSValueMakeUndefined(ctx) } @@ -1112,18 +1293,30 @@ microtask_report_uncaught_cb :: proc "c" ( // lazy module's first require, once per context. See builtin_compile_cb. install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { state := get_state_from_ctx(ctx) - if state == nil do return + + if state == nil { + return + } override_dir := js_override_dir() loader := eval_internal_source(ctx, "internal:loader", override_dir, "js/bootstrap/loader.js", BOOTSTRAP_LOADER) - if loader == nil || !jsc.JSValueIsObject(ctx, loader) do return + + if loader == nil || !jsc.JSValueIsObject(ctx, loader) { + return + } // Cold native: called once per builtin per context, so the generic host path, // not a *_host wrapper. Passed as a bare argument, so it is reachable only from // the loader's closure — never from user code. compile := host_native_create(ctx, "compile", builtin_compile_cb, 1) - if compile == nil do compile = make_native_function(ctx, "compile", builtin_compile_cb) - if compile == nil do return + + if compile == nil { + compile = make_native_function(ctx, "compile", builtin_compile_cb) + } + + if compile == nil { + return + } // Native primitives keyed by module id. The loader passes natives[id] to // each factory as its fourth argument, so a module receives its Odin-backed @@ -1153,6 +1346,7 @@ install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) set_named(ctx, natives, "node/tty", cast(jsc.JSValueRef)make_tty_bindings(ctx)) set_named(ctx, natives, "node/fs", cast(jsc.JSValueRef)make_fs_bindings(ctx)) } + // Intrinsic process/console objects. Captured here (context init, before user // code) and handed to the factories so require('node:process') / // require('node:console') never re-read the globals — node returns the @@ -1161,6 +1355,7 @@ install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) if process_val := get_named(ctx, global, "process"); process_val != nil { set_named(ctx, natives, "node/process", process_val) } + if console_val := get_named(ctx, global, "console"); console_val != nil { set_named(ctx, natives, "node/console", console_val) } @@ -1168,11 +1363,15 @@ install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) args := [2]jsc.JSValueRef{cast(jsc.JSValueRef)compile, cast(jsc.JSValueRef)natives} exception: jsc.JSValueRef resolver := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)loader, nil, 2, raw_data(args[:]), &exception) + if exception != nil { report_internal_exception(ctx, "internal:loader", exception) return } - if resolver == nil || !jsc.JSValueIsObject(ctx, resolver) do return + + if resolver == nil || !jsc.JSValueIsObject(ctx, resolver) { + return + } jsc.JSValueProtect(ctx, resolver) state.builtin_require = resolver @@ -1194,8 +1393,10 @@ install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) // missing one leaves state.esm_transform nil and `.mjs` reports "ESM transform // unavailable" instead of silently transforming with the poisonable path. esm_factory := eval_internal_source(ctx, "lava:esm", override_dir, "js/bootstrap/esm.js", BOOTSTRAP_ESM) + if esm_factory != nil && jsc.JSValueIsObject(ctx, esm_factory) { primordials := get_named(ctx, cast(jsc.JSObjectRef)resolver, "primordials") + if primordials != nil && jsc.JSValueIsObject(ctx, primordials) { esm_args := [1]jsc.JSValueRef{primordials} esm_exception: jsc.JSValueRef @@ -1207,6 +1408,7 @@ install_internal_modules :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) raw_data(esm_args[:]), &esm_exception, ) + if esm_exception != nil { report_internal_exception(ctx, "lava:esm", esm_exception) } else if transform != nil && jsc.JSValueIsObject(ctx, transform) { @@ -1258,7 +1460,10 @@ builtin_compile_cb :: proc "c" ( runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD() undefined := jsc.JSValueMakeUndefined(ctx) state := get_state_from_ctx(ctx) - if state == nil || argument_count < 1 || !jsc.JSValueIsString(ctx, arguments[0]) do return undefined + + if state == nil || argument_count < 1 || !jsc.JSValueIsString(ctx, arguments[0]) { + return undefined + } // The loader builds ids by concatenation, so the argument is usually a rope, // which value_chars8 declines; read_string_arg flattens it. Where the cell read @@ -1266,46 +1471,92 @@ builtin_compile_cb :: proc "c" ( // string, so narrow it into a stack buffer; a non-ASCII unit or an id longer // than any embedded one cannot match. r := read_string_arg(ctx, arguments[0]) - defer if r.str != nil do jsc.JSStringRelease(r.str) - if !r.ok do return undefined + defer if r.str != nil { + jsc.JSStringRelease(r.str) + } + + if !r.ok { + return undefined + } + narrow: [64]byte id: string + if r.is8 { id = string(r.s8) } else { - if len(r.s16) > len(narrow) do return undefined + if len(r.s16) > len(narrow) { + return undefined + } + for u, i in r.s16 { - if u >= 0x80 do return undefined + if u >= 0x80 { + return undefined + } + narrow[i] = byte(u) } id = string(narrow[:len(r.s16)]) } // Excluded from this build (LAVA_NODE_MODULES=false): not a builtin. - if node_module_excluded(id) do return undefined + if node_module_excluded(id) { + return undefined + } slash := strings.last_index_byte(id, '/') - if slash <= 0 do return undefined + + if slash <= 0 { + return undefined + } + prefix, base := id[:slash], id[slash + 1:] - if len(base) == 0 do return undefined + + if len(base) == 0 { + return undefined + } for dir in EMBEDDED_JS_DIRS { - if dir.prefix != prefix do continue + if dir.prefix != prefix { + continue + } + for file in dir.files { - if len(file.name) != len(base) + 3 || !strings.has_suffix(file.name, ".js") do continue - if file.name[:len(base)] != base do continue + if len(file.name) != len(base) + 3 || !strings.has_suffix(file.name, ".js") { + continue + } + + if file.name[:len(base)] != base { + continue + } rel_path, rel_err := strings.concatenate({"js/", dir.prefix, "/", file.name}, context.temp_allocator) - if rel_err != nil do return undefined + + if rel_err != nil { + return undefined + } + // Source name is what a stack frame shows: `node:buffer`, `node:stream/web` // for public modules and `node:internal/fetch` for internal ones, the shape // node's own frames take (`node:internal/url`). spec := rel_path[len("js/"):len(rel_path) - len(".js")] - if strings.has_prefix(spec, "node/") do spec = spec[len("node/"):] + + if strings.has_prefix(spec, "node/") { + spec = spec[len("node/"):] + } + source_name, name_err := strings.concatenate({"node:", spec}, context.temp_allocator) - if name_err != nil do return undefined + + if name_err != nil { + return undefined + } + factory := eval_internal_source(ctx, source_name, js_override_dir(), rel_path, string(file.data)) - if factory == nil do return undefined + + if factory == nil { + return undefined + } + state.builtin_compiles += 1 return factory } @@ -1323,7 +1574,11 @@ require_builtin :: proc( out_exception: ^jsc.JSValueRef = nil, ) -> jsc.JSValueRef { state := get_state_from_ctx(ctx) - if state == nil || state.builtin_require == nil do return nil + + if state == nil || state.builtin_require == nil { + return nil + } + args := [1]jsc.JSValueRef{specifier} exception: jsc.JSValueRef result := jsc.JSObjectCallAsFunction( @@ -1334,14 +1589,22 @@ require_builtin :: proc( raw_data(args[:]), &exception, ) + // A builtin factory that threw (e.g. a lazy module failing to initialize) must // surface that error, not be mistaken for "not a builtin" and fall through to // filesystem resolution as a misleading MODULE_NOT_FOUND. if exception != nil { - if out_exception != nil do out_exception^ = exception + if out_exception != nil { + out_exception^ = exception + } + return nil } - if result == nil || jsc.JSValueIsUndefined(ctx, result) do return nil + + if result == nil || jsc.JSValueIsUndefined(ctx, result) { + return nil + } + return result } @@ -1351,15 +1614,30 @@ require_builtin :: proc( // stdio leaves the properties undefined, which is exactly the pre-existing behavior. install_stdio :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { state := get_state_from_ctx(ctx) - if state == nil || state.builtin_require == nil do return + + if state == nil || state.builtin_require == nil { + return + } + installer := get_named(ctx, cast(jsc.JSObjectRef)state.builtin_require, "installStdio") - if installer == nil || !jsc.JSValueIsObject(ctx, installer) do return + + if installer == nil || !jsc.JSValueIsObject(ctx, installer) { + return + } + proc_obj := get_named(ctx, global, "process") - if proc_obj == nil || !jsc.JSValueIsObject(ctx, proc_obj) do return + + if proc_obj == nil || !jsc.JSValueIsObject(ctx, proc_obj) { + return + } + args := [1]jsc.JSValueRef{proc_obj} exception: jsc.JSValueRef jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)installer, nil, 1, raw_data(args[:]), &exception) - if exception != nil do report_internal_exception(ctx, "internal:stdio", exception) + + if exception != nil { + report_internal_exception(ctx, "internal:stdio", exception) + } } // install_console builds the full `console` object. CONSOLE_PRELUDE evaluates @@ -1371,16 +1649,25 @@ install_stdio :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { install_console :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { out_fn := make_native_function(ctx, "__lava_write_out", console_stdout_write_cb) err_fn := make_native_function(ctx, "__lava_write_err", console_stderr_write_cb) - if out_fn == nil || err_fn == nil do return + + if out_fn == nil || err_fn == nil { + return + } override_dir := js_override_dir() factory := eval_internal_source(ctx, "lava:console", override_dir, "js/bootstrap/console.js", CONSOLE_PRELUDE) - if factory == nil || !jsc.JSValueIsObject(ctx, factory) do return + + if factory == nil || !jsc.JSValueIsObject(ctx, factory) { + return + } args := [2]jsc.JSValueRef{cast(jsc.JSValueRef)out_fn, cast(jsc.JSValueRef)err_fn} exception: jsc.JSValueRef jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)factory, nil, 2, raw_data(args[:]), &exception) - if exception != nil do report_internal_exception(ctx, "lava:console", exception) + + if exception != nil { + report_internal_exception(ctx, "lava:console", exception) + } } // make_native_function wraps an Odin callback as a standalone JS function value @@ -1392,7 +1679,11 @@ make_native_function :: proc( callback: jsc.JSObjectCallAsFunctionCallback, ) -> jsc.JSObjectRef { c_name, err := strings.clone_to_cstring(name, context.temp_allocator) - if err != nil do return nil + + if err != nil { + return nil + } + js_name := jsc.JSStringCreateWithUTF8CString(c_name) defer jsc.JSStringRelease(js_name) return jsc.JSObjectMakeFunctionWithCallback(ctx, js_name, callback) @@ -1467,10 +1758,18 @@ js_override_dir :: proc() -> string { break } } - if last_sep < 0 do return "" + + if last_sep < 0 { + return "" + } + runtime_dir := file[:last_sep] marker, err := strings.concatenate({runtime_dir, "/../../bin/.lava.js-override"}, context.temp_allocator) - if err != nil || !os.exists(marker) do return "" + + if err != nil || !os.exists(marker) { + return "" + } + return runtime_dir } } @@ -1484,12 +1783,14 @@ eval_internal_source :: proc( ) -> jsc.JSValueRef { if len(override_dir) > 0 && len(rel_path) > 0 { full_path, err := strings.concatenate({override_dir, "/", rel_path}, context.temp_allocator) + if err == nil { if data, read_err := os.read_entire_file(full_path, context.temp_allocator); read_err == os.ERROR_NONE { return eval_internal(ctx, name, string(data)) } } } + return eval_internal(ctx, name, embedded) } @@ -1498,28 +1799,41 @@ eval_internal_source :: proc( // code; nil is returned in that case. eval_internal :: proc(ctx: jsc.JSContextRef, name: string, source: string) -> jsc.JSValueRef { c_source, source_err := strings.clone_to_cstring(source, context.temp_allocator) - if source_err != nil do return nil + + if source_err != nil { + return nil + } + js_source := jsc.JSStringCreateWithUTF8CString(c_source) defer jsc.JSStringRelease(js_source) c_name, name_err := strings.clone_to_cstring(name, context.temp_allocator) - if name_err != nil do return nil + + if name_err != nil { + return nil + } + js_name := jsc.JSStringCreateWithUTF8CString(c_name) defer jsc.JSStringRelease(js_name) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, js_source, nil, js_name, 1, &exception) + if exception != nil { report_internal_exception(ctx, name, exception) return nil } + return value } report_internal_exception :: proc(ctx: jsc.JSContextRef, name: string, exception: jsc.JSValueRef) { msg, allocated := jsc_value_to_string_or_default(ctx, exception) process_write(os.stderr, "lava: failed to initialize ", name, ": ", msg, "\n") - if allocated do delete(msg, context.allocator) + + if allocated { + delete(msg, context.allocator) + } } install_process :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { @@ -1538,9 +1852,11 @@ install_process :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { // Node's argv layout is [execPath, scriptPath, ...userArgs] (eval() builds it // on the state). Fall back to os.args only for embedders that never set it. argv := os.args + if state := get_state_from_ctx(ctx); state != nil && len(state.script_argv) > 0 { argv = state.script_argv } + set_named(ctx, process, "argv", cast(jsc.JSValueRef)build_string_array(ctx, argv)) set_named(ctx, process, "env", cast(jsc.JSValueRef)build_env_object(ctx)) @@ -1554,7 +1870,11 @@ install_process :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { process_version_string :: proc() -> string { parts := [?]string{"v", NODE_BASELINE, ".0.0"} result, err := strings.concatenate(parts[:], context.temp_allocator) - if err != nil do return "v22.0.0" + + if err != nil { + return "v22.0.0" + } + return result } @@ -1562,7 +1882,11 @@ process_version_string :: proc() -> string { set_named :: proc(ctx: jsc.JSContextRef, object: jsc.JSObjectRef, name: string, value: jsc.JSValueRef) { c_name, err := strings.clone_to_cstring(name, context.temp_allocator) - if err != nil do return + + if err != nil { + return + } + js_name := jsc.JSStringCreateWithUTF8CString(c_name) defer jsc.JSStringRelease(js_name) jsc.JSObjectSetProperty(ctx, object, js_name, value, {}, nil) @@ -1590,10 +1914,18 @@ build_string_array :: proc(ctx: jsc.JSContextRef, items: []string) -> jsc.JSObje build_env_object :: proc(ctx: jsc.JSContextRef) -> jsc.JSObjectRef { object := jsc.JSObjectMake(ctx, nil, nil) environ, err := os.environ(context.temp_allocator) - if err != os.ERROR_NONE do return object + + if err != os.ERROR_NONE { + return object + } + for entry in environ { idx := strings.index_byte(entry, '=') - if idx <= 0 do continue + + if idx <= 0 { + continue + } + set_named(ctx, object, entry[:idx], js_string_value(ctx, entry[idx + 1:])) } return object diff --git a/pkg/runtime/host_natives.odin b/pkg/runtime/host_natives.odin index bc7b1999..def1d964 100644 --- a/pkg/runtime/host_natives.odin +++ b/pkg/runtime/host_natives.odin @@ -26,20 +26,30 @@ host_dispatch :: proc "c" (global: rawptr, cf: [^]u64, cb: jsc.JSObjectCallAsFun context = runtime.default_context() // valid allocator for the overflow slice below ctx := jsc.JSContextRef(global) argc := int(u32(cf[jsc.CALL_FRAME_ARGC_SLOT] & 0xFFFFFFFF)) - 1 // minus `this` - if argc < 0 do argc = 0 + + if argc < 0 { + argc = 0 + } + // Deliver every argument. Fixed stack buffer for the common small case; a // genuinely variadic caller (setTimeout(fn, delay, ...args)) that overflows // it uses a temp slice rather than being silently truncated. stack_args: [16]jsc.JSValueRef args: []jsc.JSValueRef = stack_args[:] + if argc > len(stack_args) { overflow, alloc_err := make([]jsc.JSValueRef, argc, context.temp_allocator) + // Fail closed, same rule as a dispatch miss: a nil slice faults at &args[0] // and a truncated one would run the native against arguments it was never // passed. Reachable only at >16 args under temp-arena OOM. - if alloc_err != nil do return host_dispatch_fail(ctx, "lava: host native dispatch failed (argument allocation)") + if alloc_err != nil { + return host_dispatch_fail(ctx, "lava: host native dispatch failed (argument allocation)") + } + args = overflow } + for i in 0 ..< argc { args[i] = jsc.JSValueRef(uintptr(cf[jsc.CALL_FRAME_FIRST_ARG_SLOT + i])) } @@ -47,36 +57,53 @@ host_dispatch :: proc "c" (global: rawptr, cf: [^]u64, cb: jsc.JSObjectCallAsFun this := host_cell_object(cf[jsc.CALL_FRAME_THIS_SLOT]) exception: jsc.JSValueRef ret := cb(ctx, callee, this, c.size_t(argc), &args[0], &exception) + if exception != nil { // Same rule as host_dispatch_fail: never return a value we know is not an // exception. Here g_host_ok is implied (we got here via a table hit, so // registration ran on this thread), but the check costs nothing and keeps // the two sites from drifting. - if !jsc.host_throw(ctx, exception) do return transmute(i64)jsc.JSValueMakeUndefined(ctx) + if !jsc.host_throw(ctx, exception) { + return transmute(i64)jsc.JSValueMakeUndefined(ctx) + } + return transmute(i64)exception } - if ret == nil do return transmute(i64)jsc.JSValueMakeUndefined(ctx) + + if ret == nil { + return transmute(i64)jsc.JSValueMakeUndefined(ctx) + } + return transmute(i64)ret } @(private = "file") host_cell_object :: proc "contextless" (bits: u64) -> jsc.JSObjectRef { - if bits == 0 || (bits & jsc.VALUE_NOT_CELL_MASK) != 0 do return nil + if bits == 0 || (bits & jsc.VALUE_NOT_CELL_MASK) != 0 { + return nil + } + return jsc.JSObjectRef(uintptr(bits)) } // js_int_arg reads an integer argument without a C-API call when it is an // immediate int32 (the common case for offsets/lengths from the JS layer). js_int_arg :: proc(ctx: jsc.JSContextRef, v: jsc.JSValueRef) -> int { - if x, ok := jsc.value_int32(ctx, v); ok do return int(x) + if x, ok := jsc.value_int32(ctx, v); ok { + return int(x) + } + return int(jsc.JSValueToNumber(ctx, v, nil)) } // js_int_value encodes an integer result without a C-API call when possible. js_int_value :: proc(ctx: jsc.JSContextRef, v: int) -> jsc.JSValueRef { if v >= -2147483648 && v <= 2147483647 { - if r, ok := jsc.make_int32(ctx, i32(v)); ok do return r + if r, ok := jsc.make_int32(ctx, i32(v)); ok { + return r + } } + return jsc.JSValueMakeNumber(ctx, f64(v)) } @@ -141,7 +168,10 @@ g_host_tables_bound: bool // purpose: re-running the reserve on every injection would buy nothing. @(private = "file") bind_host_tables :: proc() { - if g_host_tables_bound do return + if g_host_tables_bound { + return + } + g_host_tables_bound = true sync.atomic_add(&g_host_tables_live, 1) g_host_native_fns, _ = make(map[Host_Native_Key]jsc.JSObjectRef, 64, runtime.default_allocator()) @@ -165,7 +195,10 @@ g_host_tables_live: int // both backings — once per worker thread per lifetime. Pinned by // workers_give_back_their_host_tables (pkg/runtime/workers_test.odin). host_native_thread_teardown :: proc() { - if !g_host_tables_bound do return + if !g_host_tables_bound { + return + } + // Every context's entries went with it (host_natives_release_context); one still // here means a context outlived the thread, and its names would leak with it. assert(len(g_host_native_fns) == 0, "host_native_thread_teardown: a context on this thread is still alive") @@ -191,9 +224,11 @@ generic_native_host_cb :: proc "c" (global: rawptr, cf: [^]u64) -> i64 { // bench/micro/encoding.js, zero misses). Keeping the cold path in its own // #force_no_inline proc restores the previous codegen instruction-for-instruction. cb, found := g_host_native_cbs[rawptr(uintptr(cf[jsc.CALL_FRAME_CALLEE_SLOT]))] + if !found { return host_dispatch_fail(jsc.JSContextRef(global), "lava: host native dispatch failed (unregistered callee)") } + return host_dispatch(global, cf, cb) } @@ -223,6 +258,7 @@ generic_native_host_cb :: proc "c" (global: rawptr, cf: [^]u64) -> i64 { host_dispatch_fail :: #force_no_inline proc "c" (ctx: jsc.JSContextRef, why: string) -> i64 { context = runtime.default_context() exception := make_js_error(ctx, why) + // Both guards matter. make_js_error can return nil under OOM; returning it // would hand JSC the EMPTY JSValue with no pending exception, which is its // TDZ sentinel and isCell()-true — a segfault or a bogus "cannot access @@ -233,8 +269,14 @@ host_dispatch_fail :: #force_no_inline proc "c" (ctx: jsc.JSContextRef, why: str // ordinary VALUE the moment that reasoning rots, and that is fail-open // again. Undefined is the honest answer when we cannot raise: wrong, but not // a crash and not a forged success. - if exception == nil do return transmute(i64)jsc.JSValueMakeUndefined(ctx) - if !jsc.host_throw(ctx, exception) do return transmute(i64)jsc.JSValueMakeUndefined(ctx) + if exception == nil { + return transmute(i64)jsc.JSValueMakeUndefined(ctx) + } + + if !jsc.host_throw(ctx, exception) { + return transmute(i64)jsc.JSValueMakeUndefined(ctx) + } + return transmute(i64)exception } @@ -273,9 +315,12 @@ host_native_create :: proc( arity: int = 1, ) -> jsc.JSObjectRef { key := Host_Native_Key{rawptr(ctx), transmute(rawptr)cb, name} + // Lookup first: the hit path is hot (measured ~60k hits per 20k fs.statSync, // three per Stats instance) and must not pay for anything below it. - if fn, hit := g_host_native_fns[key]; hit do return fn + if fn, hit := g_host_native_fns[key]; hit { + return fn + } // State FIRST, before anything is created. Names are cloned through the // Runtime_State's allocator, not the ambient one: this runs from @@ -292,14 +337,22 @@ host_native_create :: proc( // stateless (embedder) context used to mint a JSFunction, protect it, bind two // maps and then discard all three on EVERY injection. state := get_state_from_ctx(ctx) - if state == nil do return nil + + if state == nil { + return nil + } fn, ok := jsc.host_function_create(ctx, name, generic_native_host_cb, arity) - if !ok || fn == nil do return nil + + if !ok || fn == nil { + return nil + } + jsc.JSValueProtect(ctx, jsc.JSValueRef(fn)) bind_host_tables() alloc := state.allocator cloned, clone_err := strings.clone(name, alloc) + if clone_err != nil { // Raw unprotect on purpose, unlike the sweep below: a mid-run rollback of // the protect taken above, with the context fully healthy. @@ -308,7 +361,9 @@ host_native_create :: proc( jsc.JSValueUnprotect(ctx, jsc.JSValueRef(fn)) return nil } + key.name = cloned // outlive the caller's (possibly temp) string + // CHECKED inserts. A bare `m[k] = v` discards the allocator error, and a half // -inserted pair is worse than no cache: an entry in cbs that fns does not // know about is unreachable from the sweep (it walks fns keys), so it would @@ -322,12 +377,14 @@ host_native_create :: proc( jsc.JSValueUnprotect(ctx, jsc.JSValueRef(fn)) return nil } + if map_insert(&g_host_native_cbs, rawptr(fn), cb) == nil { delete_key(&g_host_native_fns, key) delete(cloned, alloc) jsc.JSValueUnprotect(ctx, jsc.JSValueRef(fn)) return nil } + return fn } @@ -345,7 +402,10 @@ host_natives_release_context :: proc(ctx: jsc.JSContextRef, alloc: mem.Allocator // would silently leave live entries keyed by a dead context — the exact // use-after-free this sweep exists to prevent, with no diagnostic. for key, fn in g_host_native_fns { - if key.ctx != rawptr(ctx) do continue + if key.ctx != rawptr(ctx) { + continue + } + // Through the shared helper, NOT a raw JSValueUnprotect: it skips the // unprotect on Windows on purpose (final teardown races the VM's GC/JIT // workers and exits 127; the VM is intentionally leaked there anyway). diff --git a/pkg/runtime/http.odin b/pkg/runtime/http.odin index 0f262fa5..4c96ae48 100644 --- a/pkg/runtime/http.odin +++ b/pkg/runtime/http.odin @@ -62,18 +62,31 @@ http_parse_request_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return http_parse_status(ctx, PARSE_ERROR) + + if argument_count < 2 { + return http_parse_status(ctx, PARSE_ERROR) + } + args := arguments[:int(argument_count)] // js_int_arg can run JS (valueOf) — read it before borrowing the view; see // the note in buffer_utf16le_write_into_cb (buffer.odin). last_len := js_int_arg(ctx, args[1]) view, ok := typed_array_view(ctx, args[0]) - if !ok do return http_parse_status(ctx, PARSE_ERROR) + + if !ok { + return http_parse_status(ctx, PARSE_ERROR) + } hdrs: [pico.MAX_HEADERS]pico.Header consumed, minor, num, method, path, res := pico.parse_request(view, last_len, hdrs[:]) - if res == .Partial do return http_parse_status(ctx, PARSE_PARTIAL) - if res == .Error do return http_parse_status(ctx, PARSE_ERROR) + + if res == .Partial { + return http_parse_status(ctx, PARSE_PARTIAL) + } + + if res == .Error { + return http_parse_status(ctx, PARSE_ERROR) + } // Interleaved [name, value, ...]; RFC 7230 obs-fold continuations (empty name) are // merged into the previous value with a single space. NAMES are kept in their @@ -83,6 +96,7 @@ http_parse_request_cb :: proc "c" ( last_val_idx := -1 for i in 0 ..< num { h := hdrs[i] + if h.name == "" { if last_val_idx >= 0 { cont := strings.trim_space(h.value) @@ -91,8 +105,10 @@ http_parse_request_cb :: proc "c" ( context.temp_allocator, ) } + continue } + append(&hdr_list, h.name) append(&hdr_list, strings.trim_space(h.value)) last_val_idx = len(hdr_list) - 1 diff --git a/pkg/runtime/js_root.odin b/pkg/runtime/js_root.odin index 17784f61..3596b145 100644 --- a/pkg/runtime/js_root.odin +++ b/pkg/runtime/js_root.odin @@ -21,17 +21,26 @@ import jsc "lava:pkg/jsc" js_root_set :: proc(ctx: jsc.JSContextRef, slot: ^jsc.JSObjectRef, fn: jsc.JSObjectRef) { assert(slot^ == nil, "js_root_set requires an empty slot (clear it first)") slot^ = fn - if fn != nil do jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)fn) + + if fn != nil { + jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)fn) + } } js_root_clear :: proc(ctx: jsc.JSContextRef, slot: ^jsc.JSObjectRef) { - if slot^ == nil do return + if slot^ == nil { + return + } + jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)slot^) slot^ = nil } js_root_clear_private :: proc(ctx: jsc.JSContextRef, slot: ^jsc.JSObjectRef) { - if slot^ == nil do return + if slot^ == nil { + return + } + jsc.JSObjectSetPrivate(slot^, nil) jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)slot^) slot^ = nil diff --git a/pkg/runtime/module_resolution.odin b/pkg/runtime/module_resolution.odin index 273353be..d8981aec 100644 --- a/pkg/runtime/module_resolution.odin +++ b/pkg/runtime/module_resolution.odin @@ -16,13 +16,16 @@ resolve_module_path :: proc(specifier: string, base_dir: string) -> (string, boo // caller-owned allocator (and canonicalize so redundant separators/symlinks // collapse to one module-cache key). canonical := resolved + if abs_path, abs_err := filepath.abs(resolved, context.temp_allocator); abs_err == os.ERROR_NONE && len(abs_path) > 0 { canonical = abs_path } + owned, _ := strings.clone(canonical, context.allocator) return owned, true } + return "", false } @@ -39,15 +42,29 @@ resolve_module_temp :: proc(specifier: string, base_dir: string) -> (string, boo if is_relative || is_absolute_path(specifier) { base := specifier + if !is_absolute_path(specifier) { dir := base_dir - if len(dir) == 0 do dir = "." + + if len(dir) == 0 { + dir = "." + } + joined, join_err := filepath.join({dir, specifier}, context.temp_allocator) - if join_err != nil do return "", false + + if join_err != nil { + return "", false + } + base = joined } + cleaned, clean_err := filepath.clean(base, context.temp_allocator) - if clean_err != nil do return "", false + + if clean_err != nil { + return "", false + } + return resolve_file_or_directory(cleaned) } @@ -59,18 +76,30 @@ resolve_module_temp :: proc(specifier: string, base_dir: string) -> (string, boo // resolve_file_or_directory tries `base` as a file (with extension probes) and, if // it is a directory, via package.json "main" / index.*. resolve_file_or_directory :: proc(base: string) -> (string, bool) { - if resolved, ok := resolve_as_file(base); ok do return resolved, true - if os.is_dir(base) do return resolve_as_directory(base) + if resolved, ok := resolve_as_file(base); ok { + return resolved, true + } + + if os.is_dir(base) { + return resolve_as_directory(base) + } + return "", false } // resolve_as_file returns `base` if it is a regular file, else the first hit of the // extension probes. Probe order is Node's (.js, .json) then Lava's CJS/ESM extras. resolve_as_file :: proc(base: string) -> (string, bool) { - if module_resolvable_file(base) do return base, true + if module_resolvable_file(base) { + return base, true + } + for ext in ([?]string{".js", ".json", ".cjs", ".mjs"}) { with_ext := strings.concatenate({base, ext}, context.temp_allocator) - if module_resolvable_file(with_ext) do return with_ext, true + + if module_resolvable_file(with_ext) { + return with_ext, true + } } return "", false } @@ -80,24 +109,37 @@ resolve_as_file :: proc(base: string) -> (string, bool) { resolve_as_directory :: proc(dir: string) -> (string, bool) { if main, ok := package_main(dir); ok { main_base, join_err := filepath.join({dir, main}, context.temp_allocator) + if join_err == nil { cleaned, clean_err := filepath.clean(main_base, context.temp_allocator) + if clean_err == nil { - if resolved, ok2 := resolve_as_file(cleaned); ok2 do return resolved, true + if resolved, ok2 := resolve_as_file(cleaned); ok2 { + return resolved, true + } + // "main" may point at a directory whose index.* is the entry. if os.is_dir(cleaned) { - if resolved, ok3 := resolve_directory_index(cleaned); ok3 do return resolved, true + if resolved, ok3 := resolve_directory_index(cleaned); ok3 { + return resolved, true + } } } } + // Fall through to index.* when "main" is unresolvable (matches Node). } + return resolve_directory_index(dir) } resolve_directory_index :: proc(dir: string) -> (string, bool) { index_base, join_err := filepath.join({dir, "index"}, context.temp_allocator) - if join_err != nil do return "", false + + if join_err != nil { + return "", false + } + return resolve_as_file(index_base) } @@ -106,17 +148,26 @@ resolve_directory_index :: proc(dir: string) -> (string, bool) { // scoped (@scope/name) and subpath (pkg/lib/x) specifiers since they embed the // separator that filepath.join preserves. resolve_node_modules :: proc(specifier: string, base_dir: string) -> (string, bool) { - if len(base_dir) == 0 do return "", false + if len(base_dir) == 0 { + return "", false + } + dir := base_dir for { target, join_err := filepath.join({dir, "node_modules", specifier}, context.temp_allocator) + if join_err == nil { - if resolved, ok := resolve_file_or_directory(target); ok do return resolved, true + if resolved, ok := resolve_file_or_directory(target); ok { + return resolved, true + } } + parent := filepath.dir(dir) - if parent == dir || len(parent) == 0 do break // reached the root + + if parent == dir || len(parent) == 0 {break} // reached the root dir = parent } + return "", false } @@ -124,18 +175,30 @@ resolve_node_modules :: proc(specifier: string, base_dir: string) -> (string, bo // non-empty. (Only "main" is read; "exports" conditional resolution is unsupported.) package_main :: proc(dir: string) -> (string, bool) { pkg_path, join_err := filepath.join({dir, "package.json"}, context.temp_allocator) - if join_err != nil do return "", false + + if join_err != nil { + return "", false + } + data, read_err := os.read_entire_file(pkg_path, context.temp_allocator) - if read_err != os.ERROR_NONE do return "", false + + if read_err != os.ERROR_NONE { + return "", false + } Package :: struct { main: string, } pkg: Package + if json.unmarshal(data, &pkg, json.DEFAULT_SPECIFICATION, context.temp_allocator) != nil { return "", false } - if len(pkg.main) == 0 do return "", false + + if len(pkg.main) == 0 { + return "", false + } + return pkg.main, true } @@ -168,13 +231,20 @@ global_dirname :: proc(ctx: jsc.JSContextRef) -> (string, bool) { // own isAbsolute lives in js/node/path.js.) is_absolute_path :: proc(path: string) -> bool { when ODIN_OS == .Windows { - if len(path) == 0 do return false + if len(path) == 0 { + return false + } + // Leading separator, including UNC paths (\\server\share) and '//'. - if path[0] == '/' || path[0] == '\\' do return true + if path[0] == '/' || path[0] == '\\' { + return true + } + // Drive-letter absolute path: 'C:\' or 'C:/'. if len(path) >= 3 && is_ascii_letter(path[0]) && path[1] == ':' && (path[2] == '/' || path[2] == '\\') { return true } + return false } else { return strings.has_prefix(path, "/") diff --git a/pkg/runtime/net.odin b/pkg/runtime/net.odin index 4e2c2d93..4f7ce3fc 100644 --- a/pkg/runtime/net.odin +++ b/pkg/runtime/net.odin @@ -48,12 +48,14 @@ net_tls_handshake_timeout_ms_cached: u64 = 0 net_tls_handshake_timeout_ms :: proc() -> u64 { if net_tls_handshake_timeout_ms_cached == 0 { net_tls_handshake_timeout_ms_cached = TLS_HANDSHAKE_TIMEOUT_MS + if v := os.get_env("LAVA_TLS_HANDSHAKE_TIMEOUT_MS", context.temp_allocator); v != "" { if ms, ok := strconv.parse_int(v); ok && ms > 0 { net_tls_handshake_timeout_ms_cached = u64(ms) } } } + return net_tls_handshake_timeout_ms_cached } @@ -209,25 +211,44 @@ net_listen_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 4 { - if exception != nil do exception^ = make_js_error(ctx, "net.listen requires (port, host, backlog, onConnection)") + if exception != + nil {exception^ = make_js_error(ctx, "net.listen requires (port, host, backlog, onConnection)")} + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] port := int(jsc.JSValueToNumber(ctx, args[0], nil)) host, host_alloc := jsc_value_to_string_or_default(ctx, args[1]) - defer if host_alloc do delete(host, context.allocator) + defer if host_alloc { + delete(host, context.allocator) + } backlog := int(jsc.JSValueToNumber(ctx, args[2], nil)) - if backlog <= 0 do backlog = NET_DEFAULT_BACKLOG + + if backlog <= 0 { + backlog = NET_DEFAULT_BACKLOG + } + on_connection := callback_arg(ctx, args[3]) + if on_connection == nil { - if exception != nil do exception^ = make_js_error(ctx, "net.listen onConnection must be a function") + if exception != nil { + exception^ = make_js_error(ctx, "net.listen onConnection must be a function") + } + return jsc.JSValueMakeUndefined(ctx) } + loop := get_loop_from_ctx(ctx) state := get_state_from_ctx(ctx) + if loop == nil || state == nil { - if exception != nil do exception^ = make_js_error(ctx, "net: no event loop is bound to this context") + if exception != nil { + exception^ = make_js_error(ctx, "net: no event loop is bound to this context") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -238,20 +259,31 @@ net_listen_cb :: proc "c" ( // (listen_ok), at which point the defer no-ops and net_close_server owns the free. tls_ctx: rawptr = nil tls_enabled := false + if argument_count >= 5 && jsc.JSValueIsNumber(ctx, args[4]) { ctx_id := u64(jsc.JSValueToNumber(ctx, args[4], nil)) + if found, ok := state.tls_server_ctxs[ctx_id]; ok { tls_ctx = found tls_enabled = true delete_key(&state.tls_server_ctxs, ctx_id) } else { - if g_multi_worker do net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: invalid TLS context handle") + if g_multi_worker { + net_startup_failed() + } + + if exception != nil { + exception^ = make_js_error(ctx, "net.listen: invalid TLS context handle") + } + return jsc.JSValueMakeUndefined(ctx) } } + listen_ok := false - defer if !listen_ok && tls_enabled do tls_server_ctx_free(cast(SSL_CTX)tls_ctx) + defer if !listen_ok && tls_enabled { + tls_server_ctx_free(cast(SSL_CTX)tls_ctx) + } // Multi-worker (Slice 3a): every worker binds the same addr:port and the kernel load-balances // connections across them via SO_REUSEPORT. An ephemeral port (0) can't work — each worker would @@ -260,19 +292,31 @@ net_listen_cb :: proc "c" ( // can't come up on one core must not run degraded on the others. if g_multi_worker && port == 0 { net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: an explicit port is required under LAVA_WORKERS>1 (ephemeral port 0 is not supported)") + + if exception != + nil {exception^ = make_js_error(ctx, "net.listen: an explicit port is required under LAVA_WORKERS>1 (ephemeral port 0 is not supported)")} + return jsc.JSValueMakeUndefined(ctx) } sfd, sock_err := linux.socket(.INET, .STREAM, {.NONBLOCK}, .TCP) + if sock_err != .NONE { - if g_multi_worker do net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: could not create socket") + if g_multi_worker { + net_startup_failed() + } + + if exception != nil { + exception^ = make_js_error(ctx, "net.listen: could not create socket") + } + return jsc.JSValueMakeUndefined(ctx) } + // SO_REUSEADDR so a restart can rebind a port still in TIME_WAIT (best-effort). reuse: i32 = 1 _ = linux.setsockopt(sfd, linux.SOL_SOCKET, linux.Socket_Option.REUSEADDR, &reuse) + // SO_REUSEPORT for the multi-worker listener group. Unlike REUSEADDR its result MUST be checked: // every socket sharing the port must set it, or the group is unsafe (a bind would collide). Surface // the failure as a startup abort. @@ -280,7 +324,11 @@ net_listen_cb :: proc "c" ( if so_err := linux.setsockopt(sfd, linux.SOL_SOCKET, linux.Socket_Option.REUSEPORT, &reuse); so_err != .NONE { linux.close(sfd) net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: SO_REUSEPORT failed") + + if exception != nil { + exception^ = make_js_error(ctx, "net.listen: SO_REUSEPORT failed") + } + return jsc.JSValueMakeUndefined(ctx) } } @@ -290,8 +338,10 @@ net_listen_cb :: proc "c" ( // interface. M1 binds IPv4 only: accept a numeric IPv4 or "localhost"; reject IPv6 // literals and anything else (a real resolver is a later milestone). ip4 := net.IP4_Address{0, 0, 0, 0} + if len(host) > 0 && host != "0.0.0.0" { resolved := false + if parsed := net.parse_address(host); parsed != nil { #partial switch a in parsed { case net.IP4_Address: @@ -302,27 +352,48 @@ net_listen_cb :: proc "c" ( ip4 = net.IP4_Address{127, 0, 0, 1} resolved = true } + if !resolved { linux.close(sfd) - if exception != nil do exception^ = make_js_error(ctx, "net.listen: unsupported host (only numeric IPv4 and 'localhost' are supported)") + + if exception != + nil {exception^ = make_js_error(ctx, "net.listen: unsupported host (only numeric IPv4 and 'localhost' are supported)")} + return jsc.JSValueMakeUndefined(ctx) } } + addr := linux.Sock_Addr_In { sin_family = .INET, sin_port = u16be(u16(port)), sin_addr = transmute([4]u8)ip4, } + if bind_err := linux.bind(sfd, &addr); bind_err != .NONE { linux.close(sfd) - if g_multi_worker do net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: bind failed (address in use?)") + + if g_multi_worker { + net_startup_failed() + } + + if exception != nil { + exception^ = make_js_error(ctx, "net.listen: bind failed (address in use?)") + } + return jsc.JSValueMakeUndefined(ctx) } + if listen_err := linux.listen(sfd, i32(backlog)); listen_err != .NONE { linux.close(sfd) - if g_multi_worker do net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: listen failed") + + if g_multi_worker { + net_startup_failed() + } + + if exception != nil { + exception^ = make_js_error(ctx, "net.listen: listen failed") + } + return jsc.JSValueMakeUndefined(ctx) } @@ -344,15 +415,23 @@ net_listen_cb :: proc "c" ( callback = net_accept_cb, user_data = server, } + if !eventloop.watch_fd(loop, &server.watcher) { delete_key(&state.net_servers, server.id) jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)on_connection) linux.close(sfd) free(server) // the deferred ctx-free (listen_ok still false) releases server.tls_ctx - if g_multi_worker do net_startup_failed() - if exception != nil do exception^ = make_js_error(ctx, "net.listen: could not register listener with the event loop") + + if g_multi_worker { + net_startup_failed() + } + + if exception != + nil {exception^ = make_js_error(ctx, "net.listen: could not register listener with the event loop")} + return jsc.JSValueMakeUndefined(ctx) } + listen_ok = true // success: the Net_Server now owns tls_ctx; the defer no-ops return jsc.JSValueMakeNumber(ctx, f64(server.id)) } @@ -364,13 +443,22 @@ net_listen_cb :: proc "c" ( net_accept_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { context = runtime.default_context() // allocate Net_Connection on the heap net_maybe_free frees with server := cast(^Net_Server)user_data - if server == nil || server.closing do return + + if server == nil || server.closing { + return + } + state := get_state_from_ctx(server.ctx) - if state == nil do return + + if state == nil { + return + } + for { addr: linux.Sock_Addr_In cfd, accept_err := linux.accept(linux.Fd(server.fd), &addr, {.NONBLOCK}) - if accept_err != .NONE do break // EAGAIN (drained) or a transient error — stop this round + + if accept_err != .NONE {break} // EAGAIN (drained) or a transient error — stop this round // TCP_NODELAY: disable Nagle so small request/response exchanges aren't stalled by // the ~40 ms Nagle + delayed-ACK interaction (the dominant cost on a keep-alive @@ -395,6 +483,7 @@ net_accept_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { net_close_conn(conn, true) // SSL/BIO alloc failed — drop this conn (no JS yet) continue } + conn.handshake_timer = eventloop.set_timeout( loop, net_tls_handshake_timeout, @@ -405,7 +494,8 @@ net_accept_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { cid := jsc.JSValueMakeNumber(server.ctx, f64(conn.id)) net_emit(server.ctx, server.on_connection, &cid, 1) - if server.closing do break // a 'connection' handler closed the server + + if server.closing {break} // a 'connection' handler closed the server } } @@ -415,9 +505,17 @@ net_accept_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { net_tls_handshake_timeout :: proc(loop: ^eventloop.Loop, user_data: rawptr) { context = runtime.default_context() conn := cast(^Net_Connection)user_data - if conn == nil do return + + if conn == nil { + return + } + conn.handshake_timer = 0 - if conn.closing || !conn.tls_handshaking do return + + if conn.closing || !conn.tls_handshaking { + return + } + net_emit_error(conn, "tls handshake timeout") net_close_conn(conn, true) } @@ -455,7 +553,11 @@ net_connect_errno_name :: proc(errno: i32) -> string { net_connect_io_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { context = runtime.default_context() conn := cast(^Net_Connection)user_data - if conn == nil || conn.closing do return + + if conn == nil || conn.closing { + return + } + eventloop.unwatch_fd(loop, &conn.watcher) soerr: i32 = 0 @@ -463,6 +565,7 @@ net_connect_io_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // POINTEE type (a core:sys/linux quirk in this Odin build), so ^i32 never // matches it. _, _ = linux.getsockopt_base(linux.Fd(conn.fd), cast(int)linux.SOL_SOCKET, linux.Socket_Option.ERROR, &soerr) + if soerr == 0 { fn := conn.on_connect conn.on_connect = nil @@ -470,6 +573,7 @@ net_connect_io_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { net_unprotect(conn.ctx, fn) return } + net_emit_error(conn, fmt.tprintf("connect %s %s", net_connect_errno_name(soerr), conn.connect_label)) net_close_conn(conn, true) } @@ -490,32 +594,49 @@ net_connect_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 4 { - if exception != nil do exception^ = make_js_error(ctx, "net.connect requires (port, host, onConnected, onError)") + if exception != + nil {exception^ = make_js_error(ctx, "net.connect requires (port, host, onConnected, onError)")} + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] port := int(jsc.JSValueToNumber(ctx, args[0], nil)) host, host_alloc := jsc_value_to_string_or_default(ctx, args[1]) - defer if host_alloc do delete(host, context.allocator) + defer if host_alloc { + delete(host, context.allocator) + } on_connected := callback_arg(ctx, args[2]) on_error := callback_arg(ctx, args[3]) + if on_connected == nil || on_error == nil { - if exception != nil do exception^ = make_js_error(ctx, "net.connect: onConnected and onError must be functions") + if exception != nil { + exception^ = make_js_error(ctx, "net.connect: onConnected and onError must be functions") + } + return jsc.JSValueMakeUndefined(ctx) } + loop := get_loop_from_ctx(ctx) state := get_state_from_ctx(ctx) + if loop == nil || state == nil { - if exception != nil do exception^ = make_js_error(ctx, "net: no event loop is bound to this context") + if exception != nil { + exception^ = make_js_error(ctx, "net: no event loop is bound to this context") + } + return jsc.JSValueMakeUndefined(ctx) } // Same policy as net.listen: numeric IPv4 or "localhost" only — never fall // back to a wildcard or a resolver silently. ip4 := net.IP4_Address{127, 0, 0, 1} + if len(host) > 0 { resolved := false + if parsed := net.parse_address(host); parsed != nil { #partial switch a in parsed { case net.IP4_Address: @@ -525,17 +646,25 @@ net_connect_cb :: proc "c" ( } else if host == "localhost" { resolved = true } + if !resolved { - if exception != nil do exception^ = make_js_error(ctx, "net.connect: unsupported host (only numeric IPv4 and 'localhost' are supported)") + if exception != + nil {exception^ = make_js_error(ctx, "net.connect: unsupported host (only numeric IPv4 and 'localhost' are supported)")} + return jsc.JSValueMakeUndefined(ctx) } } cfd, sock_err := linux.socket(.INET, .STREAM, {.NONBLOCK}, .TCP) + if sock_err != .NONE { - if exception != nil do exception^ = make_js_error(ctx, "net.connect: could not create socket") + if exception != nil { + exception^ = make_js_error(ctx, "net.connect: could not create socket") + } + return jsc.JSValueMakeUndefined(ctx) } + nodelay: i32 = 1 _ = linux.setsockopt(cfd, linux.SOL_TCP, linux.Socket_TCP_Option.NODELAY, &nodelay) @@ -562,23 +691,27 @@ net_connect_cb :: proc "c" ( // can connect synchronously) still resolves through the writability watcher // so JS always receives onConnected AFTER it has the connection id. conn_err := linux.connect(cfd, &addr) + if conn_err != .NONE && conn_err != .EINPROGRESS && conn_err != .EAGAIN { // Synchronous failure (e.g. ENETUNREACH). The error must still be // delivered asynchronously — JS attaches listeners after this returns — // so leave delivery to the watcher: a failed socket polls writable with // SO_ERROR set. If even the watcher can't register, fall through below. } + conn.watcher = eventloop.IO_Watcher { fd = conn.fd, mode = .Write, callback = net_connect_io_cb, user_data = conn, } + if !eventloop.watch_fd(loop, &conn.watcher) { net_emit_error(conn, "net.connect: could not register connection with the event loop") net_close_conn(conn, true) return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeNumber(ctx, f64(conn.id)) } @@ -596,16 +729,27 @@ net_start_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 5 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 5 { + return jsc.JSValueMakeUndefined(ctx) + } + args := arguments[:int(argument_count)] conn := net_get_conn(ctx, args[0]) - if conn == nil || conn.closing do return jsc.JSValueMakeUndefined(ctx) + + if conn == nil || conn.closing { + return jsc.JSValueMakeUndefined(ctx) + } conn.on_data = callback_arg(ctx, args[1]) conn.on_end = callback_arg(ctx, args[2]) conn.on_close = callback_arg(ctx, args[3]) conn.on_error = callback_arg(ctx, args[4]) - if argument_count >= 6 do conn.on_drain = callback_arg(ctx, args[5]) + + if argument_count >= 6 { + conn.on_drain = callback_arg(ctx, args[5]) + } + net_protect(ctx, conn.on_data) net_protect(ctx, conn.on_end) net_protect(ctx, conn.on_close) @@ -620,6 +764,7 @@ net_start_cb :: proc "c" ( if !net_force_readiness() && eventloop.proactor_available(conn.loop) { if eventloop.bufring_available(conn.loop) { id := eventloop.submit_recv_ring(conn.loop, conn.fd, net_recv_ring_complete, on_op_dispose, conn) + if id != eventloop.OP_ID_INVALID { conn.io_mode = .ProactorRing // no recv_buf — reads draw from the shared ring conn.recv_op = id @@ -627,14 +772,17 @@ net_start_cb :: proc "c" ( return jsc.JSValueMakeUndefined(ctx) } } + conn.recv_buf = make([]byte, NET_PROACTOR_RECV, context.allocator) id := eventloop.submit_recv(conn.loop, conn.fd, conn.recv_buf, on_recv_complete, on_op_dispose, conn) + if id != eventloop.OP_ID_INVALID { conn.io_mode = .Proactor conn.recv_op = id conn.inflight += 1 return jsc.JSValueMakeUndefined(ctx) } + delete(conn.recv_buf, context.allocator) conn.recv_buf = nil } @@ -646,6 +794,7 @@ net_start_cb :: proc "c" ( callback = conn_read_cb, user_data = conn, } + // If the watcher can't be registered (loop resource exhaustion), the conn has an open fd and // protected handlers but no I/O — tear it down rather than strand it. (Rare; the handlers are // already registered, so 'close' still reports the failure to a listener attached this tick.) @@ -653,6 +802,7 @@ net_start_cb :: proc "c" ( net_emit_error(conn, "could not register connection with the event loop") net_close_conn(conn, true) } + return jsc.JSValueMakeUndefined(ctx) } @@ -670,6 +820,7 @@ net_force_readiness :: proc() -> bool { if net_force_readiness_state == .Unknown { net_force_readiness_state = os.get_env("LAVA_NET_FORCE_READINESS", context.temp_allocator) != "" ? .Yes : .No } + return net_force_readiness_state == .Yes } @@ -687,21 +838,32 @@ net_force_readiness :: proc() -> bool { // (closing/EOF, a recv already in flight, or write-backpressured) or the submit failed (it then // closes the conn — and `conn` may already be freed, so the caller must NOT touch it after a false). net_maybe_arm_recv :: proc(conn: ^Net_Connection) -> bool { - if conn.closing || conn.read_done do return false - if conn.recv_op != eventloop.OP_ID_INVALID do return false // a recv is already in flight + if conn.closing || conn.read_done { + return false + } + + if conn.recv_op != eventloop.OP_ID_INVALID {return false} // a recv is already in flight + // A 'drain' is owed (write() returned backpressure): keep reads paused until it fires — Node's // input-paused-until-'drain' semantics. This is the SINGLE gate for every re-arm path (3b §7): it // covers the SEND_ZC result→notif window (buffered drops on the result but 'drain' waits for the // notif) and also tightens 2a/1b — reads no longer resume on a partial drain (buffered < HWM) // before 'drain'. net_proactor_on_drained clears want_drain BEFORE re-arming, so this never deadlocks. - if conn.want_drain do return false + if conn.want_drain { + return false + } + // Defensive HWM backstop. With the want_drain unification above this is effectively redundant — // any write that crosses HWM sets want_drain (cleared only on a full drain), so buffered >= HWM // implies want_drain and the gate above already returned. Kept as a cheap local guard (no struct // state — it used to be a read_paused field, which created a misleading "second backpressure // mechanism"); it never independently pauses in proactor mode today. - if net_proactor_buffered(conn) >= NET_WRITE_HWM do return false + if net_proactor_buffered(conn) >= NET_WRITE_HWM { + return false + } + id: eventloop.Op_ID + if conn.io_mode == .ProactorRing { // Shared ring: no per-conn buffer; the kernel picks one at completion (net_recv_ring_complete). id = eventloop.submit_recv_ring(conn.loop, conn.fd, net_recv_ring_complete, on_op_dispose, conn) @@ -713,11 +875,13 @@ net_maybe_arm_recv :: proc(conn: ^Net_Connection) -> bool { } else { id = eventloop.submit_recv(conn.loop, conn.fd, conn.recv_buf, on_recv_complete, on_op_dispose, conn) } + if id == eventloop.OP_ID_INVALID { net_emit_error(conn, "read submit failed") net_close_conn(conn, true) return false } + conn.recv_op = id conn.inflight += 1 return true @@ -740,6 +904,7 @@ net_recv_ring_complete :: proc( ) { context = runtime.default_context() conn := cast(^Net_Connection)user_data + if !more { conn.recv_op = eventloop.OP_ID_INVALID // terminal: this op is finished conn.recv_cancel_pending = false // any backpressure cancel for this op is now consumed @@ -749,6 +914,7 @@ net_recv_ring_complete :: proc( // For TLS, feed ciphertext into the state machine here (it copies into rbio and emits decrypted // plaintext itself), leaving arg nil so the plaintext-delivery step below is skipped. arg: jsc.JSValueRef = nil + if has_buf && res > 0 && !conn.closing { if src := eventloop.recv_ring_buf(loop, bid, int(res)); src != nil { if conn.tls { @@ -760,23 +926,34 @@ net_recv_ring_complete :: proc( } } } + // (2) recycle UNCONDITIONALLY for any buffer-carrying CQE (incl. a terminal one), then refill. if has_buf { eventloop.recv_ring_recycle(loop, bid) - if state := get_state_from_ctx(conn.ctx); state != nil do net_refill_starved(state) + + if state := get_state_from_ctx(conn.ctx); state != nil { + net_refill_starved(state) + } } + // (3) deliver / classify. fatal := false + if !conn.closing { if res > 0 { - if arg != nil do net_emit(conn.ctx, conn.on_data, &arg, 1) + if arg != nil { + net_emit(conn.ctx, conn.on_data, &arg, 1) + } } else if res == 0 { // On a MULTISHOT ring recv the op stays armed across CQEs, so a graceful TLS close arrives // as TWO completions — the close_notify (res>0, decrypted to a clean SSL EOF inside // tls_server_on_ciphertext, which already set read_done + fired 'end') and then the FIN // (res==0, here). Guard on read_done so the FIN does not fire a SECOND 'end'. A plaintext // half-close reaches res==0 only once, so the guard is a no-op there. - if !conn.read_done do net_emit(conn.ctx, conn.on_end, nil, 0) + if !conn.read_done { + net_emit(conn.ctx, conn.on_end, nil, 0) + } + conn.read_done = true // EOF (always terminal — F_MORE clear) } else if res == -i32(linux.Errno.EINVAL) && conn.recv_multishot { // This op was submitted MULTISHOT and the kernel rejected it (has buffer rings but not @@ -803,6 +980,7 @@ net_recv_ring_complete :: proc( net_maybe_pause_multishot(conn) return } + // TERMINAL CQE: re-arm (unless EOF/fatal/closing — net_maybe_arm_recv also no-ops while paused), // then drop the op's in-flight count LAST (reentrant destroy() inside a handler stays safe). if !fatal && !conn.closing && !conn.read_done { @@ -817,6 +995,7 @@ net_recv_ring_complete :: proc( net_maybe_arm_recv(conn) } } + net_op_finished(conn) } @@ -830,9 +1009,18 @@ net_recv_ring_complete :: proc( // cleared on the op's terminal CQE (net_recv_ring_complete) — and per-op (net_maybe_arm_recv), so a // momentarily-full SQ that dropped the cancel is retried on the next crossing. net_maybe_pause_multishot :: proc(conn: ^Net_Connection) { - if conn.io_mode != .ProactorRing || conn.closing do return - if conn.recv_op == eventloop.OP_ID_INVALID || conn.recv_cancel_pending do return - if !eventloop.recv_ring_multishot(conn.loop) do return + if conn.io_mode != .ProactorRing || conn.closing { + return + } + + if conn.recv_op == eventloop.OP_ID_INVALID || conn.recv_cancel_pending { + return + } + + if !eventloop.recv_ring_multishot(conn.loop) { + return + } + if net_proactor_buffered(conn) >= NET_WRITE_HWM { conn.recv_cancel_pending = eventloop.cancel_op(conn.loop, conn.recv_op) } @@ -851,28 +1039,40 @@ NET_RECV_CREDIT_MAX :: 256 net_starved_enqueue :: proc(state: ^Runtime_State, conn: ^Net_Connection) { conn.starved_next = nil conn.starved_prev = state.net_starved_tail - if state.net_starved_tail != nil do state.net_starved_tail.starved_next = conn - else do state.net_starved_head = conn + + if state.net_starved_tail != nil {state.net_starved_tail.starved_next = conn} else { + state.net_starved_head = conn + } + state.net_starved_tail = conn } @(private = "file") net_starved_dequeue :: proc(state: ^Runtime_State) -> ^Net_Connection { conn := state.net_starved_head - if conn == nil do return nil + + if conn == nil { + return nil + } + state.net_starved_head = conn.starved_next - if state.net_starved_head != nil do state.net_starved_head.starved_prev = nil - else do state.net_starved_tail = nil + + if state.net_starved_head != nil {state.net_starved_head.starved_prev = nil} else { + state.net_starved_tail = nil + } + conn.starved_next, conn.starved_prev = nil, nil return conn } @(private = "file") net_starved_unlink :: proc(state: ^Runtime_State, conn: ^Net_Connection) { - if conn.starved_prev != nil do conn.starved_prev.starved_next = conn.starved_next - else do state.net_starved_head = conn.starved_next - if conn.starved_next != nil do conn.starved_next.starved_prev = conn.starved_prev - else do state.net_starved_tail = conn.starved_prev + if conn.starved_prev != + nil {conn.starved_prev.starved_next = conn.starved_next} else {state.net_starved_head = conn.starved_next} + + if conn.starved_next != + nil {conn.starved_next.starved_prev = conn.starved_prev} else {state.net_starved_tail = conn.starved_prev} + conn.starved_next, conn.starved_prev = nil, nil } @@ -882,19 +1082,30 @@ net_starved_unlink :: proc(state: ^Runtime_State, conn: ^Net_Connection) { // the lost-wakeup; otherwise park on the starved FIFO and take a loop-liveness ref (async_begin) so // the loop cannot exit with our peer's data unread — a future recycle re-arms us. net_park_or_rearm :: proc(conn: ^Net_Connection) { - if conn.closing || conn.read_done do return + if conn.closing || conn.read_done { + return + } + // A 'drain' is owed → net_maybe_arm_recv would no-op (it gates on want_drain), so spending a recv // credit here would buy nothing and defer another parked conn's re-arm by a recycle. The drain // transition (net_proactor_on_drained) re-arms anyway. Mirrors net_refill_starved's want_drain policy. - if conn.want_drain do return + if conn.want_drain { + return + } + state := get_state_from_ctx(conn.ctx) - if state == nil do return + + if state == nil { + return + } + if state.net_recv_credits > 0 { state.net_recv_credits -= 1 net_maybe_arm_recv(conn) return } - if conn.recv_starved do return // no duplicate insertion + + if conn.recv_starved {return} // no duplicate insertion conn.recv_starved = true net_starved_enqueue(state, conn) eventloop.async_begin(conn.loop) @@ -911,19 +1122,30 @@ net_park_or_rearm :: proc(conn: ^Net_Connection) { net_refill_starved :: proc(state: ^Runtime_State) { for { conn := net_starved_dequeue(state) - if conn == nil do break + + if conn == nil { + break + } + conn.recv_starved = false eventloop.async_cancel(conn.loop) // drop the parked liveness ref - if net_maybe_arm_recv(conn) do return // armed → this conn consumes the wakeup + + if net_maybe_arm_recv(conn) {return} // armed → this conn consumes the wakeup // else couldn't arm (closing/EOF/backpressured/submit-failed) — try the next parked conn } - if state.net_recv_credits < NET_RECV_CREDIT_MAX do state.net_recv_credits += 1 + + if state.net_recv_credits < NET_RECV_CREDIT_MAX { + state.net_recv_credits += 1 + } } // net_unpark removes a conn from the starved FIFO before it is freed (lifetime safety: a later // recycle must never walk a freed conn), releasing its liveness ref. O(1). net_unpark :: proc(state: ^Runtime_State, conn: ^Net_Connection) { - if !conn.recv_starved do return + if !conn.recv_starved { + return + } + conn.recv_starved = false eventloop.async_cancel(conn.loop) net_starved_unlink(state, conn) @@ -936,14 +1158,19 @@ on_recv_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32) { context = runtime.default_context() conn := cast(^Net_Connection)user_data conn.recv_op = eventloop.OP_ID_INVALID + if !conn.closing { if res > 0 { n := int(res) + if conn.tls { // Feed ciphertext to the TLS state machine (it copies into rbio, drives the // handshake or decrypt loop, and emits decrypted plaintext as on_data), then re-arm. tls_server_on_ciphertext(conn, conn.recv_buf[:n]) - if !conn.closing do net_maybe_arm_recv(conn) + + if !conn.closing { + net_maybe_arm_recv(conn) + } } else { // Copy out of the reused landing buffer into a JSC-owned Uint8Array (no-copy handoff // frees copy_buf on GC). The landing buffer must NOT be handed to JSC — it is reused. @@ -956,7 +1183,10 @@ on_recv_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32) { } else if res == 0 { // Single-shot can't double-fire (net_maybe_arm_recv gates on read_done after a TLS EOF), // but guard for consistency with the ring path: never fire 'end' twice. - if !conn.read_done do net_emit(conn.ctx, conn.on_end, nil, 0) + if !conn.read_done { + net_emit(conn.ctx, conn.on_end, nil, 0) + } + conn.read_done = true // half-close: never re-arm } else if res == -i32(linux.Errno.EINTR) || res == -i32(linux.Errno.EAGAIN) { net_maybe_arm_recv(conn) // transient — a fresh submit (kernel re-polls), not a spin @@ -964,8 +1194,10 @@ on_recv_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32) { net_emit_error(conn, "read error") net_close_conn(conn, true) } + // -ECANCELED: our own teardown cancel; no error, just let op_finished reclaim. } + net_op_finished(conn) } @@ -983,12 +1215,19 @@ g_zc_ok_reported: bool @(private = "file") g_zc_engaged_reported: bool net_zc_stats_note :: proc(loop: ^eventloop.Loop, use_zc: bool) { - if g_zc_ok_reported && (g_zc_engaged_reported || !use_zc) do return - if os.get_env("LAVA_ZC_STATS", context.temp_allocator) == "" do return + if g_zc_ok_reported && (g_zc_engaged_reported || !use_zc) { + return + } + + if os.get_env("LAVA_ZC_STATS", context.temp_allocator) == "" { + return + } + if !g_zc_ok_reported { g_zc_ok_reported = true os.write_string(os.stderr, eventloop.send_zc_ok(loop) ? "LAVA_ZC: zc_ok=1\n" : "LAVA_ZC: zc_ok=0\n") } + if use_zc && !g_zc_engaged_reported { g_zc_engaged_reported = true os.write_string(os.stderr, "LAVA_ZC: SEND_ZC engaged\n") @@ -1015,16 +1254,19 @@ net_proactor_submit :: proc(conn: ^Net_Connection, force_plain := false) { conn.send_was_zc = use_zc net_zc_stats_note(conn.loop, use_zc) // M3: env-gated stderr evidence that the SEND_ZC path actually ran id: eventloop.Op_ID + if use_zc { id = eventloop.submit_send_zc(conn.loop, conn.fd, buf, net_send_zc_complete, on_op_dispose, conn) } else { id = eventloop.submit_send(conn.loop, conn.fd, buf, on_send_complete, on_op_dispose, conn) } + if id == eventloop.OP_ID_INVALID { net_emit_error(conn, "write submit failed") net_close_conn(conn, true) return } + conn.send_op = id conn.inflight += 1 } @@ -1032,9 +1274,16 @@ net_proactor_submit :: proc(conn: ^Net_Connection, force_plain := false) { // net_proactor_kick_send rotates pending_writes into active_send and submits, if no send is in // flight and there is data. Rotation (swap + clear) preserves each backing's allocator/capacity. net_proactor_kick_send :: proc(conn: ^Net_Connection) { - if conn.closing do return - if conn.send_op != eventloop.OP_ID_INVALID do return // a send is already in flight - if len(conn.pending_writes) == 0 do return + if conn.closing { + return + } + + if conn.send_op != eventloop.OP_ID_INVALID {return} // a send is already in flight + + if len(conn.pending_writes) == 0 { + return + } + conn.active_send, conn.pending_writes = conn.pending_writes, conn.active_send clear(&conn.pending_writes) conn.active_send_off = 0 @@ -1047,9 +1296,11 @@ on_send_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32) { context = runtime.default_context() conn := cast(^Net_Connection)user_data conn.send_op = eventloop.OP_ID_INVALID + if !conn.closing { if res > 0 { conn.active_send_off += int(res) + if conn.active_send_off < len(conn.active_send) { net_proactor_submit(conn) // partial send — re-submit the unsent tail } else if len(conn.pending_writes) > 0 { @@ -1069,6 +1320,7 @@ on_send_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32) { net_close_conn(conn, true) } } + net_op_finished(conn) } @@ -1082,13 +1334,17 @@ on_send_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32) { net_send_zc_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32, more: bool) { context = runtime.default_context() conn := cast(^Net_Connection)user_data + // INTERMEDIATE (result CQE): pages pinned, notif owed. RECORD ONLY, then return (INV-1) — never // finish/clear/free/submit/close here. off advances only on a non-negative result (INV-4); a // negative result is an errored-but-pinned send whose error is carried to the terminal. if more { conn.saw_result = true - if res >= 0 do conn.active_send_off += int(res) - else do conn.zc_err = res + + if res >= 0 {conn.active_send_off += int(res)} else { + conn.zc_err = res + } + return } @@ -1097,8 +1353,10 @@ net_send_zc_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32, // across any re-submit, so net_maybe_free can't transiently free the still-needed conn). saw := conn.saw_result conn.send_op = eventloop.OP_ID_INVALID + if !conn.closing { err: i32 = 0 + if saw { err = conn.zc_err // 0 if the result succeeded; <0 if it errored (ignore THIS notif's res — INV-3) } else if res > 0 { @@ -1106,7 +1364,9 @@ net_send_zc_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32, } else if res < 0 { err = res // single-CQE pre-transmission error } + if err < 0 { // off untouched on any error (INV-4) → a re-send is the exact unsent tail + if err == -i32(linux.Errno.EINVAL) && conn.send_was_zc { eventloop.disable_zc(loop) // missing/rejected opcode is a kernel-wide fact: latch ZC off loop-wide net_proactor_submit(conn, force_plain = true) // re-send PLAIN @@ -1122,6 +1382,7 @@ net_send_zc_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32, net_emit_error(conn, "write error") net_close_conn(conn, true) // fatal (EPIPE, …) } + // -ECANCELED: benign (a non-closing cancel doesn't occur on the send path; closing is guarded) } else if !saw && res == 0 { net_emit_error(conn, "write stalled") // zero-byte stall (plain-path parity) @@ -1136,6 +1397,7 @@ net_send_zc_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32, net_proactor_on_drained(conn) } } + conn.saw_result = false // redundant defensive zero — net_proactor_submit is the canonical per-op reset; conn.zc_err = 0 // nothing reads these on the closing/free path, but keep them clean for the next op net_op_finished(conn) // LAST, unconditional @@ -1146,19 +1408,27 @@ net_send_zc_complete :: proc(loop: ^eventloop.Loop, user_data: rawptr, res: i32, // re-arm reads / close only against the FRESH state. net_proactor_on_drained :: proc(conn: ^Net_Connection) { resumed := conn.want_drain + if conn.want_drain { conn.want_drain = false net_emit(conn.ctx, conn.on_drain, nil, 0) } - if conn.closing do return // a 'drain' listener destroyed the socket + + if conn.closing {return} // a 'drain' listener destroyed the socket + // TLS: reads may have paused mid-decrypt with plaintext still buffered in the rbio; now that the // write drained, decrypt+emit that remainder before re-arming the recv (it lives in userspace, so // the recv re-arm alone would never deliver it). No-op if nothing is buffered. if conn.tls && resumed { tls_server_pump_reads(conn) - if conn.closing do return + + if conn.closing { + return + } } + net_maybe_arm_recv(conn) // recomputes read_paused from the (possibly new) buffered count + if conn.end_after_drain && conn.send_op == eventloop.OP_ID_INVALID && len(conn.pending_writes) == 0 { net_close_conn(conn, false) } @@ -1192,21 +1462,27 @@ net_zc_pinned_at_teardown :: proc(conn: ^Net_Connection) -> bool { // == 0 means no op remains to call it again). The fd is closed BEFORE 'close' is emitted, and the // conn is dropped from the registry before any JS runs so a reentrant destroy() can't re-enter. net_maybe_free :: proc(conn: ^Net_Connection) { - if !conn.closing || conn.inflight > 0 do return + if !conn.closing || conn.inflight > 0 { + return + } + // Pin the default heap: recv_buf/active_send/pending_writes are allocated under // runtime.default_context (the proc"c" entry points) and the conn under net_accept_cb's // (also default) context, so free them the same way regardless of the ambient context when // this runs (e.g. net_shutdown_active / an Op_Dispose during eventloop.destroy). context = runtime.default_context() linux.close(linux.Fd(conn.fd)) + if state := get_state_from_ctx(conn.ctx); state != nil { delete_key(&state.net_conns, conn.id) net_drain_check_complete(state, conn.loop) } + if !conn.silent_close { had := jsc.JSValueMakeBoolean(conn.ctx, b32(conn.had_error)) net_emit(conn.ctx, conn.on_close, &had, 1) } + net_unprotect(conn.ctx, conn.on_data) net_unprotect(conn.ctx, conn.on_end) net_unprotect(conn.ctx, conn.on_close) @@ -1215,6 +1491,7 @@ net_maybe_free :: proc(conn: ^Net_Connection) { net_unprotect(conn.ctx, conn.on_connect) // closed mid-connect: the success cb never fired delete(conn.connect_label) delete(conn.recv_buf) + // M1/M2 (kernel-side UAF): a SEND_ZC whose pages the kernel may STILL hold pinned — its notification // never fired, so we reached here via the eventloop.destroy dispose path (the disposer drove inflight // to 0), NOT the more=false terminal: send_op is still live and the last send was ZC. Closing the ring @@ -1229,6 +1506,7 @@ net_maybe_free :: proc(conn: ^Net_Connection) { if !net_zc_pinned_at_teardown(conn) { delete(conn.active_send) } + delete(conn.pending_writes) // Free the TLS session (and, with it, both BIOs) + cancel any handshake timer. OUTSIDE the // ZC-pin guard above (which only forgoes active_send): the SSL is never kernel-pinned, so it @@ -1241,14 +1519,22 @@ net_maybe_free :: proc(conn: ^Net_Connection) { // shutdown(SHUT_RDWR) (cancel_op alone is best-effort), cancel for promptness, then maybe_free // (finalizes immediately if no op is in flight — e.g. after a peer EOF). had_error is sticky. net_close_conn_proactor :: proc(conn: ^Net_Connection, had_error: bool) { - if had_error do conn.had_error = true // sticky, BEFORE the idempotency guard - if conn.closing do return + if had_error {conn.had_error = true} // sticky, BEFORE the idempotency guard + + if conn.closing { + return + } + conn.closing = true + // Remove from the -ENOBUFS starved list FIRST (lifetime safety: a later recycle must never // re-arm/walk a conn that maybe_free is about to free). if conn.recv_starved { - if state := get_state_from_ctx(conn.ctx); state != nil do net_unpark(state, conn) + if state := get_state_from_ctx(conn.ctx); state != nil { + net_unpark(state, conn) + } } + linux.shutdown(linux.Fd(conn.fd), .RDWR) eventloop.cancel_op(conn.loop, conn.recv_op) eventloop.cancel_op(conn.loop, conn.send_op) @@ -1261,20 +1547,28 @@ net_close_conn_proactor :: proc(conn: ^Net_Connection, had_error: bool) { // if conn.closing — safe because net_close_conn defers the actual free. Loop thread. conn_read_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { conn := cast(^Net_Connection)user_data + // read_done guard: on a TLS conn the EOF is detected INSIDE the state machine (a close_notify // arrives as n>0 ciphertext, SSL_read → ZERO_RETURN → on_end), not via the n==0 branch below, so // without this guard the peer's subsequent FIN would re-enter here and fire 'end' a second time. - if conn == nil || conn.closing || conn.read_done do return + if conn == nil || conn.closing || conn.read_done { + return + } + buf: [NET_READ_CHUNK]byte for { n, recv_err := linux.recv(linux.Fd(conn.fd), buf[:], {}) - if recv_err == .EINTR do continue // interrupted by a signal — retry, not fatal - if recv_err == .EAGAIN do return // no more data buffered — wait for the next event + + if recv_err == .EINTR {continue} // interrupted by a signal — retry, not fatal + + if recv_err == .EAGAIN {return} // no more data buffered — wait for the next event + if recv_err != .NONE { net_emit_error(conn, "read error") net_close_conn(conn, true) return } + if n == 0 { // peer half-closed (read EOF) // Stop the read watcher (EOF is persistent — it would re-fire forever) and // fire 'end'. Do NOT close here: this is a true half-close. The peer is done @@ -1287,6 +1581,7 @@ conn_read_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { net_emit(conn.ctx, conn.on_end, nil, 0) return } + if conn.tls { // Feed ciphertext to the TLS state machine (decrypts + emits plaintext on_data, drains // any ciphertext via net_flush). Then honor the same closing/backpressure gates below. @@ -1299,14 +1594,17 @@ conn_read_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { arg := make_uint8_array(conn.ctx, copy_buf) net_emit(conn.ctx, conn.on_data, &arg, 1) } - if conn.closing do return // a data handler closed the socket + + if conn.closing {return} // a data handler closed the socket + if conn.read_done { // TLS close_notify surfaced as a clean EOF inside the state machine (on_end already // fired). Unwatch like the n==0 branch so the peer's FIN can't re-fire and double 'end'. eventloop.unwatch_fd(conn.loop, &conn.watcher) return } - if conn.writing do return // a data handler wrote and hit backpressure — pause reads + + if conn.writing {return} // a data handler wrote and hit backpressure — pause reads } } @@ -1323,10 +1621,17 @@ net_write_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return jsc.JSValueMakeBoolean(ctx, true) + + if argument_count < 2 { + return jsc.JSValueMakeBoolean(ctx, true) + } + args := arguments[:int(argument_count)] conn := net_get_conn(ctx, args[0]) - if conn == nil || conn.closing do return jsc.JSValueMakeBoolean(ctx, false) + + if conn == nil || conn.closing { + return jsc.JSValueMakeBoolean(ctx, false) + } if net_is_proactor(conn) { // Hold a lifetime reference for the call: net_proactor_kick_send can fail a submit and @@ -1334,25 +1639,34 @@ net_write_cb :: proc "c" ( // alive until we have read its state and computed the return (mirrors a completion's ref). conn.inflight += 1 defer net_op_finished(conn) + if conn.tls { // SSL_write the plaintext; tls_server_write drains the resulting ciphertext into // pending_writes and kicks the send. The backpressure gate below measures buffered // CIPHERTEXT (net_proactor_buffered), identical to the plaintext path. if view, ok := typed_array_view(ctx, args[1]); ok && len(view) > 0 { - if !tls_server_write(conn, view) do return jsc.JSValueMakeBoolean(ctx, false) + if !tls_server_write(conn, view) { + return jsc.JSValueMakeBoolean(ctx, false) + } } } else { if view, ok := typed_array_view(ctx, args[1]); ok && len(view) > 0 { append(&conn.pending_writes, ..view) } + net_proactor_kick_send(conn) } - if conn.closing do return jsc.JSValueMakeBoolean(ctx, false) + + if conn.closing { + return jsc.JSValueMakeBoolean(ctx, false) + } + if net_proactor_buffered(conn) >= NET_WRITE_HWM { conn.want_drain = true // backpressure (Node's write()==false); a 'drain' is owed net_maybe_pause_multishot(conn) // a write from outside on_data can backpressure too return jsc.JSValueMakeBoolean(ctx, false) } + return jsc.JSValueMakeBoolean(ctx, true) } @@ -1360,9 +1674,13 @@ net_write_cb :: proc "c" ( // SSL_write + pump (tls_pump_wbio drains ciphertext into write_queue and runs net_flush, // which sets conn.writing on backpressure). if view, ok := typed_array_view(ctx, args[1]); ok && len(view) > 0 { - if !tls_server_write(conn, view) do return jsc.JSValueMakeBoolean(ctx, false) + if !tls_server_write(conn, view) { + return jsc.JSValueMakeBoolean(ctx, false) + } } + backpressured := conn.writing + if backpressured { conn.want_drain = true } else if !conn.closing && !conn.read_done { @@ -1371,6 +1689,7 @@ net_write_cb :: proc "c" ( // drive the leftover (it's in userspace). No-op when nothing is buffered. tls_server_pump_reads(conn) } + return jsc.JSValueMakeBoolean(ctx, b32(!backpressured)) } @@ -1378,8 +1697,10 @@ net_write_cb :: proc "c" ( net_compact_write_queue(conn) // drop the sent prefix so backpressure doesn't retain dead bytes append(&conn.write_queue, ..view) } + backpressured := net_flush(conn) - if backpressured do conn.want_drain = true // owe a 'drain' once the queue empties + + if backpressured {conn.want_drain = true} // owe a 'drain' once the queue empties return jsc.JSValueMakeBoolean(ctx, b32(!backpressured)) } @@ -1387,7 +1708,10 @@ net_write_cb :: proc "c" ( // queue so sustained backpressure (repeated writes / TLS pumps while write_off > 0) doesn't retain // dead bytes until a full drain. copy is memmove-safe for the overlap; no-op when nothing was sent. net_compact_write_queue :: proc(conn: ^Net_Connection) { - if conn.write_off <= 0 do return + if conn.write_off <= 0 { + return + } + n := copy(conn.write_queue[:], conn.write_queue[conn.write_off:]) resize(&conn.write_queue, n) conn.write_off = 0 @@ -1402,44 +1726,65 @@ net_flush :: proc(conn: ^Net_Connection) -> (backpressured: bool) { // is released on full drain (clear below) or dropped when a new write arrives (net_write_cb). for conn.write_off < len(conn.write_queue) { sent, send_err := linux.send(linux.Fd(conn.fd), conn.write_queue[conn.write_off:], {.NOSIGNAL}) - if send_err == .EINTR do continue // interrupted by a signal — retry, not fatal + + if send_err == .EINTR {continue} // interrupted by a signal — retry, not fatal + if send_err == .EAGAIN { net_set_mode(conn, .Write) // wait for writability, then conn_write_cb drains return true } + if send_err != .NONE { net_emit_error(conn, "write error") net_close_conn(conn, true) return true } + if sent <= 0 { net_set_mode(conn, .Write) // no progress this time — wait for the next writable event return true } + conn.write_off += sent } clear(&conn.write_queue) // fully drained conn.write_off = 0 + // Drained. Restore read interest only if the read side is still open; after a read // EOF (read_done) the socket is write-only and about to close. - if conn.writing && !conn.read_done do net_set_mode(conn, .Read) + if conn.writing && !conn.read_done { + net_set_mode(conn, .Read) + } + // Fire the owed 'drain' (readiness parity with the proactor path) so a JS writer that // stopped on write()==false resumes. Reentrancy-safe: clear before emit (the listener may // write again — re-arming want_drain — or destroy()), then bail if it closed us. if conn.want_drain { conn.want_drain = false net_emit(conn.ctx, conn.on_drain, nil, 0) - if conn.closing do return false + + if conn.closing { + return false + } + } + + if conn.end_after_drain { + net_close_conn(conn, false) } - if conn.end_after_drain do net_close_conn(conn, false) + return false } // conn_write_cb fires when a backpressured socket becomes writable again. Loop thread. conn_write_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { conn := cast(^Net_Connection)user_data - if conn == nil || conn.closing do return + + if conn == nil || conn.closing { + return + } + net_flush(conn) + // Readiness TLS: once the write fully drains (reads resume — net_flush restored .Read, so // conn.writing is clear), decrypt+emit any plaintext that paused in the rbio under backpressure. // Done AFTER net_flush returns (not inside it) so the pump's on_data → write → net_flush is a @@ -1453,7 +1798,10 @@ conn_write_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // watches one direction at a time). Mirrors fetch_set_watch_mode: unwatch, retarget, // rewatch. Pausing reads while draining a blocked write is also correct backpressure. net_set_mode :: proc(conn: ^Net_Connection, mode: eventloop.Poll_Mode) { - if conn.closing do return + if conn.closing { + return + } + eventloop.unwatch_fd(conn.loop, &conn.watcher) conn.watcher.mode = mode conn.watcher.callback = mode == .Write ? conn_write_cb : conn_read_cb @@ -1472,30 +1820,50 @@ net_end_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + conn := net_get_conn(ctx, arguments[0]) - if conn == nil || conn.closing do return jsc.JSValueMakeUndefined(ctx) + + if conn == nil || conn.closing { + return jsc.JSValueMakeUndefined(ctx) + } + conn.end_after_drain = true + if net_is_proactor(conn) { // Guarded like net_write_cb: kick / close below may free the conn otherwise. conn.inflight += 1 defer net_op_finished(conn) + // TLS: queue a close_notify (SSL_shutdown → pump) before draining; the close_notify's send // keeps send_op live so the close-if-empty check below defers to on_send_complete. A // still-handshaking conn has no session — begin_close no-ops and we hard-close immediately. - if conn.tls do tls_server_begin_close(conn) - else do net_proactor_kick_send(conn) + if conn.tls {tls_server_begin_close(conn)} else { + net_proactor_kick_send(conn) + } + // Nothing left to drain → close now; otherwise on_send_complete closes once drained. if !conn.closing && conn.send_op == eventloop.OP_ID_INVALID && len(conn.pending_writes) == 0 { net_close_conn(conn, false) } + return jsc.JSValueMakeUndefined(ctx) } + // Readiness: begin_close queues a close_notify (a no-op while still handshaking); net_flush then // drains whatever is queued and, on full drain, honors end_after_drain — so a plain conn, a // handshaking TLS conn (nothing to send → closes now), and an established TLS conn all converge. - if conn.tls do tls_server_begin_close(conn) - if !conn.closing do net_flush(conn) + if conn.tls { + tls_server_begin_close(conn) + } + + if !conn.closing { + net_flush(conn) + } + return jsc.JSValueMakeUndefined(ctx) } @@ -1509,8 +1877,15 @@ net_close_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) - if conn := net_get_conn(ctx, arguments[0]); conn != nil do net_close_conn(conn, false) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + + if conn := net_get_conn(ctx, arguments[0]); conn != nil { + net_close_conn(conn, false) + } + return jsc.JSValueMakeUndefined(ctx) } @@ -1525,8 +1900,15 @@ net_close_server_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) - if server := net_get_server(ctx, arguments[0]); server != nil do net_close_server(server) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + + if server := net_get_server(ctx, arguments[0]); server != nil { + net_close_server(server) + } + return jsc.JSValueMakeUndefined(ctx) } @@ -1540,11 +1922,23 @@ net_server_port_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 0) + } + server := net_get_server(ctx, arguments[0]) - if server == nil do return jsc.JSValueMakeNumber(ctx, 0) + + if server == nil { + return jsc.JSValueMakeNumber(ctx, 0) + } + addr: linux.Sock_Addr_Any - if linux.getsockname(linux.Fd(server.fd), &addr) != .NONE do return jsc.JSValueMakeNumber(ctx, 0) + + if linux.getsockname(linux.Fd(server.fd), &addr) != .NONE { + return jsc.JSValueMakeNumber(ctx, 0) + } + return jsc.JSValueMakeNumber(ctx, f64(u16(addr.port))) } @@ -1555,12 +1949,19 @@ net_server_port_cb :: proc "c" ( // next tick (so an in-flight read/write callback can still read conn.closing safely). // Idempotent. Loop thread. net_close_conn :: proc(conn: ^Net_Connection, had_error: bool) { - if conn == nil do return + if conn == nil { + return + } + if net_is_proactor(conn) { net_close_conn_proactor(conn, had_error) return } - if conn.closing do return + + if conn.closing { + return + } + conn.closing = true eventloop.unwatch_fd(conn.loop, &conn.watcher) // idempotent if never armed linux.close(linux.Fd(conn.fd)) @@ -1580,6 +1981,7 @@ net_close_conn :: proc(conn: ^Net_Connection, had_error: bool) { delete_key(&state.net_conns, conn.id) net_drain_check_complete(state, conn.loop) // readiness path: drain promptly on the last conn close } + eventloop.async_begin(conn.loop) eventloop.post_async(conn.loop, net_conn_free_cb, conn) } @@ -1597,12 +1999,16 @@ net_conn_free_cb :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // handler may close the server from inside net_accept_cb). Existing connections are left // running, exactly like Node's server.close(). net_close_server :: proc(server: ^Net_Server) { - if server == nil || server.closing do return + if server == nil || server.closing { + return + } + server.closing = true eventloop.unwatch_fd(server.loop, &server.watcher) linux.close(linux.Fd(server.fd)) net_unprotect(server.ctx, server.on_connection) server.on_connection = nil + // Free the per-listener SSL_CTX (unlike the client's process-global g_tls_ctx). Existing TLS // connections keep their own SSL (per-conn, freed at their own teardown); SSL_CTX is refcounted, // so freeing it here while conns still hold SSL_new references is safe. @@ -1611,7 +2017,11 @@ net_close_server :: proc(server: ^Net_Server) { server.tls = false server.tls_ctx = nil } - if state := get_state_from_ctx(server.ctx); state != nil do delete_key(&state.net_servers, server.id) + + if state := get_state_from_ctx(server.ctx); state != nil { + delete_key(&state.net_servers, server.id) + } + eventloop.async_begin(server.loop) eventloop.post_async(server.loop, net_server_free_cb, server) } @@ -1638,25 +2048,32 @@ NET_DRAIN_TIMEOUT_MS :: 10_000 net_drain_begin :: proc(loop: ^eventloop.Loop, user_data: rawptr) { context = runtime.default_context() state := cast(^Runtime_State)user_data + if state == nil { eventloop.begin_force_exit(loop) return } + state.draining = true // Stop accepting: unwatch + close each listener fd. Leave the Net_Server in the map — the final // net_shutdown_active frees it (it skips already-closing servers, so no double close). for _, server in state.net_servers { - if server.closing do continue + if server.closing { + continue + } + server.closing = true eventloop.unwatch_fd(server.loop, &server.watcher) linux.close(linux.Fd(server.fd)) net_unprotect(server.ctx, server.on_connection) } + // Nothing in flight -> exit now; otherwise let connections drain, bounded by the timeout. if len(state.net_conns) == 0 { eventloop.begin_force_exit(loop) return } + state.drain_timer = eventloop.set_timeout(loop, net_drain_timeout, NET_DRAIN_TIMEOUT_MS, state) } @@ -1666,23 +2083,31 @@ net_drain_begin :: proc(loop: ^eventloop.Loop, user_data: rawptr) { // net_close_conn (readiness) — so a readiness-mode server drains promptly instead of always waiting the // full timeout. loop outlives the connection, so it is safe to touch here. net_drain_check_complete :: proc(state: ^Runtime_State, loop: ^eventloop.Loop) { - if state == nil || !state.draining || len(state.net_conns) != 0 do return + if state == nil || !state.draining || len(state.net_conns) != 0 { + return + } + if state.drain_timer != 0 { eventloop.clear_timeout(loop, state.drain_timer) state.drain_timer = 0 } + eventloop.begin_force_exit(loop) } @(private = "file") net_drain_timeout :: proc(loop: ^eventloop.Loop, user_data: rawptr) { state := cast(^Runtime_State)user_data - if state != nil do state.drain_timer = 0 // fired; nothing left to cancel + + if state != nil {state.drain_timer = 0} // fired; nothing left to cancel eventloop.begin_force_exit(loop) } net_shutdown_active :: proc(state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + context = runtime.default_context() // alloc/free conns + buffers on the default heap (see net_maybe_free) // Iterated DIRECTLY, not through a snapshot. net_maybe_free deletes the freed // proactor conn from net_conns, and Odin documents that as safe: @@ -1705,10 +2130,12 @@ net_shutdown_active :: proc(state: ^Runtime_State) { net_unprotect(conn.ctx, conn.on_error) net_unprotect(conn.ctx, conn.on_drain) conn.on_data, conn.on_end, conn.on_close, conn.on_error, conn.on_drain = nil, nil, nil, nil, nil + if conn.recv_starved { conn.recv_starved = false // the whole starved list is cleared after this loop eventloop.async_cancel(conn.loop) // balance the parked liveness ref } + if !conn.closing { // Not yet closing: wake any op pending on an idle peer + cancel for promptness. conn.closing = true @@ -1716,12 +2143,14 @@ net_shutdown_active :: proc(state: ^Runtime_State) { eventloop.cancel_op(conn.loop, conn.recv_op) eventloop.cancel_op(conn.loop, conn.send_op) } + // Cancel an armed handshake timer NOW (loop still alive) so a deferred Op_Dispose free // during eventloop.destroy doesn't clear_timeout against a torn-down timer heap. if conn.handshake_timer != 0 { eventloop.clear_timeout(conn.loop, conn.handshake_timer) conn.handshake_timer = 0 } + // Zero-inflight (e.g. post-EOF, no op/disposer) finalizes now; a live-op conn is a // no-op here and is freed by its Op_Dispose during eventloop.destroy, which the // deferred teardown runs BEFORE destroy_runtime_state deletes net_conns (so the @@ -1729,7 +2158,8 @@ net_shutdown_active :: proc(state: ^Runtime_State) { net_maybe_free(conn) continue } - if conn.closing do continue // readiness: already torn down; its deferred free is dropped at destroy + + if conn.closing {continue} // readiness: already torn down; its deferred free is dropped at destroy conn.closing = true eventloop.unwatch_fd(conn.loop, &conn.watcher) linux.close(linux.Fd(conn.fd)) @@ -1742,6 +2172,7 @@ net_shutdown_active :: proc(state: ^Runtime_State) { tls_server_free_conn(conn) // free SSL/BIOs + cancel handshake timer (no-op on a plaintext conn) free(conn) } + clear(&state.net_conns) // live-op proactor conns (if any) are freed by their Op_Dispose state.net_starved_head, state.net_starved_tail = nil, nil // FIFO emptied (conns freed above / by disposer) for _, server in state.net_servers { @@ -1751,10 +2182,14 @@ net_shutdown_active :: proc(state: ^Runtime_State) { tls_server_ctx_free(cast(SSL_CTX)server.tls_ctx) server.tls_ctx = nil } + // COUPLING: net_drain_begin (graceful drain) may already have unwatched + closed this listener // and set closing=true; skip it here to avoid a double unwatch/close. The two functions agree on // this flag — a listener is unwatched+closed exactly once, by whichever runs first. - if server.closing do continue + if server.closing { + continue + } + server.closing = true eventloop.unwatch_fd(server.loop, &server.watcher) linux.close(linux.Fd(server.fd)) @@ -1766,13 +2201,18 @@ net_shutdown_active :: proc(state: ^Runtime_State) { // net_destroy_state releases the registry backing once everything is shut down. net_destroy_state :: proc(state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + net_shutdown_active(state) delete(state.net_servers) delete(state.net_conns) // Free any TLS contexts still parked in the registry (createServer without a successful listen); // listened ones moved to their Net_Server and were freed in net_shutdown_active. - for _, ctx_ptr in state.tls_server_ctxs do tls_server_ctx_free(cast(SSL_CTX)ctx_ptr) + for _, ctx_ptr in state.tls_server_ctxs { + tls_server_ctx_free(cast(SSL_CTX)ctx_ptr) + } delete(state.tls_server_ctxs) // net_starved is an intrusive list (head/tail pointers, no backing allocation) — nothing to free. } @@ -1781,32 +2221,56 @@ net_destroy_state :: proc(state: ^Runtime_State) { net_get_conn :: proc(ctx: jsc.JSContextRef, id_val: jsc.JSValueRef) -> ^Net_Connection { state := get_state_from_ctx(ctx) - if state == nil do return nil + + if state == nil { + return nil + } + id := u64(jsc.JSValueToNumber(ctx, id_val, nil)) - if conn, ok := state.net_conns[id]; ok do return conn + + if conn, ok := state.net_conns[id]; ok { + return conn + } + return nil } net_get_server :: proc(ctx: jsc.JSContextRef, id_val: jsc.JSValueRef) -> ^Net_Server { state := get_state_from_ctx(ctx) - if state == nil do return nil + + if state == nil { + return nil + } + id := u64(jsc.JSValueToNumber(ctx, id_val, nil)) - if server, ok := state.net_servers[id]; ok do return server + + if server, ok := state.net_servers[id]; ok { + return server + } + return nil } net_protect :: proc(ctx: jsc.JSContextRef, fn: jsc.JSObjectRef) { - if fn != nil do jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)fn) + if fn != nil { + jsc.JSValueProtect(ctx, cast(jsc.JSValueRef)fn) + } } net_unprotect :: proc(ctx: jsc.JSContextRef, fn: jsc.JSObjectRef) { - if fn != nil do jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)fn) + if fn != nil { + jsc.JSValueUnprotect(ctx, cast(jsc.JSValueRef)fn) + } } net_emit :: proc(ctx: jsc.JSContextRef, fn: jsc.JSObjectRef, args: [^]jsc.JSValueRef, argc: c.size_t) { - if fn == nil do return + if fn == nil { + return + } + exception: jsc.JSValueRef invoke_user_callback(ctx, fn, args, argc, &exception) + if exception != nil { report_uncaught(ctx, exception) mark_async_failed(ctx) @@ -1814,7 +2278,10 @@ net_emit :: proc(ctx: jsc.JSContextRef, fn: jsc.JSObjectRef, args: [^]jsc.JSValu } net_emit_error :: proc(conn: ^Net_Connection, message: string) { - if conn.on_error == nil do return + if conn.on_error == nil { + return + } + arg := js_string_value(conn.ctx, message) net_emit(conn.ctx, conn.on_error, &arg, 1) } diff --git a/pkg/runtime/net_other.odin b/pkg/runtime/net_other.odin index 7ae0cf29..04164601 100644 --- a/pkg/runtime/net_other.odin +++ b/pkg/runtime/net_other.odin @@ -28,7 +28,10 @@ net_shutdown_active :: proc(state: ^Runtime_State) {} // The registries are make()d unconditionally in new_runtime_state (shared across platforms); free // their (empty here) backings so the non-Linux build doesn't leak the map headers at teardown. net_destroy_state :: proc(state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + delete(state.net_servers) delete(state.net_conns) delete(state.tls_server_ctxs) diff --git a/pkg/runtime/net_zc_test.odin b/pkg/runtime/net_zc_test.odin index 6944f395..e348a2ab 100644 --- a/pkg/runtime/net_zc_test.odin +++ b/pkg/runtime/net_zc_test.odin @@ -41,10 +41,12 @@ zc_free :: proc(conn: ^Net_Connection) { @(test) zc_result_records_off_only :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -61,10 +63,12 @@ zc_result_records_off_only :: proc(t: ^testing.T) { @(test) zc_result_errored_pinned_records_err :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -79,10 +83,12 @@ zc_result_errored_pinned_records_err :: proc(t: ^testing.T) { @(test) zc_terminal_drained :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -100,10 +106,12 @@ zc_terminal_drained :: proc(t: ^testing.T) { @(test) zc_terminal_copied_success_not_close :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 50) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -118,10 +126,12 @@ zc_terminal_copied_success_not_close :: proc(t: ^testing.T) { @(test) zc_terminal_stall_closes :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -136,10 +146,12 @@ zc_terminal_stall_closes :: proc(t: ^testing.T) { @(test) zc_terminal_einval_falls_back_plain :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -156,10 +168,12 @@ zc_terminal_einval_falls_back_plain :: proc(t: ^testing.T) { @(test) zc_terminal_enobufs_not_fatal :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -177,10 +191,12 @@ zc_terminal_enobufs_not_fatal :: proc(t: ^testing.T) { @(test) zc_errored_pinned_terminal_closes :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -198,10 +214,12 @@ zc_errored_pinned_terminal_closes :: proc(t: ^testing.T) { @(test) zc_carried_einval_falls_back_loopwide :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -221,10 +239,12 @@ zc_carried_einval_falls_back_loopwide :: proc(t: ^testing.T) { @(test) zc_eopnotsupp_is_per_conn :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -244,10 +264,12 @@ zc_eopnotsupp_is_per_conn :: proc(t: ^testing.T) { @(test) zc_partial_then_tail_resubmit :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 100) defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST: dispose ops while conn is still live, then free @@ -287,10 +309,12 @@ zc_pinned_at_teardown_predicate :: proc(t: ^testing.T) { @(test) zc_want_drain_keeps_reads_paused :: proc(t: ^testing.T) { loop := eventloop.init() + if !eventloop.proactor_available(&loop) { eventloop.destroy(&loop) return } + conn := zc_conn(&loop, 0) // empty body → net_proactor_buffered == 0 (< HWM): a "partial drain" state defer zc_free(conn) // runs LAST defer eventloop.destroy(&loop) // registered 2nd -> runs FIRST diff --git a/pkg/runtime/os.odin b/pkg/runtime/os.odin index c209a28f..d7913542 100644 --- a/pkg/runtime/os.odin +++ b/pkg/runtime/os.odin @@ -63,9 +63,11 @@ Uname_Field :: enum { // fallback when unset. Used by the platform layer for password-db / user fallbacks. os_getenv_or :: proc(key: string, fallback: string) -> string { v := os.get_env(key, context.temp_allocator) + if v == "" { return fallback } + return v } @@ -213,7 +215,11 @@ os_avail_parallelism_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() n := os_avail_parallelism() - if n < 1 do n = 1 + + if n < 1 { + n = 1 + } + return jsc.JSValueMakeNumber(ctx, f64(n)) } @@ -314,11 +320,13 @@ os_userinfo_cb :: proc "c" ( set_named(ctx, o, "gid", jsc.JSValueMakeNumber(ctx, f64(ui.gid))) set_named(ctx, o, "username", js_string_value(ctx, ui.username)) set_named(ctx, o, "homedir", js_string_value(ctx, ui.homedir)) + if ui.has_shell { set_named(ctx, o, "shell", js_string_value(ctx, ui.shell)) } else { set_named(ctx, o, "shell", jsc.JSValueMakeNull(ctx)) } + return cast(jsc.JSValueRef)o } @@ -339,14 +347,21 @@ os_getpriority_cb :: proc "c" ( ) -> jsc.JSValueRef { context = runtime.default_context() pid := 0 + if argument_count >= 1 { pid = int(jsc.JSValueToNumber(ctx, arguments[0], nil)) } + value, err := os_get_priority(pid) + if err != 0 { - if exception != nil do exception^ = make_os_system_error(ctx, "getpriority", err) + if exception != nil { + exception^ = make_os_system_error(ctx, "getpriority", err) + } + return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeNumber(ctx, f64(value)) } @@ -359,16 +374,26 @@ os_setpriority_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { - if exception != nil do exception^ = make_js_error(ctx, "os.setPriority requires (pid, priority)") + if exception != nil { + exception^ = make_js_error(ctx, "os.setPriority requires (pid, priority)") + } + return jsc.JSValueMakeUndefined(ctx) } + pid := int(jsc.JSValueToNumber(ctx, arguments[0], nil)) value := int(jsc.JSValueToNumber(ctx, arguments[1], nil)) + if err := os_set_priority(pid, value); err != 0 { - if exception != nil do exception^ = make_os_system_error(ctx, "setpriority", err) + if exception != nil { + exception^ = make_os_system_error(ctx, "setpriority", err) + } + return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeUndefined(ctx) } @@ -383,10 +408,12 @@ os_setpriority_cb :: proc "c" ( make_os_system_error :: proc(ctx: jsc.JSContextRef, syscall: string, err: int) -> jsc.JSValueRef { msg := fmt.tprintf("A system error occurred: %s returned errno %d", syscall, err) e := make_native_error(ctx, "SystemError", msg, "ERR_SYSTEM_ERROR") + if jsc.JSValueIsObject(ctx, e) { o := cast(jsc.JSObjectRef)e set_named(ctx, o, "errno", jsc.JSValueMakeNumber(ctx, f64(-err))) set_named(ctx, o, "syscall", js_string_value(ctx, syscall)) } + return e } diff --git a/pkg/runtime/os_darwin.odin b/pkg/runtime/os_darwin.odin index 9fda34f8..abd52b57 100644 --- a/pkg/runtime/os_darwin.odin +++ b/pkg/runtime/os_darwin.odin @@ -19,9 +19,11 @@ foreign libsystem { sysctl_u64 :: proc(name: string) -> (u64, bool) { v: u64 size := c.size_t(size_of(u64)) + if darwin.syscall_sysctlbyname(name, &v, &size, nil, 0) != 0 { return 0, false } + return v, true } @@ -29,9 +31,11 @@ sysctl_u64 :: proc(name: string) -> (u64, bool) { sysctl_u32 :: proc(name: string) -> (u32, bool) { v: u32 size := c.size_t(size_of(u32)) + if darwin.syscall_sysctlbyname(name, &v, &size, nil, 0) != 0 { return 0, false } + return v, true } @@ -39,9 +43,11 @@ sysctl_u32 :: proc(name: string) -> (u32, bool) { sysctl_i32 :: proc(name: string) -> (i32, bool) { v: i32 size := c.size_t(size_of(i32)) + if darwin.syscall_sysctlbyname(name, &v, &size, nil, 0) != 0 { return 0, false } + return v, true } @@ -49,16 +55,21 @@ sysctl_i32 :: proc(name: string) -> (i32, bool) { sysctl_string :: proc(name: string) -> string { buf: [256]u8 size := c.size_t(len(buf)) + if darwin.syscall_sysctlbyname(name, raw_data(buf[:]), &size, nil, 0) != 0 { return "" } + n := int(size) + if n > 0 && buf[n - 1] == 0 { n -= 1 // sysctl reports the length including the NUL terminator } + if n <= 0 { return "" } + out := make([]u8, n, context.temp_allocator) copy(out, buf[:n]) return string(out) @@ -70,9 +81,11 @@ os_avail_parallelism :: proc() -> int { if n, ok := sysctl_i32("hw.logicalcpu"); ok && n > 0 { return int(n) } + if m, ok := sysctl_i32("hw.ncpu"); ok && m > 0 { return int(m) } + return 1 } @@ -83,22 +96,28 @@ os_process_rss_bytes :: proc() -> u64 { os_totalmem :: proc() -> u64 { v, ok := sysctl_u64("hw.memsize") + if !ok { return 0 } + return v } os_freemem :: proc() -> u64 { // vm.page_free_count is a 32-bit page count; bytes = pages * page size. pages, ok := sysctl_u32("vm.page_free_count") + if !ok { return 0 } + page := u64(getpagesize()) + if page == 0 { page = 4096 } + return u64(pages) * page } @@ -107,36 +126,45 @@ os_uptime :: proc() -> f64 { // needed. Uptime is wall-clock now minus the boot epoch. boot: [2]i64 size := c.size_t(size_of(boot)) + if darwin.syscall_sysctlbyname("kern.boottime", &boot, &size, nil, 0) != 0 { return 0 } + now := time.now()._nsec / 1_000_000_000 + if now <= boot[0] { return 0 } + return f64(now - boot[0]) } os_cpus :: proc() -> []Os_Cpu { count := 0 + if n, ok := sysctl_i32("hw.logicalcpu"); ok && n > 0 { count = int(n) } else if m, ok2 := sysctl_i32("hw.ncpu"); ok2 && m > 0 { count = int(m) } + if count < 1 { count = 1 } model := sysctl_string("machdep.cpu.brand_string") + if model == "" { model = sysctl_string("hw.model") } + if model == "" { model = "unknown" } speed := 0 + if hz, ok := sysctl_u64("hw.cpufrequency"); ok { speed = int(hz / 1_000_000) } diff --git a/pkg/runtime/os_linux.odin b/pkg/runtime/os_linux.odin index c9cb9f55..0d1cdac4 100644 --- a/pkg/runtime/os_linux.odin +++ b/pkg/runtime/os_linux.odin @@ -23,59 +23,77 @@ read_sysinfo :: proc() -> (si: linux.Sys_Info, ok: bool) { @(private = "file") sysinfo_unit :: proc(si: linux.Sys_Info) -> u64 { unit := u64(si.mem_unit) + if unit == 0 { return 1 } + return unit } os_process_rss_bytes :: proc() -> u64 { data, err := os.read_entire_file("/proc/self/statm", context.temp_allocator) + if err != os.ERROR_NONE || len(data) == 0 { return 0 } + s := string(data) sp := strings.index_byte(s, ' ') + if sp < 0 { return 0 } + rest := s[sp + 1:] end := strings.index_byte(rest, ' ') + if end < 0 { end = len(rest) } + pages, ok := strconv.parse_u64(rest[:end]) + if !ok { return 0 } + page := u64(posix.sysconf(._PAGESIZE)) + if page == 0 { page = 4096 } + return pages * page } os_totalmem :: proc() -> u64 { si, ok := read_sysinfo() + if !ok { return 0 } + return u64(si.totalram) * sysinfo_unit(si) } os_freemem :: proc() -> u64 { si, ok := read_sysinfo() + if !ok { return 0 } + return u64(si.freeram) * sysinfo_unit(si) } os_uptime :: proc() -> f64 { si, ok := read_sysinfo() + if !ok { return 0 } + return f64(si.uptime) } @@ -86,9 +104,11 @@ os_uptime :: proc() -> f64 { // reports the same split (cpus() = all online CPUs, availableParallelism() = mask). os_avail_parallelism :: proc() -> int { n := os.get_processor_core_count() + if n < 1 { return 1 } + return n } @@ -99,9 +119,11 @@ os_avail_parallelism :: proc() -> int { @(private = "file") clk_tck :: proc() -> i64 { hz := i64(posix.sysconf(._CLK_TCK)) + if hz <= 0 { return 100 } + return hz } @@ -116,17 +138,21 @@ field_i64 :: proc(line: string, n: int) -> i64 { for i < len(line) && (line[i] == ' ' || line[i] == '\t') { i += 1 } + if i >= len(line) { break } + start := i for i < len(line) && line[i] != ' ' && line[i] != '\t' { i += 1 } + if idx == n { v, _ := strconv.parse_i64(line[start:i]) return v } + idx += 1 } return 0 @@ -135,9 +161,11 @@ field_i64 :: proc(line: string, n: int) -> i64 { @(private = "file") value_after_colon :: proc(line: string) -> string { idx := strings.index_byte(line, ':') + if idx < 0 { return "" } + return strings.trim_space(line[idx + 1:]) } @@ -152,9 +180,11 @@ os_cpus :: proc() -> []Os_Cpu { if len(line) < 4 || !strings.has_prefix(line, "cpu") { continue } + if line[3] < '0' || line[3] > '9' { continue // the aggregate "cpu " line } + append( &cpus, Os_Cpu { @@ -173,6 +203,7 @@ os_cpus :: proc() -> []Os_Cpu { // is exactly what Node reports in the same situation. models := make([dynamic]string, 0, 8, context.temp_allocator) speeds := make([dynamic]int, 0, 8, context.temp_allocator) + if data, err := os.read_entire_file("/proc/cpuinfo", context.temp_allocator); err == os.ERROR_NONE { cur_model := "" cur_speed := 0 @@ -186,9 +217,12 @@ os_cpus :: proc() -> []Os_Cpu { cur_speed = 0 have = false } + continue } + have = true + if strings.has_prefix(line, "model name") { cur_model = value_after_colon(line) } else if strings.has_prefix(line, "cpu MHz") { @@ -196,6 +230,7 @@ os_cpus :: proc() -> []Os_Cpu { cur_speed = int(f) } } + if have { append(&models, cur_model) append(&speeds, cur_speed) diff --git a/pkg/runtime/os_posix.odin b/pkg/runtime/os_posix.odin index b3dae09a..e8195439 100644 --- a/pkg/runtime/os_posix.odin +++ b/pkg/runtime/os_posix.odin @@ -99,22 +99,27 @@ clone_cstring :: proc(s: cstring) -> string { if s == nil { return "" } + return strings.clone(string(s), context.temp_allocator) } os_hostname :: proc() -> string { buf: [256]c.char + if posix.gethostname(raw_data(buf[:]), len(buf)) != .OK { return "" } + return clone_c_field(buf[:]) } os_uname :: proc(field: Uname_Field) -> string { u: posix.utsname + if posix.uname(&u) != 0 { return "" } + switch field { case .SYSNAME: return clone_c_field(u.sysname[:]) @@ -130,9 +135,11 @@ os_uname :: proc(field: Uname_Field) -> string { os_loadavg :: proc() -> [3]f64 { out: [3]f64 + if getloadavg(raw_data(out[:]), 3) != 3 { return {0, 0, 0} } + return out } @@ -144,22 +151,27 @@ os_user_info :: proc() -> Os_User_Info { gid = int(u32(gid)), } pw := posix.getpwuid(uid) + if pw != nil { ui.username = clone_cstring(pw.pw_name) ui.homedir = clone_cstring(pw.pw_dir) + if pw.pw_shell != nil && len(string(pw.pw_shell)) > 0 { ui.shell = clone_cstring(pw.pw_shell) ui.has_shell = true } } + // Fall back to the environment when there is no passwd entry (e.g. a bare // container UID); Node would throw here, but a best-effort answer is friendlier. if ui.username == "" { ui.username = os_getenv_or("USER", os_getenv_or("LOGNAME", "")) } + if ui.homedir == "" { ui.homedir = os_getenv_or("HOME", "") } + return ui } @@ -171,11 +183,13 @@ os_user_info :: proc() -> Os_User_Info { os_get_priority :: proc(pid: int) -> (value: int, err: int) { posix.set_errno(.NONE) v := posix.getpriority(.PROCESS, posix.id_t(pid)) + if v == -1 { if e := posix.errno(); e != .NONE { return 0, int(e) } } + return int(v), 0 } @@ -183,13 +197,17 @@ os_get_priority :: proc(pid: int) -> (value: int, err: int) { // (EPERM when lowering another user's nice value, ESRCH for an unknown pid). os_set_priority :: proc(pid: int, value: int) -> (err: int) { posix.set_errno(.NONE) + if posix.setpriority(.PROCESS, posix.id_t(pid), c.int(value)) != .OK { e := posix.errno() + if e == .NONE { e = .EPERM } + return int(e) } + return 0 } @@ -200,9 +218,11 @@ os_set_priority :: proc(pid: int, value: int) -> (err: int) { // Node). js/node/os.js groups them by name and adds the family string + CIDR. os_network_interfaces :: proc() -> []Os_Net_Iface { head: ^ifaddrs + if getifaddrs(&head) != 0 || head == nil { return nil } + defer freeifaddrs(head) macs := make(map[string]string, 8, context.temp_allocator) @@ -210,6 +230,7 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { if cur.ifa_addr == nil || int(cur.ifa_addr.sa_family) != AF_LINK_LOCAL { continue } + if mac, ok := link_mac(cur.ifa_addr); ok { macs[clone_cstring(cur.ifa_name)] = mac } @@ -220,12 +241,15 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { if cur.ifa_addr == nil { continue } + family := cur.ifa_addr.sa_family name := clone_cstring(cur.ifa_name) mac := "00:00:00:00:00:00" + if m, ok := macs[name]; ok { mac = m } + rec := Os_Net_Iface { name = name, mac = mac, @@ -236,6 +260,7 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { a := cast(^posix.sockaddr_in)cur.ifa_addr rec.family = 4 rec.address = format_v4(a.sin_addr.s_addr) + if cur.ifa_netmask != nil { m := cast(^posix.sockaddr_in)cur.ifa_netmask rec.netmask = format_v4(m.sin_addr.s_addr) @@ -245,6 +270,7 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { rec.family = 6 rec.address = format_v6(&a.sin6_addr) rec.scopeid = u32(a.sin6_scope_id) + if cur.ifa_netmask != nil { m := cast(^posix.sockaddr_in6)cur.ifa_netmask rec.netmask = format_v6(&m.sin6_addr) @@ -265,17 +291,21 @@ link_mac :: proc(sa: ^posix.sockaddr) -> (string, bool) { when ODIN_OS == .Linux { ll := cast(^sockaddr_ll)sa n := int(ll.sll_halen) + if n <= 0 || n > len(ll.sll_addr) { return "", false } + return format_mac(ll.sll_addr[:n]), true } else { dl := cast(^sockaddr_dl)sa n := int(dl.sdl_alen) start := 8 + int(dl.sdl_nlen) + if n <= 0 || start + n > int(dl.sdl_len) { return "", false } + base := cast([^]u8)sa return format_mac(base[start:start + n]), true } @@ -288,6 +318,7 @@ format_mac :: proc(b: []u8) -> string { if len(b) == 0 { return "00:00:00:00:00:00" } + hex := "0123456789abcdef" out := make([]u8, len(b) * 3 - 1, context.temp_allocator) j := 0 @@ -296,6 +327,7 @@ format_mac :: proc(b: []u8) -> string { out[j] = ':' j += 1 } + out[j] = hex[x >> 4] out[j + 1] = hex[x & 0xf] j += 2 @@ -317,8 +349,10 @@ format_v4 :: proc(addr: posix.in_addr_t) -> string { format_v6 :: proc(addr: rawptr) -> string { buf: [posix.INET6_ADDRSTRLEN]u8 res := posix.inet_ntop(.INET6, addr, raw_data(buf[:]), posix.socklen_t(len(buf))) + if res == nil { return "" } + return strings.clone(string(res), context.temp_allocator) } diff --git a/pkg/runtime/os_windows.odin b/pkg/runtime/os_windows.odin index 5bdfbb87..20faec64 100644 --- a/pkg/runtime/os_windows.odin +++ b/pkg/runtime/os_windows.odin @@ -114,18 +114,22 @@ os_process_rss_bytes :: proc() -> u64 { os_totalmem :: proc() -> u64 { status: windows.MEMORYSTATUSEX status.dwLength = windows.DWORD(size_of(windows.MEMORYSTATUSEX)) + if !windows.GlobalMemoryStatusEx(&status) { return 0 } + return u64(status.ullTotalPhys) } os_freemem :: proc() -> u64 { status: windows.MEMORYSTATUSEX status.dwLength = windows.DWORD(size_of(windows.MEMORYSTATUSEX)) + if !windows.GlobalMemoryStatusEx(&status) { return 0 } + return u64(status.ullAvailPhys) } @@ -147,9 +151,11 @@ os_avail_parallelism :: proc() -> int { si: windows.SYSTEM_INFO windows.GetSystemInfo(&si) n := int(si.dwNumberOfProcessors) + if n < 1 { return 1 } + return n } @@ -165,10 +171,13 @@ os_cpus :: proc() -> []Os_Cpu { // Core 0 supplies the fallback brand/speed for any core lacking its own key. model0 := reg_get_string(cpu_reg_key(0), "ProcessorNameString") + if model0 == "" { model0 = os_getenv_or("PROCESSOR_IDENTIFIER", "unknown") } + speed0 := 0 + if mhz, ok := reg_get_dword(cpu_reg_key(0), "~MHz"); ok { speed0 = int(mhz) } @@ -176,6 +185,7 @@ os_cpus :: proc() -> []Os_Cpu { perf := make([]System_Processor_Perf_Info, count, context.temp_allocator) got := 0 ret_len: u32 + if NtQuerySystemInformation( SYSTEM_PROCESSOR_PERFORMANCE_INFO_CLASS, raw_data(perf), @@ -190,17 +200,22 @@ os_cpus :: proc() -> []Os_Cpu { for i in 0 ..< count { key := cpu_reg_key(i) model := reg_get_string(key, "ProcessorNameString") + if model == "" { model = model0 } + speed := speed0 + if mhz, ok := reg_get_dword(key, "~MHz"); ok { speed = int(mhz) } + c := Os_Cpu { model = model, speed = speed, } + if i < got { p := perf[i] c.user = p.UserTime / 10000 @@ -208,6 +223,7 @@ os_cpus :: proc() -> []Os_Cpu { c.idle = p.IdleTime / 10000 c.irq = p.InterruptTime / 10000 } + cpus[i] = c } return cpus @@ -235,11 +251,13 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { buf := make([]u8, size, context.temp_allocator) base := cast([^]windows.IP_Adapter_Addresses)raw_data(buf) ret := windows.GetAdaptersAddresses(.Unspecified, flags, nil, base, &size) + if ret == ERROR_BUFFER_OVERFLOW { buf = make([]u8, size, context.temp_allocator) base = cast([^]windows.IP_Adapter_Addresses)raw_data(buf) ret = windows.GetAdaptersAddresses(.Unspecified, flags, nil, base, &size) } + if ret != windows.ERROR_SUCCESS { return nil } @@ -250,19 +268,24 @@ os_network_interfaces :: proc() -> []Os_Net_Iface { if adapter.OperStatus != .Up { continue } + name, _ := windows.wstring_to_utf8(adapter.FriendlyName, -1, context.temp_allocator) internal := adapter.IfType == IF_TYPE_SOFTWARE_LOOPBACK // Node/libuv report a MAC only for a standard 6-byte hardware address; // loopback / tunnel adapters (other lengths) are reported as all-zero. mac := "00:00:00:00:00:00" + if adapter.PhysicalAddressLength == 6 { mac = format_mac(adapter.PhysicalAddress[:6]) } + for ua := adapter.FirstUnicastAddress; ua != nil; ua = ua.Next { sa := ua.Address.lpSockaddr + if sa == nil { continue } + rec := Os_Net_Iface { name = name, mac = mac, @@ -297,10 +320,14 @@ os_get_priority :: proc(pid: int) -> (value: int, err: int) { current := pid == 0 handle := current ? windows.GetCurrentProcess() : windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, windows.FALSE, windows.DWORD(pid)) + if handle == nil { return 0, win_errno(windows.GetLastError()) } - defer if !current do windows.CloseHandle(handle) + + defer if !current { + windows.CloseHandle(handle) + } switch GetPriorityClass(handle) { case 0: @@ -344,14 +371,19 @@ os_set_priority :: proc(pid: int, value: int) -> (err: int) { current := pid == 0 handle := current ? windows.GetCurrentProcess() : windows.OpenProcess(windows.PROCESS_SET_INFORMATION, windows.FALSE, windows.DWORD(pid)) + if handle == nil { return win_errno(windows.GetLastError()) } - defer if !current do windows.CloseHandle(handle) + + defer if !current { + windows.CloseHandle(handle) + } if !SetPriorityClass(handle, cls) { return win_errno(windows.GetLastError()) } + return 0 } @@ -363,9 +395,11 @@ os_set_priority :: proc(pid: int, value: int) -> (err: int) { win_os_version :: proc() -> (major, minor, build: u32) { osvi: windows.OSVERSIONINFOEXW osvi.dwOSVersionInfoSize = u32(size_of(windows.OSVERSIONINFOEXW)) + if windows.RtlGetVersion(&osvi) == 0 { // STATUS_SUCCESS return osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber } + return 10, 0, 0 } @@ -375,12 +409,15 @@ win_os_version :: proc() -> (major, minor, build: u32) { @(private = "file") win_product_name :: proc() -> string { name := reg_get_string(REG_CURRENT_VERSION, "ProductName") + if name == "" { return "Windows" } + if _, _, build := win_os_version(); build >= 22000 && strings.has_prefix(name, "Windows 10") { return fmt.tprintf("Windows 11%s", name[len("Windows 10"):]) } + return name } @@ -390,11 +427,14 @@ reg_get_string :: proc(subkey, value: string) -> string { wsub := windows.utf8_to_wstring(subkey, context.temp_allocator) wval := windows.utf8_to_wstring(value, context.temp_allocator) size: windows.DWORD + if windows.RegGetValueW(windows.HKEY_LOCAL_MACHINE, wsub, wval, windows.RRF_RT_REG_SZ, nil, nil, &size) != 0 || size < 2 { return "" } + buf := make([]u16, int(size) / 2, context.temp_allocator) + if windows.RegGetValueW( windows.HKEY_LOCAL_MACHINE, wsub, @@ -407,6 +447,7 @@ reg_get_string :: proc(subkey, value: string) -> string { 0 { return "" } + s, _ := windows.utf16_to_utf8(buf[:], context.temp_allocator) return s } @@ -418,6 +459,7 @@ reg_get_dword :: proc(subkey, value: string) -> (u32, bool) { wval := windows.utf8_to_wstring(value, context.temp_allocator) data: windows.DWORD size := windows.DWORD(size_of(data)) + if windows.RegGetValueW( windows.HKEY_LOCAL_MACHINE, wsub, @@ -430,6 +472,7 @@ reg_get_dword :: proc(subkey, value: string) -> (u32, bool) { 0 { return 0, false } + return u32(data), true } @@ -468,6 +511,7 @@ format_mac :: proc(b: []u8) -> string { if len(b) == 0 { return "00:00:00:00:00:00" } + hex := "0123456789abcdef" out := make([]u8, len(b) * 3 - 1, context.temp_allocator) j := 0 @@ -476,6 +520,7 @@ format_mac :: proc(b: []u8) -> string { out[j] = ':' j += 1 } + out[j] = hex[x >> 4] out[j + 1] = hex[x & 0xf] j += 2 @@ -496,9 +541,11 @@ format_v4 :: proc(s_addr: u32) -> string { format_v6 :: proc(addr: ^windows.in6_addr) -> string { buf: [64]u8 res := inet_ntop(windows.AF_INET6, addr, raw_data(buf[:]), uint(len(buf))) + if res == nil { return "" } + return strings.clone(string(res), context.temp_allocator) } diff --git a/pkg/runtime/picohttpparser/picohttpparser.odin b/pkg/runtime/picohttpparser/picohttpparser.odin index 7d9eaac9..3f59f9d3 100644 --- a/pkg/runtime/picohttpparser/picohttpparser.odin +++ b/pkg/runtime/picohttpparser/picohttpparser.odin @@ -118,7 +118,7 @@ parse_response :: proc( value = value, } } - if msg_ptr != nil && msg_len > 0 do msg = string(msg_ptr[:msg_len]) + if msg_ptr != nil && msg_len > 0 {msg = string(msg_ptr[:msg_len])} return int(ret), int(status_c), msg, num, .Complete } @@ -175,7 +175,7 @@ parse_request :: proc( value = value, } } - if method_ptr != nil && method_len > 0 do method = string(method_ptr[:method_len]) - if path_ptr != nil && path_len > 0 do path = string(path_ptr[:path_len]) + if method_ptr != nil && method_len > 0 {method = string(method_ptr[:method_len])} + if path_ptr != nil && path_len > 0 {path = string(path_ptr[:path_len])} return int(ret), int(minor_c), num, method, path, .Complete } diff --git a/pkg/runtime/require.odin b/pkg/runtime/require.odin index 8240889a..fc67420b 100644 --- a/pkg/runtime/require.odin +++ b/pkg/runtime/require.odin @@ -34,12 +34,26 @@ module_precache_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 2 { + return jsc.JSValueMakeUndefined(ctx) + } + state := get_state_from_ctx(ctx) - if state == nil do return jsc.JSValueMakeUndefined(ctx) + + if state == nil { + return jsc.JSValueMakeUndefined(ctx) + } + path, allocated := jsc_value_to_string_or_default(ctx, arguments[0]) - defer if allocated do delete(path, context.allocator) - if !allocated do return jsc.JSValueMakeUndefined(ctx) + defer if allocated { + delete(path, context.allocator) + } + + if !allocated { + return jsc.JSValueMakeUndefined(ctx) + } + module_cache_set(ctx, state, path, arguments[1]) return jsc.JSValueMakeUndefined(ctx) } @@ -56,13 +70,18 @@ native_require_cb :: proc "c" ( // All the path/wrapper scratch in this call is temporary; reclaim it on exit // instead of letting the per-thread arena grow unbounded across requires. defer free_all(context.temp_allocator) - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } state := get_state_from_ctx(ctx) args := arguments[:int(argument_count)] specifier, alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if alloc do delete(specifier, context.allocator) + defer if alloc { + delete(specifier, context.allocator) + } // Module cache: a previously-loaded module (by specifier or resolved path) // returns its existing exports so top-level code runs exactly once. @@ -75,11 +94,15 @@ native_require_cb :: proc "c" ( // for anything it does not own, so we fall through to the native builtins // and the filesystem below. builtin_exception: jsc.JSValueRef + if builtin := require_builtin(ctx, args[0], &builtin_exception); builtin != nil { module_cache_put(ctx, state, specifier, builtin) return builtin } else if builtin_exception != nil { - if exception != nil do exception^ = builtin_exception + if exception != nil { + exception^ = builtin_exception + } + return jsc.JSValueMakeUndefined(ctx) } @@ -100,21 +123,28 @@ native_require_cb :: proc "c" ( // require resolves identically to a synchronous one. base_dir: string base_dir_alloc: bool + if len(args) >= 2 && jsc.JSValueIsString(ctx, args[1]) { base_dir, base_dir_alloc = jsc_value_to_string_or_default(ctx, args[1]) } else { base_dir, base_dir_alloc = global_dirname(ctx) } - defer if base_dir_alloc do delete(base_dir, context.allocator) + + defer if base_dir_alloc { + delete(base_dir, context.allocator) + } resolved, resolved_ok := resolve_module_path(specifier, base_dir) + if !resolved_ok { // Node throws MODULE_NOT_FOUND rather than silently yielding undefined. if exception != nil { exception^ = make_module_not_found(ctx, specifier) } + return jsc.JSValueMakeUndefined(ctx) } + defer delete(resolved, context.allocator) if cached, ok := module_cache_get(state, resolved); ok { @@ -123,12 +153,15 @@ native_require_cb :: proc "c" ( if strings.has_suffix(resolved, ".json") { data, err := os.read_entire_file(resolved, context.allocator) + if err != os.ERROR_NONE { if exception != nil { exception^ = make_js_error(ctx, fmt.tprintf("Cannot read module '%s'", resolved)) } + return jsc.JSValueMakeUndefined(ctx) } + defer delete(data, context.allocator) // Parse as JSON (Node uses JSON.parse), NOT JSEvaluateScript — wrapping the @@ -136,9 +169,14 @@ native_require_cb :: proc "c" ( // file and accept non-JSON. JSValueMakeFromJSONString returns null on a // malformed document, which we surface as a SyntaxError like Node. json_str := js_string_from_string(string(data)) - if json_str == nil do return jsc.JSValueMakeUndefined(ctx) + + if json_str == nil { + return jsc.JSValueMakeUndefined(ctx) + } + defer jsc.JSStringRelease(json_str) value := jsc.JSValueMakeFromJSONString(ctx, json_str) + if value == nil { if exception != nil { exception^ = make_js_named_error( @@ -147,27 +185,37 @@ native_require_cb :: proc "c" ( fmt.tprintf("Unexpected token in JSON in %s", resolved), ) } + return jsc.JSValueMakeUndefined(ctx) } + module_cache_put(ctx, state, resolved, value) return value } if strings.has_suffix(resolved, ".mjs") { data, err := os.read_entire_file(resolved, context.allocator) + if err != os.ERROR_NONE { if exception != nil { exception^ = make_js_error(ctx, fmt.tprintf("Cannot read module '%s'", resolved)) } + return jsc.JSValueMakeUndefined(ctx) } + defer delete(data, context.allocator) wrapped, wrap_ok := esm_wrap_source(ctx, string(data), resolved, exception) - if !wrap_ok do return jsc.JSValueMakeUndefined(ctx) + + if !wrap_ok { + return jsc.JSValueMakeUndefined(ctx) + } + defer delete(wrapped, context.allocator) value := eval_source_value(ctx, wrapped, resolved, exception) + if exception == nil || exception^ == nil { module_cache_put(ctx, state, resolved, value) } else { @@ -178,17 +226,21 @@ native_require_cb :: proc "c" ( // succeeding with broken (empty) exports. module_cache_remove(ctx, state, resolved) } + return value } if strings.has_suffix(resolved, ".cjs") || strings.has_suffix(resolved, ".js") { data, err := os.read_entire_file(resolved, context.allocator) + if err != os.ERROR_NONE { if exception != nil { exception^ = make_js_error(ctx, fmt.tprintf("Cannot read module '%s'", resolved)) } + return jsc.JSValueMakeUndefined(ctx) } + defer delete(data, context.allocator) dirname := filepath.dir(resolved) @@ -216,9 +268,13 @@ native_require_cb :: proc "c" ( ");return module.exports;})()", } wrapped, wrapped_err := strings.concatenate(wrapper_parts[:], context.temp_allocator) - if wrapped_err != nil do return jsc.JSValueMakeUndefined(ctx) + + if wrapped_err != nil { + return jsc.JSValueMakeUndefined(ctx) + } value := eval_source_value(ctx, wrapped, resolved, exception) + if exception == nil || exception^ == nil { // Overwrite the pre-registered partial entry with the final exports // (the body may have reassigned module.exports). @@ -228,6 +284,7 @@ native_require_cb :: proc "c" ( // re-loads it rather than getting half-initialised exports. module_cache_remove(ctx, state, resolved) } + return value } @@ -237,6 +294,7 @@ native_require_cb :: proc "c" ( if exception != nil { exception^ = make_module_not_found(ctx, specifier) } + return jsc.JSValueMakeUndefined(ctx) } @@ -297,20 +355,26 @@ inject_native_function :: proc( arity: int = 1, ) { c_name, err := strings.clone_to_cstring(name, context.temp_allocator) - if err != nil do return + + if err != nil { + return + } js_name := jsc.JSStringCreateWithUTF8CString(c_name) defer jsc.JSStringRelease(js_name) fn: jsc.JSObjectRef + if host != nil { fn, _ = jsc.host_function_create(ctx, name, host, arity) } else { fn = host_native_create(ctx, name, callback, arity) } + if fn == nil { fn = jsc.JSObjectMakeFunctionWithCallback(ctx, js_name, callback) } + jsc.JSObjectSetProperty(ctx, object, js_name, cast(jsc.JSValueRef)fn, {}, nil) } diff --git a/pkg/runtime/runtime.odin b/pkg/runtime/runtime.odin index 8741c3a4..5e26b803 100644 --- a/pkg/runtime/runtime.odin +++ b/pkg/runtime/runtime.odin @@ -93,6 +93,7 @@ result_destroy :: proc(res: ^Result) { if res.is_allocated && len(res.message) > 0 { delete(res.message) } + res^ = Result{} } @@ -168,7 +169,10 @@ Result_Hook :: proc(result: Result, user_data: rawptr) // shape of every `return` in eval and run_file, so that none can skip the hook. @(private = "file") reported :: proc(result: Result, report: Result_Hook, report_data: rawptr) -> Result { - if report != nil do report(result, report_data) + if report != nil { + report(result, report_data) + } + return result } @@ -208,7 +212,10 @@ eval :: proc( // below) exists, so they destroy the loop explicitly. It holds no handles yet, so // this single destroy needs no live context. if len(source) == 0 { - if loop != nil do eventloop.destroy(loop) + if loop != nil { + eventloop.destroy(loop) + } + return reported( Result{status = .Invalid_Input, exit_code = 2, message = "empty JavaScript source"}, report, @@ -217,7 +224,10 @@ eval :: proc( } if strings.has_prefix(source_name, "node:") { - if loop != nil do eventloop.destroy(loop) + if loop != nil { + eventloop.destroy(loop) + } + return reported( Result { status = .Invalid_Input, @@ -233,7 +243,10 @@ eval :: proc( // `__lava_precache`, neither of which a `.Web` context has; refused here, before a // context exists, rather than failing inside the transformed body. if surface == .Web && strings.has_suffix(source_name, ".mjs") { - if loop != nil do eventloop.destroy(loop) + if loop != nil { + eventloop.destroy(loop) + } + return reported( Result { status = .Invalid_Input, @@ -269,12 +282,18 @@ eval :: proc( // stash Runtime_State (loop + module cache) out of reach of user JavaScript. global_class := make_global_class() ctx := jsc.JSGlobalContextCreate(global_class) + if ctx == nil { jsc.JSClassRelease(global_class) + // Still consume the loop (no context was created, so no handles exist). - if loop != nil do eventloop.destroy(loop) + if loop != nil { + eventloop.destroy(loop) + } + return reported(native_runtime_unavailable(), report, report_data) } + defer jsc.JSClassRelease(global_class) defer release_global_context_after_eval(ctx) @@ -296,7 +315,9 @@ eval :: proc( // (LAVA_WORKERS unset/1) — there SIGTERM still terminates immediately without draining, as it did // before Slice 3a. Routing the single-worker path through the same machinery is a follow-up. when ODIN_OS == .Linux { - if loop != nil do eventloop.set_shutdown_hook(loop, net_drain_begin, state) + if loop != nil { + eventloop.set_shutdown_hook(loop, net_drain_begin, state) + } } // Snapshot the standard error constructors while globalThis is still pristine — @@ -340,10 +361,14 @@ eval :: proc( eval_source := source mjs_wrapped: string mjs_allocated := false - defer if mjs_allocated do delete(mjs_wrapped) + defer if mjs_allocated { + delete(mjs_wrapped) + } + if strings.has_suffix(source_name, ".mjs") { wrap_exception: jsc.JSValueRef wrapped, ok := esm_wrap_source(cast(jsc.JSContextRef)ctx, source, source_name, &wrap_exception) + if !ok { msg, allocated := value_to_string(cast(jsc.JSContextRef)ctx, wrap_exception) return reported( @@ -352,6 +377,7 @@ eval :: proc( report_data, ) } + eval_source = wrapped mjs_wrapped = wrapped mjs_allocated = true @@ -378,6 +404,7 @@ eval :: proc( // (install_microtasks). The post-evaluation drain_next_ticks_settled below still // runs on both surfaces; it goes through Runtime_State, not a global. TOP_LEVEL_DRAIN :: "\n;var __lava_tl_drain = (typeof __lavaDrainNextTicks === 'function') && __lavaDrainNextTicks();\n" + if surface == .Node { if combined, concat_err := strings.concatenate({eval_source, TOP_LEVEL_DRAIN}, context.temp_allocator); concat_err == nil { @@ -386,6 +413,7 @@ eval :: proc( } script := js_string_from_string(eval_source) + if script == nil { return reported( Result{status = .Invalid_Input, exit_code = 2, message = "could not allocate JavaScript source string"}, @@ -393,9 +421,11 @@ eval :: proc( report_data, ) } + defer jsc.JSStringRelease(script) c_source_name, c_source_name_err := strings.clone_to_cstring(source_name, context.temp_allocator) + if c_source_name_err != nil { return reported( Result{status = .Invalid_Input, exit_code = 2, message = "could not allocate JavaScript source name"}, @@ -405,6 +435,7 @@ eval :: proc( } source_url := jsc.JSStringCreateWithUTF8CString(c_source_name) + if source_url == nil { return reported( Result { @@ -416,6 +447,7 @@ eval :: proc( report_data, ) } + defer jsc.JSStringRelease(source_url) exception: jsc.JSValueRef @@ -449,7 +481,11 @@ eval :: proc( // loop entirely and fall through to the deferred teardown — the loop never ran, so this is a // direct teardown, not a drain. nil hook (single-worker) always proceeds. proceed := true - if pre_run != nil do proceed = pre_run(pre_run_data) + + if pre_run != nil { + proceed = pre_run(pre_run_data) + } + if proceed { eventloop.run(loop) // Loop teardown is the deferred eventloop.destroy declared above — it covers @@ -489,26 +525,37 @@ eval :: proc( // non-zero exit; otherwise a script-assigned process.exitCode is honored, matching // Node. (process.exit() is handled separately and terminates immediately.) resolve_exit_code :: proc(ctx: jsc.JSContextRef, state: ^Runtime_State) -> int { - if state != nil && state.async_failed do return 1 + if state != nil && state.async_failed { + return 1 + } + return process_exit_code(ctx) } process_exit_code :: proc(ctx: jsc.JSContextRef) -> int { global := jsc.JSContextGetGlobalObject(ctx) process := get_named(ctx, global, "process") + // JSValueGetType classifies the value in one call (Object vs the Undefined/Null // switch below); the JSValueIs* predicates are equally ABI-safe now that they // return a 1-byte `bool` (see cmd/lava jsc_value_predicates, #159) — the former // "unreliable across the FFI" note described the retired `b32` return. - if process == nil || jsc.JSValueGetType(ctx, process) != .Object do return 0 + if process == nil || jsc.JSValueGetType(ctx, process) != .Object { + return 0 + } + code := get_named(ctx, cast(jsc.JSObjectRef)process, "exitCode") - if code == nil do return 0 + + if code == nil { + return 0 + } #partial switch jsc.JSValueGetType(ctx, code) { case .Undefined, .Null: return 0 } n := jsc.JSValueToNumber(ctx, code, nil) - if n != n do return 0 // NaN guard (e.g. exitCode set to a non-numeric value) + + if n != n {return 0} // NaN guard (e.g. exitCode set to a non-numeric value) return int(n) } @@ -520,7 +567,10 @@ run_file :: proc( report_data: rawptr = nil, ) -> Result { if len(path) == 0 { - if loop != nil do eventloop.destroy(loop) + if loop != nil { + eventloop.destroy(loop) + } + return reported( Result{status = .Invalid_Input, exit_code = 2, message = "missing JavaScript file path"}, report, @@ -529,14 +579,19 @@ run_file :: proc( } data, err := os.read_entire_file(path, context.allocator) + if err != os.ERROR_NONE { - if loop != nil do eventloop.destroy(loop) + if loop != nil { + eventloop.destroy(loop) + } + return reported( Result{status = .Read_Error, exit_code = 1, message = "could not read JavaScript file"}, report, report_data, ) } + defer delete(data) return eval(string(data), path, loop, false, script_args, report = report, report_data = report_data) @@ -550,25 +605,32 @@ build_process_argv :: proc(source_name: string, script_args: []string) -> []stri argv := make([dynamic]string, 0, len(script_args) + 2, context.temp_allocator) exec_path := "lava" + if len(os.args) > 0 { exec_path = os.args[0] + if abs_exec, abs_err := filepath.abs(exec_path, context.temp_allocator); abs_err == os.ERROR_NONE && len(abs_exec) > 0 { exec_path = abs_exec } } + append(&argv, exec_path) if source_name != "" { script_path := source_name + if abs_script, abs_err := filepath.abs(source_name, context.temp_allocator); abs_err == os.ERROR_NONE && len(abs_script) > 0 { script_path = abs_script } + append(&argv, script_path) } - for arg in script_args do append(&argv, arg) + for arg in script_args { + append(&argv, arg) + } return argv[:] } @@ -586,9 +648,11 @@ is_success :: proc(result: Result) -> bool { js_string_from_string :: proc(value: string) -> jsc.JSStringRef { c_value, err := strings.clone_to_cstring(value, context.temp_allocator) + if err != nil { return nil } + return jsc.JSStringCreateWithUTF8CString(c_value) } @@ -598,9 +662,11 @@ js_string_from_string :: proc(value: string) -> jsc.JSStringRef { value_to_string :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> (string, bool) { exception: jsc.JSValueRef js_string := jsc.JSValueToStringCopy(ctx, value, &exception) + if js_string == nil { return "JavaScript value could not be converted to string", false } + defer jsc.JSStringRelease(js_string) return js_string_ref_to_utf8_owned(js_string) } diff --git a/pkg/runtime/sqlite.odin b/pkg/runtime/sqlite.odin index 056cbf65..c68358f3 100644 --- a/pkg/runtime/sqlite.odin +++ b/pkg/runtime/sqlite.odin @@ -36,7 +36,10 @@ make_sqlite_bindings :: proc(ctx: jsc.JSContextRef) -> jsc.JSObjectRef { // sqlite_destroy_state finalizes every open statement and database for the context. sqlite_destroy_state :: proc(state: ^Runtime_State) { - if state == nil do return + if state == nil { + return + } + for _, ptr in state.sqlite_stmts { stmt := cast(^sqlite.Statement)ptr sqlite.finalize(stmt) @@ -54,14 +57,26 @@ sqlite_destroy_state :: proc(state: ^Runtime_State) { // --- registry helpers --- sqlite_get_db :: proc(state: ^Runtime_State, id: u64) -> ^sqlite.Database { - if state == nil do return nil - if ptr, ok := state.sqlite_dbs[id]; ok do return cast(^sqlite.Database)ptr + if state == nil { + return nil + } + + if ptr, ok := state.sqlite_dbs[id]; ok { + return cast(^sqlite.Database)ptr + } + return nil } sqlite_get_stmt :: proc(state: ^Runtime_State, id: u64) -> ^sqlite.Statement { - if state == nil do return nil - if ptr, ok := state.sqlite_stmts[id]; ok do return cast(^sqlite.Statement)ptr + if state == nil { + return nil + } + + if ptr, ok := state.sqlite_stmts[id]; ok { + return cast(^sqlite.Statement)ptr + } + return nil } @@ -80,23 +95,38 @@ sqlite_open_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 1 { - if exception != nil do exception^ = make_js_error(ctx, "sqlite open requires a path") + if exception != nil { + exception^ = make_js_error(ctx, "sqlite open requires a path") + } + return jsc.JSValueMakeUndefined(ctx) } + state := get_state_from_ctx(ctx) - if state == nil do return jsc.JSValueMakeUndefined(ctx) + + if state == nil { + return jsc.JSValueMakeUndefined(ctx) + } args := arguments[:int(argument_count)] path, path_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if path_alloc do delete(path, context.allocator) + defer if path_alloc { + delete(path, context.allocator) + } db := new(sqlite.Database) result: sqlite.Result db^, result = sqlite.open(path) + if result.status != .Ok { free(db) - if exception != nil do exception^ = sqlite_error(ctx, result.message) + + if exception != nil { + exception^ = sqlite_error(ctx, result.message) + } + return jsc.JSValueMakeUndefined(ctx) } @@ -115,15 +145,21 @@ sqlite_close_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + state := get_state_from_ctx(ctx) id := sqlite_arg_id(ctx, arguments[0]) db := sqlite_get_db(state, id) + if db != nil { sqlite.close(db) free(db) delete_key(&state.sqlite_dbs, id) } + return jsc.JSValueMakeUndefined(ctx) } @@ -136,24 +172,38 @@ sqlite_exec_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { - if exception != nil do exception^ = make_js_error(ctx, "sqlite exec requires a handle and SQL") + if exception != nil { + exception^ = make_js_error(ctx, "sqlite exec requires a handle and SQL") + } + return jsc.JSValueMakeUndefined(ctx) } + state := get_state_from_ctx(ctx) args := arguments[:int(argument_count)] db := sqlite_get_db(state, sqlite_arg_id(ctx, args[0])) + if db == nil { - if exception != nil do exception^ = make_js_error(ctx, "database is not open") + if exception != nil { + exception^ = make_js_error(ctx, "database is not open") + } + return jsc.JSValueMakeUndefined(ctx) } + sql, sql_alloc := jsc_value_to_string_or_default(ctx, args[1]) - defer if sql_alloc do delete(sql, context.allocator) + defer if sql_alloc { + delete(sql, context.allocator) + } result := sqlite.exec(db, sql) + if result.status != .Ok && exception != nil { exception^ = sqlite_error(ctx, sqlite_error_text(db, result)) } + return jsc.JSValueMakeUndefined(ctx) } @@ -166,26 +216,43 @@ sqlite_prepare_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { - if exception != nil do exception^ = make_js_error(ctx, "sqlite prepare requires a handle and SQL") + if exception != nil { + exception^ = make_js_error(ctx, "sqlite prepare requires a handle and SQL") + } + return jsc.JSValueMakeUndefined(ctx) } + state := get_state_from_ctx(ctx) args := arguments[:int(argument_count)] db := sqlite_get_db(state, sqlite_arg_id(ctx, args[0])) + if db == nil { - if exception != nil do exception^ = make_js_error(ctx, "database is not open") + if exception != nil { + exception^ = make_js_error(ctx, "database is not open") + } + return jsc.JSValueMakeUndefined(ctx) } + sql, sql_alloc := jsc_value_to_string_or_default(ctx, args[1]) - defer if sql_alloc do delete(sql, context.allocator) + defer if sql_alloc { + delete(sql, context.allocator) + } stmt := new(sqlite.Statement) result: sqlite.Result stmt^, result = sqlite.prepare(db, sql) + if result.status != .Ok { free(stmt) - if exception != nil do exception^ = sqlite_error(ctx, sqlite_error_text(db, result)) + + if exception != nil { + exception^ = sqlite_error(ctx, sqlite_error_text(db, result)) + } + return jsc.JSValueMakeUndefined(ctx) } @@ -204,15 +271,21 @@ sqlite_finalize_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + state := get_state_from_ctx(ctx) id := sqlite_arg_id(ctx, arguments[0]) stmt := sqlite_get_stmt(state, id) + if stmt != nil { sqlite.finalize(stmt) free(stmt) delete_key(&state.sqlite_stmts, id) } + return jsc.JSValueMakeUndefined(ctx) } @@ -225,10 +298,18 @@ sqlite_reset_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + state := get_state_from_ctx(ctx) stmt := sqlite_get_stmt(state, sqlite_arg_id(ctx, arguments[0])) - if stmt != nil do sqlite.reset(stmt) + + if stmt != nil { + sqlite.reset(stmt) + } + return jsc.JSValueMakeUndefined(ctx) } @@ -241,10 +322,18 @@ sqlite_bind_parameter_count_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 0) + } + state := get_state_from_ctx(ctx) stmt := sqlite_get_stmt(state, sqlite_arg_id(ctx, arguments[0])) - if stmt == nil do return jsc.JSValueMakeNumber(ctx, 0) + + if stmt == nil { + return jsc.JSValueMakeNumber(ctx, 0) + } + return jsc.JSValueMakeNumber(ctx, f64(sqlite.bind_parameter_count(stmt))) } @@ -260,10 +349,18 @@ sqlite_bind_parameter_name_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 2 do return js_string_value(ctx, "") + + if argument_count < 2 { + return js_string_value(ctx, "") + } + state := get_state_from_ctx(ctx) stmt := sqlite_get_stmt(state, sqlite_arg_id(ctx, arguments[0])) - if stmt == nil do return js_string_value(ctx, "") + + if stmt == nil { + return js_string_value(ctx, "") + } + index := int(jsc.JSValueToNumber(ctx, arguments[1], nil)) return js_string_value(ctx, sqlite.bind_parameter_name(stmt, index)) } @@ -279,17 +376,27 @@ sqlite_bind_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 3 { - if exception != nil do exception^ = make_js_error(ctx, "sqlite bind requires handle, index and value") + if exception != nil { + exception^ = make_js_error(ctx, "sqlite bind requires handle, index and value") + } + return jsc.JSValueMakeUndefined(ctx) } + state := get_state_from_ctx(ctx) args := arguments[:int(argument_count)] stmt := sqlite_get_stmt(state, sqlite_arg_id(ctx, args[0])) + if stmt == nil { - if exception != nil do exception^ = make_js_error(ctx, "statement is not prepared") + if exception != nil { + exception^ = make_js_error(ctx, "statement is not prepared") + } + return jsc.JSValueMakeUndefined(ctx) } + index := int(jsc.JSValueToNumber(ctx, args[1], nil)) value := args[2] @@ -315,20 +422,26 @@ sqlite_bind_cb :: proc "c" ( res = sqlite.bind_double(stmt, index, jsc.JSValueToNumber(ctx, value, nil)) case .String: s, alloc := jsc_value_to_string_or_default(ctx, value) - defer if alloc do delete(s, context.allocator) + defer if alloc { + delete(s, context.allocator) + } res = sqlite.bind_text(stmt, index, s) case .Object: if jsc.JSValueGetTypedArrayType(ctx, value, nil) != .None { bytes: []byte = nil + if view, ok := typed_array_view(ctx, value); ok { bytes = view } + res = sqlite.bind_blob(stmt, index, bytes) } else if exception != nil { exception^ = make_js_error(ctx, "unsupported SQLite bind value type") } case: - if exception != nil do exception^ = make_js_error(ctx, "unsupported SQLite bind value type") + if exception != nil { + exception^ = make_js_error(ctx, "unsupported SQLite bind value type") + } } sqlite_throw_bind_error(ctx, res, exception) return jsc.JSValueMakeUndefined(ctx) @@ -347,25 +460,42 @@ sqlite_bind_bigint_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 3 { - if exception != nil do exception^ = make_js_error(ctx, "sqlite bindBigInt requires handle, index and value") + if exception != nil { + exception^ = make_js_error(ctx, "sqlite bindBigInt requires handle, index and value") + } + return jsc.JSValueMakeUndefined(ctx) } + state := get_state_from_ctx(ctx) args := arguments[:int(argument_count)] stmt := sqlite_get_stmt(state, sqlite_arg_id(ctx, args[0])) + if stmt == nil { - if exception != nil do exception^ = make_js_error(ctx, "statement is not prepared") + if exception != nil { + exception^ = make_js_error(ctx, "statement is not prepared") + } + return jsc.JSValueMakeUndefined(ctx) } + index := int(jsc.JSValueToNumber(ctx, args[1], nil)) s, alloc := jsc_value_to_string_or_default(ctx, args[2]) - defer if alloc do delete(s, context.allocator) + defer if alloc { + delete(s, context.allocator) + } v, ok := strconv.parse_i64(s) + if !ok { - if exception != nil do exception^ = make_js_error(ctx, "invalid BigInt value") + if exception != nil { + exception^ = make_js_error(ctx, "invalid BigInt value") + } + return jsc.JSValueMakeUndefined(ctx) } + sqlite_throw_bind_error(ctx, sqlite.bind_int(stmt, index, v), exception) return jsc.JSValueMakeUndefined(ctx) } @@ -396,10 +526,19 @@ sqlite_error :: proc(ctx: jsc.JSContextRef, message: string) -> jsc.JSValueRef { // JS Error carrying SQLite's text and the ERR_SQLITE_ERROR code, instead of // letting the statement execute with the slot silently unbound. sqlite_throw_bind_error :: proc(ctx: jsc.JSContextRef, res: sqlite.Result, exception: ^jsc.JSValueRef) { - if res.status == .Ok do return - if exception == nil do return + if res.status == .Ok { + return + } + + if exception == nil { + return + } + // Don't clobber a more specific exception already set by the caller. - if exception^ != nil do return + if exception^ != nil { + return + } + msg := len(res.message) > 0 ? res.message : "sqlite bind failed" exception^ = sqlite_error(ctx, msg) } @@ -414,14 +553,23 @@ sqlite_step_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 1) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 1) + } + state := get_state_from_ctx(ctx) id := sqlite_arg_id(ctx, arguments[0]) stmt := sqlite_get_stmt(state, id) + if stmt == nil { - if exception != nil do exception^ = make_js_error(ctx, "statement is not prepared") + if exception != nil { + exception^ = make_js_error(ctx, "statement is not prepared") + } + return jsc.JSValueMakeNumber(ctx, 1) } + switch sqlite.step(stmt) { case .Row: return jsc.JSValueMakeNumber(ctx, 0) @@ -430,11 +578,17 @@ sqlite_step_cb :: proc "c" ( case .Error: // The owning db id is passed as the 2nd arg so we can surface its errmsg. db := argument_count >= 2 ? sqlite_get_db(state, sqlite_arg_id(ctx, arguments[1])) : nil + if exception != nil { msg := db != nil ? sqlite.errmsg(db, context.temp_allocator) : "sqlite step failed" - if len(msg) == 0 do msg = "sqlite step failed" + + if len(msg) == 0 { + msg = "sqlite step failed" + } + exception^ = sqlite_error(ctx, msg) } + return jsc.JSValueMakeNumber(ctx, 1) } return jsc.JSValueMakeNumber(ctx, 1) @@ -451,10 +605,17 @@ sqlite_row_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + state := get_state_from_ctx(ctx) stmt := sqlite_get_stmt(state, sqlite_arg_id(ctx, arguments[0])) - if stmt == nil do return jsc.JSValueMakeUndefined(ctx) + + if stmt == nil { + return jsc.JSValueMakeUndefined(ctx) + } read_big_ints := sqlite_read_big_ints(ctx, argument_count, arguments, 1) row := jsc.JSObjectMake(ctx, nil, nil) @@ -465,8 +626,11 @@ sqlite_row_cb :: proc "c" ( switch sqlite.column_type(stmt, i) { case .Integer: value = sqlite_int_value(ctx, sqlite.column_int(stmt, i), read_big_ints, exception) + // An out-of-range INTEGER throws (ERR_OUT_OF_RANGE) — abandon the row. - if exception != nil && exception^ != nil do return jsc.JSValueMakeUndefined(ctx) + if exception != nil && exception^ != nil { + return jsc.JSValueMakeUndefined(ctx) + } case .Float: value = jsc.JSValueMakeNumber(ctx, sqlite.column_double(stmt, i)) case .Text: @@ -494,10 +658,18 @@ sqlite_changes_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 0) + } + state := get_state_from_ctx(ctx) db := sqlite_get_db(state, sqlite_arg_id(ctx, arguments[0])) - if db == nil do return jsc.JSValueMakeNumber(ctx, 0) + + if db == nil { + return jsc.JSValueMakeNumber(ctx, 0) + } + read_big_ints := sqlite_read_big_ints(ctx, argument_count, arguments, 1) // Unsafe counts throw like a column read (node 26); see sqlite_int_value. return sqlite_int_value(ctx, sqlite.changes(db), read_big_ints, exception) @@ -512,10 +684,18 @@ sqlite_last_insert_rowid_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeNumber(ctx, 0) + + if argument_count < 1 { + return jsc.JSValueMakeNumber(ctx, 0) + } + state := get_state_from_ctx(ctx) db := sqlite_get_db(state, sqlite_arg_id(ctx, arguments[0])) - if db == nil do return jsc.JSValueMakeNumber(ctx, 0) + + if db == nil { + return jsc.JSValueMakeNumber(ctx, 0) + } + read_big_ints := sqlite_read_big_ints(ctx, argument_count, arguments, 1) return sqlite_int_value(ctx, sqlite.last_insert_rowid(db), read_big_ints, exception) } @@ -533,7 +713,10 @@ sqlite_read_big_ints :: proc( arguments: [^]jsc.JSValueRef, index: int, ) -> bool { - if int(argument_count) <= index do return false + if int(argument_count) <= index { + return false + } + // JSValueToBoolean is ABI-safe now that the binding returns a 1-byte `bool` // (the old `b32` return read undefined upper bytes, so a JS `false` came back // `true` — the historical "heisenbug" this once worked around with a @@ -553,14 +736,19 @@ sqlite_int_value :: proc( read_big_ints: bool, exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { - if read_big_ints do return sqlite_make_bigint(ctx, v) + if read_big_ints { + return sqlite_make_bigint(ctx, v) + } + if (v > SQLITE_MAX_SAFE_INTEGER || v < -SQLITE_MAX_SAFE_INTEGER) { if exception != nil { msg := fmt.tprintf("Value is too large to be represented as a JavaScript number: %d", v) exception^ = make_native_error(ctx, "RangeError", msg, "ERR_OUT_OF_RANGE") } + return jsc.JSValueMakeUndefined(ctx) } + return jsc.JSValueMakeNumber(ctx, f64(v)) } @@ -572,10 +760,18 @@ sqlite_make_bigint :: proc(ctx: jsc.JSContextRef, v: i64) -> jsc.JSValueRef { name := jsc.JSStringCreateWithUTF8CString("BigInt") defer jsc.JSStringRelease(name) fn := jsc.JSObjectGetProperty(ctx, global, name, nil) - if !jsc.JSValueIsObject(ctx, fn) do return jsc.JSValueMakeNumber(ctx, f64(v)) + + if !jsc.JSValueIsObject(ctx, fn) { + return jsc.JSValueMakeNumber(ctx, f64(v)) + } + args := [1]jsc.JSValueRef{js_string_value(ctx, s)} result := jsc.JSObjectCallAsFunction(ctx, cast(jsc.JSObjectRef)fn, nil, 1, raw_data(args[:]), nil) - if result == nil do return jsc.JSValueMakeNumber(ctx, f64(v)) + + if result == nil { + return jsc.JSValueMakeNumber(ctx, f64(v)) + } + return result } @@ -584,7 +780,11 @@ sqlite_make_bigint :: proc(ctx: jsc.JSContextRef, v: i64) -> jsc.JSValueRef { // (make_js_error copies it into the JS string). sqlite_error_text :: proc(db: ^sqlite.Database, result: sqlite.Result) -> string { detail := sqlite.errmsg(db, context.temp_allocator) - if len(detail) > 0 do return detail + + if len(detail) > 0 { + return detail + } + return result.message } @@ -592,6 +792,10 @@ sqlite_blob_to_value :: proc(ctx: jsc.JSContextRef, data: []byte) -> jsc.JSValue // Copy into a buffer JSC owns (make_uint8_array frees it on collection); // sqlite's blob pointer is only valid until the next step/reset/finalize. buf := make([]byte, len(data), runtime.heap_allocator()) // freed by jsc_buffer_deallocator, on the heap - if len(data) > 0 do copy(buf, data) + + if len(data) > 0 { + copy(buf, data) + } + return make_uint8_array(ctx, buf) } diff --git a/pkg/runtime/stdio.odin b/pkg/runtime/stdio.odin index f55c5643..b51473ad 100644 --- a/pkg/runtime/stdio.odin +++ b/pkg/runtime/stdio.odin @@ -61,6 +61,7 @@ stdio_write_sync_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { return jsc.JSValueMakeNumber(ctx, 0) } @@ -84,6 +85,7 @@ stdio_write_sync_cb :: proc "c" ( if exception != nil { exception^ = make_js_error(ctx, "stdio writeSync: fd must be 1 or 2") } + return jsc.JSValueMakeNumber(ctx, 0) } @@ -91,17 +93,23 @@ stdio_write_sync_cb :: proc "c" ( // typed-array view is BORROWED into the JSC heap, which is safe here only because the // write below runs to completion on this thread with no JS in between. bytes, owned, ok := fs_resolve_write_payload(ctx, arguments[1]) + if !ok { if exception != nil { exception^ = make_js_error(ctx, "stdio writeSync: unsupported chunk type") } + return jsc.JSValueMakeNumber(ctx, 0) } - defer if owned do delete(bytes, context.allocator) + + defer if owned { + delete(bytes, context.allocator) + } if len(bytes) == 0 { return jsc.JSValueMakeNumber(ctx, 0) } + process_write_bytes(target, bytes) return jsc.JSValueMakeNumber(ctx, f64(len(bytes))) } diff --git a/pkg/runtime/stdio_posix.odin b/pkg/runtime/stdio_posix.odin index 63f119e6..f152dad8 100644 --- a/pkg/runtime/stdio_posix.odin +++ b/pkg/runtime/stdio_posix.odin @@ -28,7 +28,11 @@ import "core:sys/posix" // either as fatal is what silently truncated output to exactly one pipe buffer. stdio_retryable :: proc(err: os.Error) -> bool { perr, ok := err.(os.Platform_Error) - if !ok do return false + + if !ok { + return false + } + // Cross-package enum reinterpret: on Linux `perr` is a linux.Errno and this reads it as // a posix.Errno. Sound only because Linux's posix.Errno is defined from the same ABI — // verified equal for the two that matter (EAGAIN 11, EINTR 4). On darwin it is identity. diff --git a/pkg/runtime/tls.odin b/pkg/runtime/tls.odin index 59cdfdb1..d78b9965 100644 --- a/pkg/runtime/tls.odin +++ b/pkg/runtime/tls.odin @@ -166,9 +166,17 @@ g_tls_ctx_once: sync.Once @(private = "file") tls_build_ctx :: proc() { method := TLS_client_method() - if method == nil do return + + if method == nil { + return + } + ctx := SSL_CTX_new(method) - if ctx == nil do return + + if ctx == nil { + return + } + // Fail closed if the trust store can't be loaded (verification would have // nothing to check against) or the TLS 1.2 floor can't be set. Both return // 1 on success; SSL_CTX_ctrl(SET_MIN_PROTO_VERSION) returns 1 likewise. @@ -177,6 +185,7 @@ tls_build_ctx :: proc() { SSL_CTX_free(ctx) return } + // Add any platform-native roots (Windows cert store) on top of the OpenSSL // defaults. Best-effort: if it loads nothing, verification simply falls back // to whatever set_default_verify_paths / SSL_CERT_FILE provided and a missing @@ -212,9 +221,17 @@ tls_client_ctx :: proc() -> SSL_CTX { // fetch_tls_cleanup). tls_new_client :: proc(fd: uintptr, host: string) -> SSL { ctx := tls_client_ctx() - if ctx == nil do return nil + + if ctx == nil { + return nil + } + ssl := SSL_new(ctx) - if ssl == nil do return nil + + if ssl == nil { + return nil + } + // SSL_set_fd takes an int. On Windows req.fd is a SOCKET (a uintptr-wide // kernel handle); narrowing to c.int is the documented OpenSSL-on-Windows // convention (its BIO socket layer uses int) and real socket values fit. @@ -222,13 +239,16 @@ tls_new_client :: proc(fd: uintptr, host: string) -> SSL { SSL_free(ssl) return nil } + // Verification needs a NUL-terminated host. OpenSSL copies it into its own // storage, so a temp-allocator cstring scoped to this proc is sufficient. chost, clone_err := strings.clone_to_cstring(host, context.temp_allocator) + if clone_err != nil { SSL_free(ssl) return nil } + // An IP-literal host verifies against the certificate's iPAddress SAN (not a // DNS name) and must NOT be sent as SNI (RFC 6066 forbids IP literals there). // A DNS name uses SNI + DNS-name verification. Fail closed: if any of these @@ -244,11 +264,13 @@ tls_new_client :: proc(fd: uintptr, host: string) -> SSL { SSL_free(ssl) return nil } + if SSL_set1_host(ssl, chost) != 1 { SSL_free(ssl) return nil } } + return ssl } @@ -256,7 +278,13 @@ tls_new_client :: proc(fd: uintptr, host: string) -> SSL { // be verified as an IP address rather than a DNS name). The transport delivers // IPv6 literals bracket-stripped (e.g. "::1"), matching net.parse_ip6_address. tls_host_is_ip :: proc(host: string) -> bool { - if _, ok := net.parse_ip4_address(host); ok do return true - if _, ok := net.parse_ip6_address(host); ok do return true + if _, ok := net.parse_ip4_address(host); ok { + return true + } + + if _, ok := net.parse_ip6_address(host); ok { + return true + } + return false } diff --git a/pkg/runtime/tls_darwin.odin b/pkg/runtime/tls_darwin.odin index 72037146..df092e90 100644 --- a/pkg/runtime/tls_darwin.odin +++ b/pkg/runtime/tls_darwin.odin @@ -190,10 +190,12 @@ darwin_ssl_read_cb :: proc "c" (connection: SSLConnectionRef, data: rawptr, data status: OSStatus = errSecSuccess for total < requested { n := posix.recv(posix.FD(sess.fd), rawptr(&buf[total]), requested - total, {}) + if n > 0 { total += c.size_t(n) continue } + if n == 0 { status = errSSLClosedGraceful // orderly peer close break @@ -228,6 +230,7 @@ darwin_ssl_write_cb :: proc "c" (connection: SSLConnectionRef, data: rawptr, dat status: OSStatus = errSecSuccess for total < requested { n := posix.send(posix.FD(sess.fd), rawptr(&buf[total]), requested - total, {}) + if n > 0 { total += c.size_t(n) continue @@ -259,12 +262,18 @@ darwin_ssl_write_cb :: proc "c" (connection: SSLConnectionRef, data: rawptr, dat // iPAddress SAN by a policy attached in darwin_tls_verify_peer. darwin_tls_new_client :: proc(fd: uintptr, host: string) -> ^Darwin_TLS_Session { ctx := SSLCreateContext(nil, .Client, .Stream) - if ctx == nil do return nil + + if ctx == nil { + return nil + } + sess := new(Darwin_TLS_Session) + if sess == nil { CFRelease(rawptr(ctx)) return nil } + sess.ctx = ctx sess.fd = fd sess.want = .Write @@ -288,15 +297,18 @@ darwin_tls_new_client :: proc(fd: uintptr, host: string) -> ^Darwin_TLS_Session // name, so a temp-allocator cstring is fine; fail closed if it can't be set. if !sess.is_ip { chost, clone_err := strings.clone_to_cstring(host, context.temp_allocator) + if clone_err != nil { darwin_tls_free(sess) return nil } + if SSLSetPeerDomainName(ctx, chost, c.size_t(len(host))) != errSecSuccess { darwin_tls_free(sess) return nil } } + return sess } @@ -309,7 +321,11 @@ darwin_tls_new_client :: proc(fd: uintptr, host: string) -> ^Darwin_TLS_Session // the event-loop thread (matching OpenSSL's local-only verification). darwin_tls_verify_peer :: proc(sess: ^Darwin_TLS_Session, host: string) -> bool { trust: SecTrustRef - if SSLCopyPeerTrust(sess.ctx, &trust) != errSecSuccess || trust == nil do return false + + if SSLCopyPeerTrust(sess.ctx, &trust) != errSecSuccess || trust == nil { + return false + } + defer CFRelease(rawptr(trust)) // An IP literal had no peer domain name set (no SNI), so the trust object carries @@ -318,14 +334,29 @@ darwin_tls_verify_peer :: proc(sess: ^Darwin_TLS_Session, host: string) -> bool // accept any root-trusted cert for the IP). if sess.is_ip { chost, clone_err := strings.clone_to_cstring(host, context.temp_allocator) - if clone_err != nil do return false + + if clone_err != nil { + return false + } + host_cf := CFStringCreateWithCString(nil, chost, kCFStringEncodingUTF8) - if host_cf == nil do return false + + if host_cf == nil { + return false + } + defer CFRelease(rawptr(host_cf)) policy := SecPolicyCreateSSL(true, host_cf) - if policy == nil do return false + + if policy == nil { + return false + } + defer CFRelease(rawptr(policy)) - if SecTrustSetPolicies(trust, CFTypeRef(policy)) != errSecSuccess do return false + + if SecTrustSetPolicies(trust, CFTypeRef(policy)) != errSecSuccess { + return false + } } // Add SSL_CERT_FILE anchors (if any) on top of the system roots @@ -333,8 +364,13 @@ darwin_tls_verify_peer :: proc(sess: ^Darwin_TLS_Session, host: string) -> bool // behavior. A missing/empty/unparseable file leaves anchors nil and verification // falls back to the system trust store — it never weakens verification. if anchors := darwin_tls_extra_anchors(); anchors != nil { - if SecTrustSetAnchorCertificates(trust, anchors) != errSecSuccess do return false - if SecTrustSetAnchorCertificatesOnly(trust, false) != errSecSuccess do return false + if SecTrustSetAnchorCertificates(trust, anchors) != errSecSuccess { + return false + } + + if SecTrustSetAnchorCertificatesOnly(trust, false) != errSecSuccess { + return false + } } // Keep evaluation off the network: no AIA intermediate fetching or OCSP, so it @@ -345,7 +381,11 @@ darwin_tls_verify_peer :: proc(sess: ^Darwin_TLS_Session, host: string) -> bool err: CFErrorRef ok := SecTrustEvaluateWithError(trust, &err) - if err != nil do CFRelease(rawptr(err)) + + if err != nil { + CFRelease(rawptr(err)) + } + return bool(ok) } @@ -354,11 +394,15 @@ darwin_tls_verify_peer :: proc(sess: ^Darwin_TLS_Session, host: string) -> bool // fd is ignored — we are tearing down). CFRelease frees the context; the fd itself // is closed separately by the transport after fetch_tls_cleanup. darwin_tls_free :: proc(sess: ^Darwin_TLS_Session) { - if sess == nil do return + if sess == nil { + return + } + if sess.ctx != nil { SSLClose(sess.ctx) CFRelease(rawptr(sess.ctx)) } + free(sess) } @@ -368,8 +412,14 @@ darwin_tls_free :: proc(sess: ^Darwin_TLS_Session) { // tls_host_is_ip in the OpenSSL backend. @(private = "file") darwin_tls_host_is_ip :: proc(host: string) -> bool { - if _, ok := net.parse_ip4_address(host); ok do return true - if _, ok := net.parse_ip6_address(host); ok do return true + if _, ok := net.parse_ip4_address(host); ok { + return true + } + + if _, ok := net.parse_ip6_address(host); ok { + return true + } + return false } @@ -391,6 +441,7 @@ darwin_tls_extra_anchors :: proc() -> CFArrayRef { g_extra_anchors_built = true g_extra_anchors = darwin_tls_load_env_anchors() } + return g_extra_anchors } @@ -401,33 +452,54 @@ darwin_tls_extra_anchors :: proc() -> CFArrayRef { @(private = "file") darwin_tls_load_env_anchors :: proc() -> CFArrayRef { path, found := os.lookup_env("SSL_CERT_FILE", context.temp_allocator) - if !found || path == "" do return nil + + if !found || path == "" { + return nil + } data, read_err := os.read_entire_file(path, context.temp_allocator) - if read_err != nil do return nil + + if read_err != nil { + return nil + } certs: [dynamic]rawptr defer delete(certs) rest := data for len(rest) > 0 { blk, remaining, decode_err := pem.decode(rest, context.temp_allocator) - if decode_err != nil || blk == nil do break + + if decode_err != nil || blk == nil { + break + } + rest = remaining + if blk.label == pem.LABEL_CERTIFICATE && len(blk.data) > 0 { cfdata := CFDataCreate(nil, raw_data(blk.data[:]), CFIndex(len(blk.data))) + if cfdata != nil { cert := SecCertificateCreateWithData(nil, cfdata) CFRelease(rawptr(cfdata)) - if cert != nil do append(&certs, rawptr(cert)) + + if cert != nil { + append(&certs, rawptr(cert)) + } } } + pem.block_delete(blk) } - if len(certs) == 0 do return nil + + if len(certs) == 0 { + return nil + } // CFArrayCreate with kCFTypeArrayCallBacks retains each cert, so we release our own // references and let the (process-lifetime) array own them. arr := CFArrayCreate(nil, raw_data(certs[:]), CFIndex(len(certs)), &kCFTypeArrayCallBacks) - for cert in certs do CFRelease(cert) + for cert in certs { + CFRelease(cert) + } return arr } diff --git a/pkg/runtime/tls_roots_windows.odin b/pkg/runtime/tls_roots_windows.odin index aee00779..43b0fae1 100644 --- a/pkg/runtime/tls_roots_windows.odin +++ b/pkg/runtime/tls_roots_windows.odin @@ -45,7 +45,11 @@ foreign crypt32 { tls_load_platform_roots :: proc(ctx: SSL_CTX) { store := SSL_CTX_get_cert_store(ctx) - if store == nil do return + + if store == nil { + return + } + load_windows_store(store, win.utf8_to_wstring("ROOT")) load_windows_store(store, win.utf8_to_wstring("CA")) } @@ -56,18 +60,26 @@ tls_load_platform_roots :: proc(ctx: SSL_CTX) { @(private = "file") load_windows_store :: proc(store: X509_STORE, name: win.wstring) { hstore := CertOpenSystemStoreW(nil, name) - if hstore == nil do return + + if hstore == nil { + return + } + defer CertCloseStore(hstore, 0) cert: PCCERT_CONTEXT for { cert = CertEnumCertificatesInStore(hstore, cert) - if cert == nil do break + + if cert == nil { + break + } // d2i_X509 advances the pointer it's given, so hand it a local copy. der := cert.pbCertEncoded x := d2i_X509(nil, &der, c.long(cert.cbCertEncoded)) - if x == nil do continue // not a DER X.509 cert we understand + + if x == nil {continue} // not a DER X.509 cert we understand // add_cert up-refs on success and returns 0 for a duplicate (already in the // store) — both are fine. Either way we drop our own reference. diff --git a/pkg/runtime/tls_server.odin b/pkg/runtime/tls_server.odin index a3b19d8f..6c5d01c3 100644 --- a/pkg/runtime/tls_server.odin +++ b/pkg/runtime/tls_server.odin @@ -33,7 +33,10 @@ TLS_Step :: enum { } tls_step :: proc(ssl: SSL, ret: c.int) -> TLS_Step { - if ret > 0 do return .Ok + if ret > 0 { + return .Ok + } + switch SSL_get_error(ssl, ret) { case SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE: return .Want_IO @@ -60,15 +63,26 @@ tls_no_password_cb :: proc "c" (buf: rawptr, size: c.int, rwflag: c.int, u: rawp // is where a Node caller's try/catch expects bad-cert errors). The returned ctx is owned by the // caller and freed with tls_server_ctx_free on server close. tls_server_ctx_new :: proc(key: []byte, cert: []byte) -> (ctx: SSL_CTX, ok: bool) { - if len(key) == 0 || len(cert) == 0 do return nil, false + if len(key) == 0 || len(cert) == 0 { + return nil, false + } + method := TLS_server_method() - if method == nil do return nil, false + + if method == nil { + return nil, false + } + // Build into an explicit local so the cleanup frees the LIVE handle: a named-return + early // `return nil, false` would assign ctx=nil BEFORE the defer runs, so the defer would free nil and // leak the context. Every failure below is a bare `return` (ctx stays nil, ok stays false) and // `c` is freed by the defer; only success assigns ctx = c. Mirrors the client builder. c := SSL_CTX_new(method) - if c == nil do return nil, false + + if c == nil { + return nil, false + } + defer if !ok { SSL_CTX_free(c) ERR_clear_error() // PEM end-of-stream leaves a benign error on the queue; don't strand it @@ -78,15 +92,24 @@ tls_server_ctx_new :: proc(key: []byte, cert: []byte) -> (ctx: SSL_CTX, ok: bool // peer renegotiation, suppress tickets (resumption is deferred — keep it honest + bounded), // and release per-SSL buffers when idle so many keep-alive conns stay cheap. SSL_CTX_set_options // is a real function (a ctrl(OPTIONS) is a silent no-op on OpenSSL ≥ 1.1.0 — see tls.odin). - if SSL_CTX_ctrl(c, SSL_CTRL_SET_MIN_PROTO_VERSION, TLS1_2_VERSION, nil) != 1 do return + if SSL_CTX_ctrl(c, SSL_CTRL_SET_MIN_PROTO_VERSION, TLS1_2_VERSION, nil) != 1 { + return + } + SSL_CTX_set_options(c, SSL_OP_NO_RENEGOTIATION | SSL_OP_NO_TICKET) SSL_CTX_set_num_tickets(c, 0) // TLS 1.3 tickets (the SSL_OP_NO_TICKET above is TLS 1.2 only) SSL_CTX_ctrl(c, SSL_CTRL_SET_SESS_CACHE_MODE, SSL_SESS_CACHE_OFF, nil) SSL_CTX_ctrl(c, SSL_CTRL_MODE, SSL_MODE_RELEASE_BUFFERS, nil) - if !tls_server_load_cert_chain(c, cert) do return - if !tls_server_load_key(c, key) do return - if SSL_CTX_check_private_key(c) != 1 do return // key must match the leaf cert + if !tls_server_load_cert_chain(c, cert) { + return + } + + if !tls_server_load_key(c, key) { + return + } + + if SSL_CTX_check_private_key(c) != 1 {return} // key must match the leaf cert ERR_clear_error() ctx = c @@ -95,7 +118,9 @@ tls_server_ctx_new :: proc(key: []byte, cert: []byte) -> (ctx: SSL_CTX, ok: bool } tls_server_ctx_free :: proc(ctx: SSL_CTX) { - if ctx != nil do SSL_CTX_free(ctx) + if ctx != nil { + SSL_CTX_free(ctx) + } } // tls_server_load_cert_chain reads every X509 in the PEM: the first is the leaf @@ -104,22 +129,36 @@ tls_server_ctx_free :: proc(ctx: SSL_CTX) { @(private = "file") tls_server_load_cert_chain :: proc(ctx: SSL_CTX, cert: []byte) -> bool { bio := BIO_new_mem_buf(raw_data(cert), c.int(len(cert))) - if bio == nil do return false + + if bio == nil { + return false + } + defer BIO_free(bio) leaf := PEM_read_bio_X509(bio, nil, tls_no_password_cb, nil) - if leaf == nil do return false + + if leaf == nil { + return false + } + used := SSL_CTX_use_certificate(ctx, leaf) == 1 X509_free(leaf) // ctx holds its own ref now - if !used do return false + + if !used { + return false + } for { x := PEM_read_bio_X509(bio, nil, tls_no_password_cb, nil) - if x == nil do break // no more certs (end-of-stream leaves a benign error, cleared by the caller) + + if x == nil {break} // no more certs (end-of-stream leaves a benign error, cleared by the caller) + if SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, rawptr(x)) != 1 { X509_free(x) return false } + // owned by ctx now — must NOT free } return true @@ -128,10 +167,15 @@ tls_server_load_cert_chain :: proc(ctx: SSL_CTX, cert: []byte) -> bool { @(private = "file") tls_server_load_key :: proc(ctx: SSL_CTX, key: []byte) -> bool { bio := BIO_new_mem_buf(raw_data(key), c.int(len(key))) - if bio == nil do return false + + if bio == nil { + return false + } + defer BIO_free(bio) pkey := PEM_read_bio_PrivateKey(bio, nil, tls_no_password_cb, nil) - if pkey == nil do return false // bad PEM, or encrypted (tls_no_password_cb fails it closed) + + if pkey == nil {return false} // bad PEM, or encrypted (tls_no_password_cb fails it closed) used := SSL_CTX_use_PrivateKey(ctx, pkey) == 1 EVP_PKEY_free(pkey) // ctx holds its own ref now return used @@ -144,15 +188,27 @@ tls_server_load_key :: proc(ctx: SSL_CTX, key: []byte) -> bool { // accept state. Returns false if any allocation fails (the caller closes the conn). tls_server_attach :: proc(conn: ^Net_Connection, ctx: SSL_CTX) -> bool { ssl := SSL_new(ctx) - if ssl == nil do return false + + if ssl == nil { + return false + } + rbio := BIO_new(BIO_s_mem()) wbio := BIO_new(BIO_s_mem()) + if rbio == nil || wbio == nil { - if rbio != nil do BIO_free(rbio) - if wbio != nil do BIO_free(wbio) + if rbio != nil { + BIO_free(rbio) + } + + if wbio != nil { + BIO_free(wbio) + } + SSL_free(ssl) return false } + SSL_set0_rbio(ssl, rbio) // ownership → ssl SSL_set0_wbio(ssl, wbio) SSL_set_accept_state(ssl) @@ -174,6 +230,7 @@ tls_server_free_conn :: proc(conn: ^Net_Connection) { conn.rbio = nil conn.wbio = nil } + if conn.handshake_timer != 0 { eventloop.clear_timeout(conn.loop, conn.handshake_timer) conn.handshake_timer = 0 @@ -196,21 +253,35 @@ tls_server_cancel_handshake_timer :: proc(conn: ^Net_Connection) { // net_flush. Called after EVERY SSL op — this is the C1 invariant. tls_pump_wbio :: proc(conn: ^Net_Connection) { wbio := cast(BIO)conn.wbio - if wbio == nil do return + + if wbio == nil { + return + } + proactor := net_is_proactor(conn) - if !proactor do net_compact_write_queue(conn) // drop the sent prefix before appending ciphertext + + if !proactor {net_compact_write_queue(conn)} // drop the sent prefix before appending ciphertext wrote := false chunk: [16384]byte for { n := BIO_read(wbio, raw_data(chunk[:]), c.int(len(chunk))) - if n <= 0 do break - if proactor do append(&conn.pending_writes, ..chunk[:int(n)]) - else do append(&conn.write_queue, ..chunk[:int(n)]) + + if n <= 0 { + break + } + + if proactor {append(&conn.pending_writes, ..chunk[:int(n)])} else { + append(&conn.write_queue, ..chunk[:int(n)]) + } + wrote = true } - if !wrote do return // nothing produced: don't kick/flush (a stray net_flush could fire end_after_drain) - if proactor do net_proactor_kick_send(conn) - else do net_flush(conn) + + if !wrote {return} // nothing produced: don't kick/flush (a stray net_flush could fire end_after_drain) + + if proactor {net_proactor_kick_send(conn)} else { + net_flush(conn) + } } // tls_server_on_ciphertext is the recv-side driver: feed inbound ciphertext to the rbio, then @@ -218,15 +289,25 @@ tls_pump_wbio :: proc(conn: ^Net_Connection) { // (proactor single-shot / ring / readiness) when conn.tls. The caller re-arms the recv after. tls_server_on_ciphertext :: proc(conn: ^Net_Connection, cipher: []byte) { rbio := cast(BIO)conn.rbio - if rbio == nil do return + + if rbio == nil { + return + } + if len(cipher) > 0 { BIO_write(rbio, raw_data(cipher), c.int(len(cipher))) // copies into the mem BIO } + if conn.tls_handshaking { - if !tls_server_do_handshake(conn) do return // not yet complete, closed, or fatal - if conn.closing do return + if !tls_server_do_handshake(conn) {return} // not yet complete, closed, or fatal + + if conn.closing { + return + } + // handshake just completed — fall through to drain any 0.5-RTT / pipelined app data } + tls_server_read_loop(conn) } @@ -239,7 +320,11 @@ tls_server_do_handshake :: proc(conn: ^Net_Connection) -> (done: bool) { ret := SSL_accept(ssl) step := tls_step(ssl, ret) // capture before any BIO op tls_pump_wbio(conn) // send whatever handshake records SSL_accept produced - if conn.closing do return false + + if conn.closing { + return false + } + if ret == 1 { conn.tls_handshaking = false tls_server_cancel_handshake_timer(conn) @@ -261,8 +346,14 @@ tls_server_do_handshake :: proc(conn: ^Net_Connection) -> (done: bool) { // it, ciphertext already sitting in the rbio (userspace, not the kernel socket buffer) would strand // with no future recv completion to drive it. A no-op when nothing is buffered (SSL_read → WANT_READ). tls_server_pump_reads :: proc(conn: ^Net_Connection) { - if !conn.tls || conn.closing || conn.read_done || conn.tls_handshaking do return - if conn.ssl == nil do return + if !conn.tls || conn.closing || conn.read_done || conn.tls_handshaking { + return + } + + if conn.ssl == nil { + return + } + tls_server_read_loop(conn) } @@ -283,19 +374,26 @@ tls_server_read_loop :: proc(conn: ^Net_Connection) { buf: [16384]byte for { n := SSL_read(ssl, raw_data(buf[:]), c.int(len(buf))) + if n > 0 { copy_buf := make([]byte, int(n), runtime.heap_allocator()) // freed by jsc_buffer_deallocator, on the heap copy(copy_buf, buf[:int(n)]) arg := make_uint8_array(conn.ctx, copy_buf) net_emit(conn.ctx, conn.on_data, &arg, 1) tls_pump_wbio(conn) // a record produced during SSL_read (e.g. KeyUpdate reply) must go out - if conn.closing do return // a data handler destroyed us, or the pump's send failed - if conn.want_drain || conn.writing do return // backpressure: resume via pump_reads on drain + + if conn.closing {return} // a data handler destroyed us, or the pump's send failed + + if conn.want_drain || conn.writing {return} // backpressure: resume via pump_reads on drain continue } + step := tls_step(ssl, n) // capture before the pump tls_pump_wbio(conn) // drain replies even on WANT_READ - if conn.closing do return + + if conn.closing { + return + } #partial switch step { case .Want_IO: return // need more ciphertext @@ -318,13 +416,19 @@ tls_server_read_loop :: proc(conn: ^Net_Connection) { // single call suffices. Returns false if the session is closing/failed. The backpressure gate is // applied by the caller against the BUFFERED CIPHERTEXT, identical to the plaintext path. tls_server_write :: proc(conn: ^Net_Connection, plaintext: []byte) -> bool { - if len(plaintext) == 0 do return !conn.closing + if len(plaintext) == 0 { + return !conn.closing + } + ssl := cast(SSL)conn.ssl ERR_clear_error() // clear cross-conn error-queue residue before classifying (see tls_server_read_loop) n := SSL_write(ssl, raw_data(plaintext), c.int(len(plaintext))) step := tls_step(ssl, n) // capture before the pump tls_pump_wbio(conn) - if conn.closing do return false + + if conn.closing { + return false + } #partial switch step { case .Ok: return true @@ -347,7 +451,10 @@ tls_server_write :: proc(conn: ^Net_Connection, plaintext: []byte) -> bool { // — no new timer, no reuse of the loop-level drain machinery. A still-handshaking conn has no // session to shut down (the caller falls straight through to the hard close). tls_server_begin_close :: proc(conn: ^Net_Connection) { - if conn.ssl == nil || conn.tls_handshaking do return + if conn.ssl == nil || conn.tls_handshaking { + return + } + SSL_shutdown(cast(SSL)conn.ssl) tls_pump_wbio(conn) } @@ -375,28 +482,46 @@ https_create_secure_context_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() + if argument_count < 2 { - if exception != nil do exception^ = make_js_error(ctx, "https.createServer requires both `key` and `cert`") + if exception != nil { + exception^ = make_js_error(ctx, "https.createServer requires both `key` and `cert`") + } + return jsc.JSValueMakeUndefined(ctx) } + args := arguments[:int(argument_count)] state := get_state_from_ctx(ctx) + if state == nil { - if exception != nil do exception^ = make_js_error(ctx, "https: no event loop is bound to this context") + if exception != nil { + exception^ = make_js_error(ctx, "https: no event loop is bound to this context") + } + return jsc.JSValueMakeUndefined(ctx) } + key, key_alloc := jsc_value_to_string_or_default(ctx, args[0]) - defer if key_alloc do delete(key, context.allocator) + defer if key_alloc { + delete(key, context.allocator) + } cert, cert_alloc := jsc_value_to_string_or_default(ctx, args[1]) - defer if cert_alloc do delete(cert, context.allocator) + defer if cert_alloc { + delete(cert, context.allocator) + } ssl_ctx, ok := tls_server_ctx_new(transmute([]byte)key, transmute([]byte)cert) + if !ok { // ERR_TLS_*-shaped: a bad/mismatched/encrypted key or cert. Surfaced synchronously so a // caller's try/catch around https.createServer sees it (design §5). - if exception != nil do exception^ = make_js_error(ctx, "https.createServer: invalid TLS key or certificate (ERR_TLS_CERT)") + if exception != + nil {exception^ = make_js_error(ctx, "https.createServer: invalid TLS key or certificate (ERR_TLS_CERT)")} + return jsc.JSValueMakeUndefined(ctx) } + id := state.next_net_id state.next_net_id += 1 state.tls_server_ctxs[id] = rawptr(ssl_ctx) @@ -415,13 +540,23 @@ https_free_secure_context_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeUndefined(ctx) + + if argument_count < 1 { + return jsc.JSValueMakeUndefined(ctx) + } + state := get_state_from_ctx(ctx) - if state == nil do return jsc.JSValueMakeUndefined(ctx) + + if state == nil { + return jsc.JSValueMakeUndefined(ctx) + } + id := u64(jsc.JSValueToNumber(ctx, arguments[0], nil)) + if ssl_ctx, ok := state.tls_server_ctxs[id]; ok { tls_server_ctx_free(cast(SSL_CTX)ssl_ctx) delete_key(&state.tls_server_ctxs, id) } + return jsc.JSValueMakeUndefined(ctx) } diff --git a/pkg/runtime/tty.odin b/pkg/runtime/tty.odin index 6eb14ee9..3c8555df 100644 --- a/pkg/runtime/tty.odin +++ b/pkg/runtime/tty.odin @@ -26,9 +26,17 @@ tty_isatty_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { context = runtime.default_context() - if argument_count < 1 do return jsc.JSValueMakeBoolean(ctx, false) + + if argument_count < 1 { + return jsc.JSValueMakeBoolean(ctx, false) + } + fd := jsc.JSValueToNumber(ctx, arguments[0], nil) + // NaN / negative / non-integral fds are not terminals. - if fd < 0 || fd != f64(int(fd)) do return jsc.JSValueMakeBoolean(ctx, false) + if fd < 0 || fd != f64(int(fd)) { + return jsc.JSValueMakeBoolean(ctx, false) + } + return jsc.JSValueMakeBoolean(ctx, b32(tty_fd_isatty(int(fd)))) } diff --git a/pkg/runtime/typed_array.odin b/pkg/runtime/typed_array.odin index ee653d0d..be8169d0 100644 --- a/pkg/runtime/typed_array.odin +++ b/pkg/runtime/typed_array.odin @@ -50,21 +50,37 @@ g_bytes_ptr_mode: BytesPtr_Mode // written once per thread after first offset vi typed_array_view :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> ([]byte, bool) { // Direct cell read (Uint8Array of any Structure, byteOffset pre-applied) — // zero C-API calls. Other view types and DataView fall through. - if data, ok := jsc.typed_array_bytes(ctx, value); ok do return data, true + if data, ok := jsc.typed_array_bytes(ctx, value); ok { + return data, true + } + + if jsc.JSValueGetTypedArrayType(ctx, value, nil) == .None { + return nil, false + } - if jsc.JSValueGetTypedArrayType(ctx, value, nil) == .None do return nil, false obj := cast(jsc.JSObjectRef)value n := int(jsc.JSObjectGetTypedArrayByteLength(ctx, obj, nil)) - if n == 0 do return nil, true + + if n == 0 { + return nil, true + } ptr := jsc.JSObjectGetTypedArrayBytesPtr(ctx, obj, nil) offset := int(jsc.JSObjectGetTypedArrayByteOffset(ctx, obj, nil)) if ptr == nil { buffer := jsc.JSObjectGetTypedArrayBuffer(ctx, obj, nil) - if buffer == nil do return nil, false + + if buffer == nil { + return nil, false + } + base := jsc.JSObjectGetArrayBufferBytesPtr(ctx, buffer, nil) - if base == nil do return nil, false + + if base == nil { + return nil, false + } + return (cast([^]byte)base)[offset:][:n], true } @@ -73,9 +89,11 @@ typed_array_view :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> ([]byt } mode := g_bytes_ptr_mode + if mode == .Unknown { buffer := jsc.JSObjectGetTypedArrayBuffer(ctx, obj, nil) base := buffer != nil ? jsc.JSObjectGetArrayBufferBytesPtr(ctx, buffer, nil) : nil + if base != nil { if ptr == base { mode = .Base_Plus_Offset @@ -85,6 +103,7 @@ typed_array_view :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> ([]byt // Unexpected — use ArrayBuffer base + offset (always correct). return (cast([^]byte)base)[offset:][:n], true } + g_bytes_ptr_mode = mode } else { // Cannot probe; assume gtk layout (base + offset). @@ -96,6 +115,7 @@ typed_array_view :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> ([]byt if mode == .View_Start { return (cast([^]byte)ptr)[:n], true } + // Base_Plus_Offset (and default): BytesPtr is the buffer base. return (cast([^]byte)ptr)[offset:][:n], true } @@ -108,7 +128,10 @@ typed_array_view :: proc(ctx: jsc.JSContextRef, value: jsc.JSValueRef) -> ([]byt // reset (the CLI's is the heap, so only embedders see the mismatch). jsc_buffer_deallocator :: proc "c" (bytes: rawptr, deallocator_context: rawptr) { context = runtime.default_context() - if bytes != nil do free(bytes) + + if bytes != nil { + free(bytes) + } } // make_uint8_array hands a byte slice from runtime.heap_allocator() to JavaScriptCore @@ -118,11 +141,13 @@ jsc_buffer_deallocator :: proc "c" (bytes: rawptr, deallocator_context: rawptr) make_uint8_array :: proc(ctx: jsc.JSContextRef, data: []byte) -> jsc.JSValueRef { ptr := raw_data(data) n := len(data) + if ptr == nil { pad := make([]byte, 1, runtime.heap_allocator()) ptr = raw_data(pad) n = 0 } + // No free on a nil return: JSC already ran jsc_buffer_deallocator (see // make_uint8_array_uninit). array := jsc.make_uint8_nocopy_locked(ctx, ptr, c.size_t(n), jsc_buffer_deallocator) @@ -140,11 +165,22 @@ MAX_UNINIT_ALLOC :: 0x7fff_ffff // 2^31 - 1 bytes // with the deallocator as its destructor before the typed array is created, so a // failed create drops that buffer and frees them. Deleting again is a double free. make_uint8_array_uninit :: proc(ctx: jsc.JSContextRef, size: int) -> (jsc.JSValueRef, bool) { - if size <= 0 || size > MAX_UNINIT_ALLOC do return nil, false + if size <= 0 || size > MAX_UNINIT_ALLOC { + return nil, false + } + heap := runtime.heap_allocator() data, err := mem.alloc_bytes_non_zeroed(size, mem.DEFAULT_ALIGNMENT, heap) - if err != nil || len(data) != size do return nil, false + + if err != nil || len(data) != size { + return nil, false + } + array := jsc.make_uint8_nocopy_locked(ctx, raw_data(data), c.size_t(size), jsc_buffer_deallocator) - if array == nil do return nil, false + + if array == nil { + return nil, false + } + return cast(jsc.JSValueRef)array, true } diff --git a/pkg/runtime/workers.odin b/pkg/runtime/workers.odin index d98ada98..1a8b57dc 100644 --- a/pkg/runtime/workers.odin +++ b/pkg/runtime/workers.odin @@ -28,25 +28,44 @@ lava_resolve_worker_count :: proc() -> (count: int, ok: bool, msg: string) { // degrade: malformed / partial (e.g. "0x10", "1_0", trailing junk) / 0 / negative / oversized, or // LAVA_WORKERS>1 on a non-Linux platform (multi-worker needs SO_REUSEPORT/signalfd/io_uring — Linux only). lava_parse_worker_count :: proc(raw: string, has_env: bool, cpu_count: int) -> (count: int, ok: bool, msg: string) { - if !has_env || raw == "" || raw == "1" do return 1, true, "" + if !has_env || raw == "" || raw == "1" { + return 1, true, "" + } n: int + if raw == "auto" { n = cpu_count - if n < 1 do n = 1 + + if n < 1 { + n = 1 + } } else { // Base 10 explicitly + require the WHOLE string consumed, so "0x10" is not reinterpreted as hex // and trailing junk ("10abc") is rejected rather than partially parsed. (parse_int still accepts // an underscore separator, so "1_0" -> 10 — benign, still bounded by [1,256].) consumed: int parsed, pok := strconv.parse_int(raw, 10, &consumed) - if !pok || consumed != len(raw) do return 0, false, "LAVA_WORKERS must be a positive integer or 'auto'" + + if !pok || consumed != len(raw) { + return 0, false, "LAVA_WORKERS must be a positive integer or 'auto'" + } + n = parsed } - if n < 1 do return 0, false, "LAVA_WORKERS must be >= 1" - if n > LAVA_WORKERS_MAX do return 0, false, "LAVA_WORKERS exceeds the maximum of 256" + + if n < 1 { + return 0, false, "LAVA_WORKERS must be >= 1" + } + + if n > LAVA_WORKERS_MAX { + return 0, false, "LAVA_WORKERS exceeds the maximum of 256" + } + when ODIN_OS != .Linux { - if n > 1 do return 0, false, "multi-worker (LAVA_WORKERS > 1) is supported only on Linux" + if n > 1 { + return 0, false, "multi-worker (LAVA_WORKERS > 1) is supported only on Linux" + } } return n, true, "" } @@ -110,7 +129,11 @@ barrier_maybe_decide :: proc(b: ^Worker_Barrier) { barrier_settle :: proc(b: ^Worker_Barrier, failed: bool) { sync.lock(&b.mutex) defer sync.unlock(&b.mutex) - if failed do b.any_failed = true + + if failed { + b.any_failed = true + } + b.reported += 1 barrier_maybe_decide(b) sync.cond_broadcast(&b.cond) @@ -124,7 +147,9 @@ barrier_ready_wait :: proc(b: ^Worker_Barrier) -> bool { b.reported += 1 barrier_maybe_decide(b) sync.cond_broadcast(&b.cond) - for !b.decided do sync.cond_wait(&b.cond, &b.mutex) + for !b.decided { + sync.cond_wait(&b.cond, &b.mutex) + } return b.released } @@ -153,15 +178,20 @@ Worker :: struct { worker_pre_run :: proc(user_data: rawptr) -> bool { w := cast(^Worker)user_data w.reported = true + // A listener that failed to bind during startup aborts the whole startup (M7): report a failure so // the barrier releases everyone to abort, rather than reporting ready and serving partial capacity. if sync.atomic_load(&g_listen_failed) { barrier_settle(w.barrier, true) return false } + // Block at the barrier until all workers are ready (or one failed -> abort). Then proceed to run // UNLESS a shutdown was already requested — a signal during startup must not start serving. - if !barrier_ready_wait(w.barrier) do return false + if !barrier_ready_wait(w.barrier) { + return false + } + return !sync.atomic_load(&g_shutdown) } @@ -184,8 +214,13 @@ worker_main :: proc(data: rawptr) { sync.lock(&w.sig_mutex) w.loop = nil sync.unlock(&w.sig_mutex) - if !w.reported do barrier_settle(w.barrier, true) // eval failed before the ready hook - if w.result.backend_failed do sync.atomic_store(&g_worker_crashed, true) + + if !w.reported {barrier_settle(w.barrier, true)} // eval failed before the ready hook + + if w.result.backend_failed { + sync.atomic_store(&g_worker_crashed, true) + } + // This thread is about to end: give back its thread_local host-native tables, which nothing else // ever deletes. eval has already destroyed its context on every return path once one existed // (destroy_runtime_state -> host_natives_release_context), which is the teardown's precondition; @@ -201,10 +236,12 @@ worker_main :: proc(data: rawptr) { // spawn + the startup barrier + join, exercisable with a non-server script.) lava_run_workers :: proc(path: string, count: int, script_args: []string) -> int { data, err := os.read_entire_file(path, context.allocator) + if err != os.ERROR_NONE { process_write(os.stderr, "lava: could not read ", path, "\n") return 1 } + defer delete(data, context.allocator) source := string(data) @@ -230,6 +267,7 @@ lava_run_workers :: proc(path: string, count: int, script_args: []string) -> int barrier = &barrier, } t := thread.create_and_start_with_data(&workers[i], worker_main, nil, .Normal, false) + if t != nil { append(&threads, t) } else { @@ -256,6 +294,7 @@ lava_run_workers :: proc(path: string, count: int, script_args: []string) -> int // come up" must not be masked by a worker that happened to set process.exitCode. Otherwise the // first non-zero worker exit code wins. (Destroy every Result regardless.) code := 0 + if barrier.any_failed || sync.atomic_load(&g_worker_crashed) { code = 1 } else { @@ -266,6 +305,9 @@ lava_run_workers :: proc(path: string, count: int, script_args: []string) -> int } } } - for i in 0 ..< count do result_destroy(&workers[i].result) + + for i in 0 ..< count { + result_destroy(&workers[i].result) + } return code } diff --git a/pkg/runtime/workers_linux.odin b/pkg/runtime/workers_linux.odin index c3bdd1f4..0ce77443 100644 --- a/pkg/runtime/workers_linux.odin +++ b/pkg/runtime/workers_linux.odin @@ -40,11 +40,15 @@ supervisor_wait :: proc(workers: []Worker) { time_nsec = SUPERVISOR_TICK_MS * 1_000_000, } _, err := linux.rt_sigtimedwait(&set, nil, &ts) - if err == .NONE do break // SIGINT/SIGTERM received -> graceful shutdown + + if err == .NONE {break} // SIGINT/SIGTERM received -> graceful shutdown + // EAGAIN (timeout) / EINTR: poll the worker-exit state. - if sync.atomic_load(&g_worker_crashed) do break // a worker died -> stop the rest - if sync.atomic_load(&g_worker_exits) >= n do return // all finished cleanly -> nothing to signal + if sync.atomic_load(&g_worker_crashed) {break} // a worker died -> stop the rest + + if sync.atomic_load(&g_worker_exits) >= n {return} // all finished cleanly -> nothing to signal } + // Signal every worker. g_shutdown first closes the startup-vs-signal race (a worker that publishes // its loop after this sweep sees g_shutdown in its pre-run hook and aborts). Then request_shutdown // each published loop UNDER the worker's sig_mutex: holding it across the read + the call keeps that @@ -53,7 +57,11 @@ supervisor_wait :: proc(workers: []Worker) { sync.atomic_store(&g_shutdown, true) for &w in workers { sync.lock(&w.sig_mutex) - if w.loop != nil do eventloop.request_shutdown(w.loop) + + if w.loop != nil { + eventloop.request_shutdown(w.loop) + } + sync.unlock(&w.sig_mutex) } } diff --git a/pkg/runtime/workers_test.odin b/pkg/runtime/workers_test.odin index f4ca433b..d2c5b23c 100644 --- a/pkg/runtime/workers_test.odin +++ b/pkg/runtime/workers_test.odin @@ -66,11 +66,13 @@ Barrier_Probe :: struct { @(private = "file") barrier_probe_run :: proc(data: rawptr) { p := cast(^Barrier_Probe)data + if p.fail { barrier_settle(p.barrier, true) } else { p.released = barrier_ready_wait(p.barrier) } + sync.atomic_store(&p.done, true) } @@ -91,7 +93,10 @@ run_barrier :: proc(t: ^testing.T, n_ready, n_fail: int) -> (released_all: bool, } th := thread.create_and_start_with_data(&probes[i], barrier_probe_run, nil, .Normal, false) testing.expect(t, th != nil, "probe thread spawned") - if th != nil do append(&threads, th) + + if th != nil { + append(&threads, th) + } } // join — this completes only if the barrier is deadlock-free (every reporter unblocked). for th in threads { @@ -99,7 +104,11 @@ run_barrier :: proc(t: ^testing.T, n_ready, n_fail: int) -> (released_all: bool, thread.destroy(th) } released_all = true - for i in 0 ..< n_ready do if !probes[i].released do released_all = false + for i in 0 ..< n_ready { + if !probes[i].released { + released_all = false + } + } return released_all, b.any_failed } @@ -148,7 +157,11 @@ workers_give_back_their_host_tables :: proc(t: ^testing.T) { // eval destroyed its context on every path, which is the teardown's precondition; harmless when // nothing bound. Leaving the runner thread's tables bound would offset every later count. host_native_thread_teardown() - if !testing.expectf(t, probe_exit == 0, "probe eval exit code %d", probe_exit) do return + + if !testing.expectf(t, probe_exit == 0, "probe eval exit code %d", probe_exit) { + return + } + if !bound { log.warnf( "SKIP workers_give_back_their_host_tables: an eval bound no host-native tables on this thread " + @@ -156,7 +169,14 @@ workers_give_back_their_host_tables :: proc(t: ^testing.T) { ) return } - if !testing.expectf(t, host_native_tables_live() == baseline, "probe teardown left %d tables live, want baseline %d", host_native_tables_live(), baseline) do return + + if !testing.expectf( + t, + host_native_tables_live() == baseline, + "probe teardown left %d tables live, want baseline %d", + host_native_tables_live(), + baseline, + ) {return} } barrier := Worker_Barrier { @@ -171,7 +191,10 @@ workers_give_back_their_host_tables :: proc(t: ^testing.T) { barrier = &barrier, } threads[i] = thread.create_and_start_with_data(&workers[i], worker_main, nil, .Normal, false) - if !testing.expect(t, threads[i] != nil, "thread create failed") do return + + if !testing.expect(t, threads[i] != nil, "thread create failed") { + return + } } for th in threads { thread.join(th) diff --git a/pkg/std/sqlite/sqlite.odin b/pkg/std/sqlite/sqlite.odin index c94ffef0..f43c080e 100644 --- a/pkg/std/sqlite/sqlite.odin +++ b/pkg/std/sqlite/sqlite.odin @@ -128,18 +128,21 @@ open :: proc(path: string) -> (Database, Result) { if len(path) == 0 { return Database{}, Result{status = .Invalid_Input, message = "missing SQLite database path"} } + when !SQLITE_AVAILABLE { return Database{}, unavailable() } else { cpath := strings.clone_to_cstring(path, context.temp_allocator) handle: rawptr rc := sqlite3_open(cpath, &handle) + if rc != SQLITE_OK { // sqlite3_open returns a handle even on failure, and the real error text // is only reachable through it. errmsg is borrowed and invalidated by // close, so clone it (into temp, like the bridge's other error paths) // before closing the handle. msg := "could not open database" + if handle != nil { if detail := sqlite3_errmsg(handle); detail != nil { if cloned, err := strings.clone(string(detail), context.temp_allocator); @@ -147,10 +150,13 @@ open :: proc(path: string) -> (Database, Result) { msg = cloned } } + sqlite3_close_v2(handle) } + return Database{}, Result{status = .Error, message = msg} } + return Database{handle = handle, is_open = true}, Result{status = .Ok} } } @@ -161,6 +167,7 @@ close :: proc(db: ^Database) { sqlite3_close_v2(db.handle) } } + if db != nil { db.handle = nil db.is_open = false @@ -171,19 +178,23 @@ exec :: proc(db: ^Database, sql: string) -> Result { if db == nil || !db.is_open { return Result{status = .Invalid_Input, message = "database is not open"} } + // Empty SQL is a no-op, matching node:sqlite (`db.exec('')`); sqlite3_exec on // an empty/whitespace string also returns SQLITE_OK without running anything. if len(sql) == 0 { return Result{status = .Ok} } + when !SQLITE_AVAILABLE { return unavailable() } else { csql := strings.clone_to_cstring(sql, context.temp_allocator) rc := sqlite3_exec(db.handle, csql, nil, nil, nil) + if rc != SQLITE_OK { return Result{status = .Error, message = "exec failed"} } + return Result{status = .Ok} } } @@ -192,6 +203,7 @@ prepare :: proc(db: ^Database, sql: string) -> (Statement, Result) { if db == nil || !db.is_open { return Statement{}, Result{status = .Invalid_Input, message = "database is not open"} } + when !SQLITE_AVAILABLE { return Statement{}, unavailable() } else { @@ -202,9 +214,11 @@ prepare :: proc(db: ^Database, sql: string) -> (Statement, Result) { // (verified against Node 26.13.0 — `prepare("SELECT 1; SELECT 2")` runs SELECT 1), // which is more permissive than better-sqlite3's "one statement only" error. rc := sqlite3_prepare_v2(db.handle, csql, -1, &handle, nil) + if rc != SQLITE_OK || handle == nil { return Statement{}, Result{status = .Error, message = "prepare failed"} } + return Statement{handle = handle}, Result{status = .Ok} } } @@ -213,7 +227,10 @@ step :: proc(stmt: ^Statement) -> Step_Result { when !SQLITE_AVAILABLE { return .Error } else { - if stmt == nil || stmt.handle == nil do return .Error + if stmt == nil || stmt.handle == nil { + return .Error + } + rc := sqlite3_step(stmt.handle) switch rc { case SQLITE_ROW: @@ -242,14 +259,20 @@ finalize :: proc(stmt: ^Statement) { sqlite3_finalize(stmt.handle) } } - if stmt != nil do stmt.handle = nil + + if stmt != nil { + stmt.handle = nil + } } column_count :: proc(stmt: ^Statement) -> int { when !SQLITE_AVAILABLE { return 0 } else { - if stmt == nil || stmt.handle == nil do return 0 + if stmt == nil || stmt.handle == nil { + return 0 + } + return int(sqlite3_column_count(stmt.handle)) } } @@ -259,7 +282,10 @@ column_name :: proc(stmt: ^Statement, i: int) -> string { when !SQLITE_AVAILABLE { return "" } else { - if stmt == nil || stmt.handle == nil do return "" + if stmt == nil || stmt.handle == nil { + return "" + } + return string(sqlite3_column_name(stmt.handle, c.int(i))) } } @@ -268,7 +294,10 @@ column_type :: proc(stmt: ^Statement, i: int) -> Column_Type { when !SQLITE_AVAILABLE { return .Null } else { - if stmt == nil || stmt.handle == nil do return .Null + if stmt == nil || stmt.handle == nil { + return .Null + } + switch sqlite3_column_type(stmt.handle, c.int(i)) { case SQLITE_INTEGER: return .Integer @@ -287,7 +316,10 @@ column_int :: proc(stmt: ^Statement, i: int) -> i64 { when !SQLITE_AVAILABLE { return 0 } else { - if stmt == nil || stmt.handle == nil do return 0 + if stmt == nil || stmt.handle == nil { + return 0 + } + return sqlite3_column_int64(stmt.handle, c.int(i)) } } @@ -296,7 +328,10 @@ column_double :: proc(stmt: ^Statement, i: int) -> f64 { when !SQLITE_AVAILABLE { return 0 } else { - if stmt == nil || stmt.handle == nil do return 0 + if stmt == nil || stmt.handle == nil { + return 0 + } + return sqlite3_column_double(stmt.handle, c.int(i)) } } @@ -306,9 +341,16 @@ column_text :: proc(stmt: ^Statement, i: int) -> string { when !SQLITE_AVAILABLE { return "" } else { - if stmt == nil || stmt.handle == nil do return "" + if stmt == nil || stmt.handle == nil { + return "" + } + ptr := sqlite3_column_text(stmt.handle, c.int(i)) - if ptr == nil do return "" + + if ptr == nil { + return "" + } + n := int(sqlite3_column_bytes(stmt.handle, c.int(i))) return string(ptr[:n]) } @@ -319,10 +361,17 @@ column_blob :: proc(stmt: ^Statement, i: int) -> []byte { when !SQLITE_AVAILABLE { return nil } else { - if stmt == nil || stmt.handle == nil do return nil + if stmt == nil || stmt.handle == nil { + return nil + } + ptr := sqlite3_column_blob(stmt.handle, c.int(i)) n := int(sqlite3_column_bytes(stmt.handle, c.int(i))) - if ptr == nil || n == 0 do return nil + + if ptr == nil || n == 0 { + return nil + } + return (cast([^]byte)ptr)[:n] } } @@ -331,7 +380,10 @@ bind_parameter_count :: proc(stmt: ^Statement) -> int { when !SQLITE_AVAILABLE { return 0 } else { - if stmt == nil || stmt.handle == nil do return 0 + if stmt == nil || stmt.handle == nil { + return 0 + } + return int(sqlite3_bind_parameter_count(stmt.handle)) } } @@ -344,9 +396,16 @@ bind_parameter_name :: proc(stmt: ^Statement, index: int) -> string { when !SQLITE_AVAILABLE { return "" } else { - if stmt == nil || stmt.handle == nil do return "" + if stmt == nil || stmt.handle == nil { + return "" + } + name := sqlite3_bind_parameter_name(stmt.handle, c.int(index)) - if name == nil do return "" + + if name == nil { + return "" + } + return string(name) } } @@ -357,7 +416,10 @@ bind_parameter_name :: proc(stmt: ^Statement, index: int) -> string { // unbound. The message borrows sqlite's static errstr text (no free needed). bind_result :: proc(rc: c.int) -> Result { when SQLITE_AVAILABLE { - if rc == SQLITE_OK do return Result{status = .Ok} + if rc == SQLITE_OK { + return Result{status = .Ok} + } + text := sqlite3_errstr(rc) return Result{status = .Error, message = text != nil ? string(text) : "bind failed"} } else { @@ -373,6 +435,7 @@ bind_int :: proc(stmt: ^Statement, index: int, value: i64) -> Result { if stmt == nil || stmt.handle == nil { return Result{status = .Invalid_Input, message = "statement is not prepared"} } + return bind_result(sqlite3_bind_int64(stmt.handle, c.int(index), value)) } } @@ -384,6 +447,7 @@ bind_double :: proc(stmt: ^Statement, index: int, value: f64) -> Result { if stmt == nil || stmt.handle == nil { return Result{status = .Invalid_Input, message = "statement is not prepared"} } + return bind_result(sqlite3_bind_double(stmt.handle, c.int(index), value)) } } @@ -395,6 +459,7 @@ bind_null :: proc(stmt: ^Statement, index: int) -> Result { if stmt == nil || stmt.handle == nil { return Result{status = .Invalid_Input, message = "statement is not prepared"} } + return bind_result(sqlite3_bind_null(stmt.handle, c.int(index))) } } @@ -406,6 +471,7 @@ bind_text :: proc(stmt: ^Statement, index: int, value: string) -> Result { if stmt == nil || stmt.handle == nil { return Result{status = .Invalid_Input, message = "statement is not prepared"} } + // Explicit length (not strlen): an embedded NUL is a legal byte in SQLite // TEXT, so the whole slice is bound, not just up to the first NUL. cval := strings.clone_to_cstring(value, context.temp_allocator) @@ -433,6 +499,7 @@ bind_blob :: proc(stmt: ^Statement, index: int, value: []byte) -> Result { if stmt == nil || stmt.handle == nil { return Result{status = .Invalid_Input, message = "statement is not prepared"} } + empty: byte ptr := len(value) > 0 ? rawptr(raw_data(value)) : rawptr(&empty) return bind_result(sqlite3_bind_blob(stmt.handle, c.int(index), ptr, c.int(len(value)), sqlite_transient())) @@ -443,7 +510,10 @@ changes :: proc(db: ^Database) -> i64 { when !SQLITE_AVAILABLE { return 0 } else { - if db == nil || db.handle == nil do return 0 + if db == nil || db.handle == nil { + return 0 + } + return sqlite3_changes64(db.handle) } } @@ -452,7 +522,10 @@ last_insert_rowid :: proc(db: ^Database) -> i64 { when !SQLITE_AVAILABLE { return 0 } else { - if db == nil || db.handle == nil do return 0 + if db == nil || db.handle == nil { + return 0 + } + return sqlite3_last_insert_rowid(db.handle) } } @@ -462,9 +535,16 @@ errmsg :: proc(db: ^Database, allocator := context.allocator) -> string { when !SQLITE_AVAILABLE { return "" } else { - if db == nil || db.handle == nil do return "" + if db == nil || db.handle == nil { + return "" + } + msg := sqlite3_errmsg(db.handle) - if msg == nil do return "" + + if msg == nil { + return "" + } + cloned, _ := strings.clone(string(msg), allocator) return cloned } diff --git a/scripts/fmt-if.mjs b/scripts/fmt-if.mjs new file mode 100644 index 00000000..2e4f94d1 --- /dev/null +++ b/scripts/fmt-if.mjs @@ -0,0 +1,198 @@ +// Two layout rules no formatter here enforces, for Odin and C/C++ (CLAUDE.md §4): +// +// 1. A block opened on the same line as its `if`, `else`, `for`, `when` or `defer if` +// is spread over lines: `if x {return 2}` becomes three lines. odinfmt's convert_do +// turns `if x do y` into the one-line form, and clang-format's InsertBraces adds the +// braces in C, so after them every `if` has braces and this makes them multi-line. +// 2. An `if` statement has a blank line before and after it, unless it opens or closes +// a block or a case: a `{` or `case …:` line just above, a `}` or `case` just below. +// Comments directly above an `if` belong to it, so the blank line goes above them. +// +// Line-based on purpose: both rules are about lines, and a parser per language would be +// far more code than the rules. It tracks just enough lexical state to be safe — strings, +// runes, line and block comments, and Odin's multi-line raw strings (embedded JS in the +// tests is full of `if`) — and leaves any line it cannot read with confidence alone. +// +// Usage: node scripts/fmt-if.mjs ... (rewrites in place; idempotent) + +import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs'; +import { extname, join } from 'node:path'; + +const EXTS = new Set(['.odin', '.c', '.h', '.cpp', '.hpp']); +const BLOCK_KEYWORD = /^(\} else if |\} else \{|if |else |for |when |defer if |\} else when )/; + +/** + * Splits `line` into code characters and everything else, carrying multi-line state. + * Returns per-character flags `code[i]` (true outside strings and comments) and the + * state at the end of the line. + */ +function scan(line, state, isC) { + const code = new Array(line.length).fill(false); + let { raw, block } = state; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (raw) { + if (ch === '`') raw = false; + continue; + } + if (block) { + if (ch === '*' && line[i + 1] === '/') { + block = false; + i++; + } + continue; + } + if (ch === '/' && line[i + 1] === '/') break; + if (ch === '/' && line[i + 1] === '*') { + block = true; + i++; + continue; + } + if (ch === '`' && !isC) { + raw = true; + continue; + } + if (ch === '"' || ch === "'") { + const quote = ch; + for (i++; i < line.length && line[i] !== quote; i++) if (line[i] === '\\') i++; + continue; + } + code[i] = true; + } + return { code, state: { raw, block } }; +} + +function braceDelta(line, code) { + let d = 0; + for (let i = 0; i < line.length; i++) { + if (!code[i]) continue; + if (line[i] === '{') d++; + else if (line[i] === '}') d--; + } + return d; +} + +// Rule 1: `head {body}` on one line, where the closing brace is the line's last code +// character and matches a `{` that follows the keyword's condition. +function spreadOneLineBlock(line, code, indent) { + const t = line.trim(); + if (!BLOCK_KEYWORD.test(t) || !t.endsWith('}')) return null; + const end = line.lastIndexOf('}'); + if (!code[end]) return null; + let depth = 0; + let open = -1; + for (let i = end; i >= 0; i--) { + if (!code[i]) continue; + if (line[i] === '}') depth++; + else if (line[i] === '{' && --depth === 0) { + open = i; + break; + } + } + if (open < 0) return null; + const head = line.slice(0, open).trimEnd(); + const body = line.slice(open + 1, end).trim(); + // `} else if c {x}`: the head's own leading `}` closes an earlier block, fine. Bail on + // an empty body (`for {}` is deliberate) or several statements. + if (body === '' || body.includes(';')) return null; + if (head.trim() === '}' || head.trim() === '') return null; + return [`${head} {`, `${indent}\t${body}`, `${indent}}`]; +} + +const isBlank = (s) => s.trim() === ''; +const isComment = (s) => /^\s*(\/\/|\/\*|\*)/.test(s); +const opensOrLabels = (s) => { + const t = s.trim(); + return t.endsWith('{') || /^(case\b.*|default):\s*$/.test(t) || t.endsWith(':'); +}; +const closesOrLabels = (s) => { + const t = s.trim(); + return t.startsWith('}') || /^(case\b|default:)/.test(t) || t.startsWith('#'); +}; + +function formatSource(src, isC) { + const lines = src.split('\n'); + + // Pass 1: spread one-line blocks. Odin only: in C, clang-format already did it. + let out = []; + let state = { raw: false, block: false }; + for (const line of lines) { + const startState = state; + const { code, state: next } = scan(line, state, isC); + state = next; + const indent = line.match(/^\s*/)[0]; + const spread = !isC && !startState.raw && !startState.block ? spreadOneLineBlock(line, code, indent) : null; + out.push(...(spread ?? [line])); + } + + // Pass 2: blank lines around `if` statements. + const src2 = out; + const ifStart = isC ? /^if\s*\(/ : /^if /; + const result = []; + const blankAfter = new Set(); // indexes into src2 after which a blank line goes + state = { raw: false, block: false }; + const scans = src2.map((line) => { + const startState = state; + const r = scan(line, state, isC); + state = r.state; + return { code: r.code, inCode: !startState.raw && !startState.block }; + }); + + const blankBefore = new Set(); // indexes into src2 before which a blank line goes + for (let i = 0; i < src2.length; i++) { + const line = src2[i]; + if (!scans[i].inCode || !ifStart.test(line.trim())) continue; + // Before: skip up over comments attached to the if. + let top = i; + while (top > 0 && isComment(src2[top - 1]) && scans[top - 1].inCode) top--; + if (top > 0 && !isBlank(src2[top - 1]) && !opensOrLabels(src2[top - 1])) blankBefore.add(top); + // After: follow the braces to the end of the whole if/else chain. + let depth = 0; + let seenOpen = false; + let end = i; + for (let j = i; j < src2.length; j++) { + if (!scans[j].inCode) break; + depth += braceDelta(src2[j], scans[j].code); + if (src2[j].includes('{')) seenOpen = true; + end = j; + // The chain ends on a line that closes the last block: `}` (or a one-line block's + // `}`). `} else if a ||` continues it, and so does `} else {`. + if (seenOpen && depth <= 0 && src2[j].trim().endsWith('}')) break; + if (!seenOpen && isC && /;\s*$/.test(src2[j])) break; // braceless C statement + if (!seenOpen && !isC && / do /.test(src2[j])) break; // a `do` form odinfmt left + if (j - i > 2000) break; + } + if (end + 1 < src2.length && !isBlank(src2[end + 1]) && !closesOrLabels(src2[end + 1])) blankAfter.add(end); + } + + for (let i = 0; i < src2.length; i++) { + if (blankBefore.has(i) && !(result.length && isBlank(result[result.length - 1]))) result.push(''); + result.push(src2[i]); + if (blankAfter.has(i)) result.push(''); + } + return result.join('\n'); +} + +function walk(path, files) { + const st = statSync(path); + if (st.isDirectory()) { + for (const name of readdirSync(path)) { + if (name === 'picohttpparser' || name.startsWith('.') || name === 'node_modules') continue; + walk(join(path, name), files); + } + } else if (EXTS.has(extname(path))) files.push(path); +} + +const files = []; +for (const arg of process.argv.slice(2)) walk(arg, files); +let changed = 0; +for (const file of files) { + const src = readFileSync(file, 'utf8'); + const isC = extname(file) !== '.odin'; + const formatted = formatSource(src, isC); + if (formatted !== src) { + writeFileSync(file, formatted); + changed++; + } +} +console.log(`fmt-if: ${changed} of ${files.length} files changed`); diff --git a/tests/mutation-manifest.json b/tests/mutation-manifest.json index 58123aea..5dd74f19 100644 --- a/tests/mutation-manifest.json +++ b/tests/mutation-manifest.json @@ -113,7 +113,7 @@ "name": "run_until_idle_waits_out_a_stale_wakeup dies when a no-progress tick ends the drive", "why": "A surplus wakeup byte ends the drive with an off-loop completion still in flight, and it returns the did_work an earlier tick latched — so it reports success.", "source": "pkg/runtime/eventloop/loop.odin", - "find": "\t\t\tif loop.active_io_count == 0 && loop.active_async == 0 {\n\t\t\t\treturn did_work\n\t\t\t}\n\t\t\tcontinue", + "find": "\t\t\tif loop.active_io_count == 0 && loop.active_async == 0 {\n\t\t\t\treturn did_work\n\t\t\t}\n\n\t\t\tcontinue", "replace": "\t\t\treturn did_work", "gate": "odin:pkg/runtime/eventloop:eventloop.run_until_idle_waits_out_a_stale_wakeup", "expect_detail": "run_until_idle_waits_out_a_stale_wakeup" @@ -535,8 +535,8 @@ "name": "stdio-write dies when the writer stops retrying a partial/EAGAIN write", "why": "os.write abandons its loop on any errno and the old caller discarded n and err, so a full non-blocking pipe ended the write and reported success: console.log('x'.repeat(300000)) delivered 65536 bytes and exited 0. The flag is inherited from the parent, which is why an ordinary shell pipe never reproduces it. expect_detail keys off the assertion text, not the byte count: the truncated count depends on how fast the reader drains and was measured at both 65536 and 196608.", "source": "pkg/runtime/globals.odin", - "find": "\t\tif !stdio_retryable(werr) do return written, werr", - "replace": "\t\tif werr != nil do return written, werr", + "find": "\t\tif !stdio_retryable(werr) {\n\t\t\treturn written, werr\n\t\t}", + "replace": "\t\tif werr != nil {\n\t\t\treturn written, werr\n\t\t}", "gate": "node-test:tests/stdio/stdio-write.test.mjs", "expect_detail": [ "expected 300001 bytes", @@ -1182,7 +1182,7 @@ "name": "68-resizable-view-bytes dies when typed_array_bytes trusts m_length for every view mode", "why": "A length-tracking view stores 0 in m_length, so every native borrowing its bytes (TextDecoder, Buffer.compare, fs writes, sqlite binds) saw an empty view.", "source": "pkg/jsc/private_view.odin", - "find": "\t\tif mode != g_mode_fixed[0] && mode != g_mode_fixed[1] && mode != g_mode_fixed[2] do return nil, false\n", + "find": "\t\tif mode != g_mode_fixed[0] && mode != g_mode_fixed[1] && mode != g_mode_fixed[2] {\n\t\t\treturn nil, false\n\t\t}\n", "replace": "\t\t_ = mode\n", "gate": "compat:tests/node-compat/cases/68-resizable-view-bytes.js", "expect_detail": "auto: TextDecoder#decode" @@ -1254,8 +1254,8 @@ "name": "timer_binding_frees_through_its_own_allocator dies when a cleared binding is never freed", "why": "Bindings go through the owning state allocator, not a hard-coded heap, so a dispose path that stops freeing is visible to a tracking allocator as a live allocation instead of vanishing into malloc.", "source": "pkg/runtime/globals.odin", - "find": "\tif cb == nil do return\n\tfree_js_callback(cb)\n}", - "replace": "\tif cb == nil do return\n}", + "find": "\tif cb == nil {\n\t\treturn\n\t}\n\n\tfree_js_callback(cb)\n}", + "replace": "\tif cb == nil {\n\t\treturn\n\t}\n}", "gate": "odin:cmd/lava:main.timer_binding_frees_through_its_own_allocator", "expect_detail": "timer bindings leaked" }, @@ -1281,8 +1281,8 @@ "name": "timer_binding_frees_through_its_own_allocator dies when setTimeout makes bindings from the heap instead of the state allocator", "why": "A hard-coded heap pairs alloc and free just as well, so only the routing count can see it; it is what keeps a leaked binding visible to the embedder's allocator.", "source": "pkg/runtime/globals.odin", - "find": "loop, alloc := state.loop, state.allocator\n\n\tfn := callback_arg(ctx, arguments[0])\n\tif fn == nil do return jsc.JSValueMakeUndefined(ctx)\n\n\tdelay := 0.0", - "replace": "loop, alloc := state.loop, context.allocator\n\n\tfn := callback_arg(ctx, arguments[0])\n\tif fn == nil do return jsc.JSValueMakeUndefined(ctx)\n\n\tdelay := 0.0", + "find": "loop, alloc := state.loop, state.allocator\n\n\tfn := callback_arg(ctx, arguments[0])\n\n\tif fn == nil {\n\t\treturn jsc.JSValueMakeUndefined(ctx)\n\t}\n\n\tdelay := 0.0", + "replace": "loop, alloc := state.loop, context.allocator\n\n\tfn := callback_arg(ctx, arguments[0])\n\n\tif fn == nil {\n\t\treturn jsc.JSValueMakeUndefined(ctx)\n\t}\n\n\tdelay := 0.0", "gate": "odin:cmd/lava:main.timer_binding_frees_through_its_own_allocator", "expect_detail": "made through the state allocator" }, @@ -1571,7 +1571,7 @@ "name": "eval_reports_a_top_level_throw_before_teardown dies when eval's returns stop calling the report hook", "why": "Every return of eval and run_file goes through reported(); without the call, a caller that prints only from the hook (the CLI) prints nothing at all.", "source": "pkg/runtime/runtime.odin", - "find": "\tif report != nil do report(result, report_data)\n", + "find": "\tif report != nil {\n\t\treport(result, report_data)\n\t}\n", "replace": "", "gate": "odin:cmd/lava:main.eval_reports_a_top_level_throw_before_teardown", "expect_detail": "expected seen.calls to be 1, got 0" @@ -1591,8 +1591,8 @@ "name": "close_begin_cancels_a_running_job_without_waiting_for_it dies when close_begin skips the cancel hook of a running job", "why": "Without the cancel, a job's protected JS callback is unprotected only by its late dispose, after the page's context — or the runner's VM — is gone.", "source": "pkg/runtime/eventloop/threadpool.odin", - "find": "\t\t\tif job.cancel != nil do job.cancel(job.user_data)\n", - "replace": "", + "find": "\t\t\tif job.cancel != nil {\n\t\t\t\tjob.cancel(job.user_data)\n\t\t\t}\n\n\t\t\tbusy = true", + "replace": "\t\t\tbusy = true", "gate": "odin:pkg/runtime/eventloop:eventloop.close_begin_cancels_a_running_job_without_waiting_for_it", "expect_detail": "job.cancel) to be 1" }, @@ -2215,8 +2215,8 @@ "name": "builtin_factories_compile_on_first_require dies when compile matches the directory prefix loosely", "why": "compile(id) is the only gate between a caller-shaped id and the embedded file table; a suffix match lets 'node:node/os' answer as a second public spelling of node:os, the shape of drift that would also let an override build read a file the exact match never names.", "source": "pkg/runtime/globals.odin", - "find": "\t\tif dir.prefix != prefix do continue\n", - "replace": "\t\tif !strings.has_suffix(prefix, dir.prefix) do continue\n", + "find": "\t\tif dir.prefix != prefix {\n\t\t\tcontinue\n\t\t}\n", + "replace": "\t\tif !strings.has_suffix(prefix, dir.prefix) {\n\t\t\tcontinue\n\t\t}\n", "gate": "odin:cmd/lava:main.builtin_factories_compile_on_first_require", "expect_detail": "an id outside the embedded set resolved" }, @@ -2955,7 +2955,7 @@ "name": "global_surface_web_skips_stdio dies when install_stdio runs on .Web", "why": "stdio compiles internal/stdio and the node-streams stack for a process object .Web removes; the surface gate is what keeps that cost off .Web contexts.", "source": "pkg/runtime/globals.odin", - "find": "\tif surface == .Node do install_stdio(ctx, global)", + "find": "\tif surface == .Node {\n\t\tinstall_stdio(ctx, global)\n\t}", "replace": "\tinstall_stdio(ctx, global)", "gate": "odin:cmd/lava:main.global_surface_web_skips_stdio", "expect_detail": "web: resolving events compiled nothing" From 0040268fea505668e41a4b3b3c74691cf53c50b3 Mon Sep 17 00:00:00 2001 From: x_ror <16686943+x-ror@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:59:03 +0200 Subject: [PATCH 3/3] style: format the code shared with Lava as Lava now does Before merging x-ror/lava#504: odinfmt (Lava's odinfmt.json), clang-format and scripts/fmt-if.mjs over cmd/lava, pkg/jsc, pkg/runtime and pkg/std/sqlite, so the merge's conflicts are Larva's real changes and not whitespace. Formatting only; make check passes. Co-Authored-By: Claude Opus 5.5 --- cmd/lava/buffer_reentrancy_test.odin | 12 +- cmd/lava/dns_alloc_test.odin | 8 +- cmd/lava/errors_test.odin | 50 +- cmd/lava/eval_report_hook_test.odin | 2 +- cmd/lava/fd_census_test.odin | 22 +- cmd/lava/fetch_url_test.odin | 12 +- cmd/lava/fs_write_payload_test.odin | 15 +- cmd/lava/global_surface_test.odin | 18 +- cmd/lava/host_native_alloc_test.odin | 4 +- cmd/lava/host_native_failclosed_test.odin | 10 +- cmd/lava/host_native_registry_test.odin | 126 ++- cmd/lava/jsc_predicates_test.odin | 8 +- cmd/lava/lazy_builtins_test.odin | 66 +- cmd/lava/main.odin | 59 +- cmd/lava/module_cache_alloc_test.odin | 2 +- cmd/lava/module_cache_rollback_test.odin | 6 +- cmd/lava/net_teardown_stress_test.odin | 33 +- cmd/lava/nocopy_bytes_alloc_test.odin | 6 +- cmd/lava/page_cpu_budget_test.odin | 20 +- cmd/lava/page_dispatcher_test.odin | 306 ++++++- cmd/lava/page_runner_alloc_test.odin | 46 +- cmd/lava/page_runner_reap_test.odin | 261 +++++- cmd/lava/page_runner_test.odin | 302 ++++++- cmd/lava/pool_cancel_hooks_test.odin | 42 +- cmd/lava/primordials_test.odin | 1 - cmd/lava/regexp_pollution_test.odin | 2 +- cmd/lava/repeated_eval_test.odin | 4 +- cmd/lava/stdio_fd_guard_test.odin | 6 +- cmd/lava/timer_binding_alloc_test.odin | 9 +- cmd/lava/vm_pool_test.odin | 55 +- odinfmt.json | 9 + pkg/jsc/bindings.odin | 6 +- pkg/jsc/host_function.odin | 123 ++- pkg/jsc/jsc_init.odin | 14 +- pkg/jsc/jsc_init_windows.cpp | 39 +- pkg/jsc/private_heap.odin | 47 +- pkg/jsc/private_string.odin | 289 ++++-- pkg/jsc/private_terminate.odin | 25 +- pkg/jsc/private_value.odin | 43 +- pkg/jsc/private_view.odin | 192 +++- pkg/jsc/string_utf8.odin | 13 +- pkg/runtime/buffer.odin | 520 +++++++++-- pkg/runtime/buffer_simd.odin | 68 +- pkg/runtime/buffer_utf8.odin | 134 ++- pkg/runtime/crypto.odin | 120 ++- pkg/runtime/dns.odin | 128 ++- pkg/runtime/environment.odin | 186 ++-- pkg/runtime/errors.odin | 79 +- .../eventloop/eventloop_backend_fd_test.odin | 22 +- .../eventloop_close_running_test.odin | 19 +- .../eventloop/eventloop_close_test.odin | 42 +- .../eventloop_close_wakeup_test.odin | 18 +- .../eventloop/eventloop_fd_lifetime_test.odin | 29 +- .../eventloop/eventloop_proactor_test.odin | 214 ++++- pkg/runtime/eventloop/eventloop_test.odin | 210 +++-- pkg/runtime/eventloop/loop.odin | 229 +++-- pkg/runtime/eventloop/loop_darwin.odin | 10 + pkg/runtime/eventloop/loop_linux.odin | 342 +++++--- pkg/runtime/eventloop/loop_windows.odin | 67 +- pkg/runtime/eventloop/threadpool.odin | 86 +- pkg/runtime/fetch.odin | 439 +++++++--- pkg/runtime/fetch_darwin.odin | 68 +- pkg/runtime/fetch_dns.odin | 25 +- pkg/runtime/fetch_linux.odin | 43 +- pkg/runtime/fetch_tls.odin | 34 +- pkg/runtime/fetch_tls_darwin.odin | 25 +- pkg/runtime/fetch_transport.odin | 109 ++- pkg/runtime/fetch_windows.odin | 75 +- pkg/runtime/fs.odin | 648 +++++++++++--- pkg/runtime/fs_fd_posix.odin | 79 +- pkg/runtime/fs_fd_windows.odin | 10 +- pkg/runtime/globals.odin | 670 ++++++++++---- pkg/runtime/host_natives.odin | 122 ++- pkg/runtime/http.odin | 32 +- pkg/runtime/js_root.odin | 15 +- pkg/runtime/module_resolution.odin | 111 ++- pkg/runtime/net.odin | 822 +++++++++++++----- pkg/runtime/net_other.odin | 5 +- pkg/runtime/net_zc_test.odin | 24 + pkg/runtime/os.odin | 35 +- pkg/runtime/os_darwin.odin | 28 + pkg/runtime/os_linux.odin | 41 +- pkg/runtime/os_posix.odin | 34 + pkg/runtime/os_windows.odin | 68 +- pkg/runtime/page.odin | 157 +++- pkg/runtime/page_dispatcher.odin | 127 ++- pkg/runtime/page_runner.odin | 142 ++- pkg/runtime/page_runner_other.odin | 15 +- .../picohttpparser/picohttpparser.odin | 16 +- pkg/runtime/require.odin | 95 +- pkg/runtime/runtime.odin | 112 ++- pkg/runtime/sqlite.odin | 326 +++++-- pkg/runtime/stdio.odin | 10 +- pkg/runtime/stdio_posix.odin | 6 +- pkg/runtime/tls.odin | 43 +- pkg/runtime/tls_darwin.odin | 114 ++- pkg/runtime/tls_roots_windows.odin | 20 +- pkg/runtime/tls_server.odin | 225 ++++- pkg/runtime/tty.odin | 12 +- pkg/runtime/typed_array.odin | 63 +- pkg/runtime/vm_cpu_posix.odin | 6 +- pkg/runtime/vm_cpu_windows.odin | 6 +- pkg/runtime/vm_pool.odin | 142 ++- pkg/runtime/workers.odin | 74 +- pkg/runtime/workers_linux.odin | 20 +- pkg/runtime/workers_test.odin | 53 +- pkg/std/sqlite/sqlite.odin | 126 ++- 107 files changed, 8015 insertions(+), 2293 deletions(-) create mode 100644 odinfmt.json diff --git a/cmd/lava/buffer_reentrancy_test.odin b/cmd/lava/buffer_reentrancy_test.odin index 84b33fca..1008edd4 100644 --- a/cmd/lava/buffer_reentrancy_test.odin +++ b/cmd/lava/buffer_reentrancy_test.odin @@ -55,7 +55,11 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -65,6 +69,7 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { ctx, reentrancy_eval(ctx, "typeof ArrayBuffer.prototype.transfer === 'function'"), ) + if !has_transfer { // Older JSC without the detach primitive: nothing to exercise. return @@ -112,10 +117,7 @@ buffer_natives_detach_during_coercion :: proc(t: ^testing.T) { // bytes; the call must be a no-op (undefined return, no write). { view, _ := reentrancy_setup(ctx) - evil2 := reentrancy_eval( - ctx, - "({ valueOf: function () { globalThis.__ab.transfer(); return 2; } })", - ) + evil2 := reentrancy_eval(ctx, "({ valueOf: function () { globalThis.__ab.transfer(); return 2; } })") args := [2]jsc.JSValueRef{view, evil2} r := lava.buffer_swap_cb(ctx, nil, nil, 2, raw_data(args[:]), &exc) testing.expect(t, jsc.JSValueIsUndefined(ctx, r), "swapInPlace must no-op on a detached target") diff --git a/cmd/lava/dns_alloc_test.odin b/cmd/lava/dns_alloc_test.odin index 9d9e18a8..b78bffcd 100644 --- a/cmd/lava/dns_alloc_test.odin +++ b/cmd/lava/dns_alloc_test.odin @@ -5,8 +5,8 @@ import "base:runtime" import "core:mem" import "core:sync" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Guards the localized dns/fetch allocator fix (Dns_Lookup_Request.allocator). The // hostname is cloned inside the native dns lookup callback (a `proc "c"` where context @@ -83,11 +83,15 @@ watched_allocator_proc :: proc( mem.Allocator_Error, ) { w := cast(^Watched_Allocator)data + if mode == .Alloc || mode == .Alloc_Non_Zeroed { for p in WATCHED_PROCS { - if loc.procedure == p do sync.atomic_add(&w.hits, 1) + if loc.procedure == p { + sync.atomic_add(&w.hits, 1) + } } } + return w.backing.procedure(w.backing.data, mode, size, alignment, old_memory, old_size, loc) } diff --git a/cmd/lava/errors_test.odin b/cmd/lava/errors_test.odin index 4f7cb795..77475bd2 100644 --- a/cmd/lava/errors_test.odin +++ b/cmd/lava/errors_test.odin @@ -23,10 +23,12 @@ node_error_factory :: proc(t: ^testing.T) { gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -81,7 +83,11 @@ node_error_received_types :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -108,13 +114,18 @@ node_error_received_types :: proc(t: ^testing.T) { for c in cases { val := eval_value(ctx, c.expr) e := lava.err_invalid_arg_type(ctx, "x", "string", val) + if !testing.expectf(t, jsc.JSValueIsObject(ctx, e), "%s: error must be an object", c.expr) { continue } + msg, allocated := lava.value_to_string(ctx, lava.get_named(ctx, cast(jsc.JSObjectRef)e, "message")) want := fmt.tprintf("The \"x\" argument must be of type string. Received %s", c.want) testing.expectf(t, msg == want, "%s: got %q want %q", c.expr, msg, want) - if allocated do delete(msg) + + if allocated { + delete(msg) + } } } @@ -131,7 +142,11 @@ expect_error_shape :: proc( want_name, want_message, want_code: string, ) { testing.expect(t, jsc.JSValueIsObject(ctx, err), "error value must be an object") - if !jsc.JSValueIsObject(ctx, err) do return + + if !jsc.JSValueIsObject(ctx, err) { + return + } + obj := cast(jsc.JSObjectRef)err global := jsc.JSContextGetGlobalObject(ctx) @@ -143,6 +158,7 @@ expect_error_shape :: proc( check_string_prop(t, ctx, obj, "message", want_message) code_v := lava.get_named(ctx, obj, "code") + if want_code == "" { testing.expect(t, jsc.JSValueIsUndefined(ctx, code_v), "plain error should have no code") } else { @@ -154,19 +170,29 @@ expect_error_shape :: proc( check_string_prop :: proc(t: ^testing.T, ctx: jsc.JSContextRef, obj: jsc.JSObjectRef, prop, want: string) { v := lava.get_named(ctx, obj, prop) got, allocated := lava.value_to_string(ctx, v) - defer if allocated do delete(got) + defer if allocated { + delete(got) + } testing.expectf(t, got == want, "%s: got %q want %q", prop, got, want) } @(private = "file") eval_truthy :: proc(ctx: jsc.JSContextRef, expr: string) -> bool { c_expr, err := strings.clone_to_cstring(expr, context.temp_allocator) - if err != nil do return false + + if err != nil { + return false + } + src := jsc.JSStringCreateWithUTF8CString(c_expr) defer jsc.JSStringRelease(src) exc: jsc.JSValueRef v := jsc.JSEvaluateScript(ctx, src, nil, nil, 1, &exc) - if exc != nil || v == nil do return false + + if exc != nil || v == nil { + return false + } + return jsc.JSValueToBoolean(ctx, v) } @@ -175,11 +201,19 @@ eval_truthy :: proc(ctx: jsc.JSContextRef, expr: string) -> bool { @(private = "file") eval_value :: proc(ctx: jsc.JSContextRef, expr: string) -> jsc.JSValueRef { c_expr, err := strings.clone_to_cstring(expr, context.temp_allocator) - if err != nil do return jsc.JSValueMakeUndefined(ctx) + + if err != nil { + return jsc.JSValueMakeUndefined(ctx) + } + src := jsc.JSStringCreateWithUTF8CString(c_expr) defer jsc.JSStringRelease(src) exc: jsc.JSValueRef v := jsc.JSEvaluateScript(ctx, src, nil, nil, 1, &exc) - if exc != nil || v == nil do return jsc.JSValueMakeUndefined(ctx) + + if exc != nil || v == nil { + return jsc.JSValueMakeUndefined(ctx) + } + return v } diff --git a/cmd/lava/eval_report_hook_test.odin b/cmd/lava/eval_report_hook_test.odin index 2b342c54..77032d8e 100644 --- a/cmd/lava/eval_report_hook_test.odin +++ b/cmd/lava/eval_report_hook_test.odin @@ -3,8 +3,8 @@ package main import "core:strings" import "core:testing" -import eventloop "lava:pkg/runtime/eventloop" import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" // Pins eval's `report` hook (runtime.odin, Result_Hook): it fires exactly once per eval, // with the Result eval returns, and BEFORE eval's deferred teardown — the loop is not diff --git a/cmd/lava/fd_census_test.odin b/cmd/lava/fd_census_test.odin index ec893df9..ee566a78 100644 --- a/cmd/lava/fd_census_test.odin +++ b/cmd/lava/fd_census_test.odin @@ -22,15 +22,29 @@ RUNNER_THREADS :: #config(ODIN_TEST_THREADS, 0) // skipped — when RUNNER_THREADS != 1. fd_census :: proc(timerfds_only := false) -> int { handle, err := os.open("/proc/self/fd") - if err != nil do return -1 + + if err != nil { + return -1 + } + defer os.close(handle) infos, read_err := os.read_directory(handle, -1, context.temp_allocator) - if read_err != nil do return -1 - if !timerfds_only do return len(infos) + + if read_err != nil { + return -1 + } + + if !timerfds_only { + return len(infos) + } + n := 0 for fi in infos { target, lerr := os.read_link(fi.fullpath, context.temp_allocator) - if lerr == nil && strings.contains(target, "timerfd") do n += 1 + + if lerr == nil && strings.contains(target, "timerfd") { + n += 1 + } } return n } diff --git a/cmd/lava/fetch_url_test.odin b/cmd/lava/fetch_url_test.odin index b0b617d2..707a401b 100644 --- a/cmd/lava/fetch_url_test.odin +++ b/cmd/lava/fetch_url_test.odin @@ -43,7 +43,11 @@ parse_http_url_cases :: proc(t: ^testing.T) { for c in cases { host, port, path, scheme, ok := lava_runtime.parse_http_url(c.url) testing.expectf(t, ok == c.ok, "%s: ok=%v want %v", c.url, ok, c.ok) - if !c.ok do continue + + if !c.ok { + continue + } + testing.expectf(t, host == c.host, "%s: host=%q want %q", c.url, host, c.host) testing.expectf(t, port == c.port, "%s: port=%d want %d", c.url, port, c.port) testing.expectf(t, path == c.path, "%s: path=%q want %q", c.url, path, c.path) @@ -78,7 +82,11 @@ fetch_parse_chunk_size_cases :: proc(t: ^testing.T) { for c in cases { size, ok := lava_runtime.fetch_parse_chunk_size(c.text) testing.expectf(t, ok == c.ok, "%q: ok=%v want %v", c.text, ok, c.ok) - if !c.ok do continue + + if !c.ok { + continue + } + testing.expectf(t, size == c.size, "%q: size=%d want %d", c.text, size, c.size) } } diff --git a/cmd/lava/fs_write_payload_test.odin b/cmd/lava/fs_write_payload_test.odin index bafbe368..b5e0f808 100644 --- a/cmd/lava/fs_write_payload_test.odin +++ b/cmd/lava/fs_write_payload_test.odin @@ -47,7 +47,11 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -57,7 +61,10 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. ctx, payload_eval(ctx, "new ArrayBuffer(8, { maxByteLength: 8 }).resizable === true"), ) - if !resizable do return + + if !resizable { + return + } // A genuine DataView over a 4096-byte resizable buffer, carrying an own byteOffset // getter that shrinks the backing to 8 bytes and an own byteLength that keeps @@ -85,9 +92,7 @@ fs_write_payload_rejects_a_window_resized_by_its_own_getter :: proc(t: ^testing. // The buffer is 8 bytes live by the time the pointer is taken. Anything longer is // memory past the allocation — which is what shipped, at 4096. - live := int( - jsc.JSValueToNumber(ctx, payload_eval(ctx, "globalThis.__ab.byteLength"), nil), - ) + live := int(jsc.JSValueToNumber(ctx, payload_eval(ctx, "globalThis.__ab.byteLength"), nil)) testing.expectf(t, live == 8, "the getter should have resized the backing to 8, got %d", live) testing.expectf( t, diff --git a/cmd/lava/global_surface_test.odin b/cmd/lava/global_surface_test.odin index 2cad5a5c..ff2a50c0 100644 --- a/cmd/lava/global_surface_test.odin +++ b/cmd/lava/global_surface_test.odin @@ -269,14 +269,7 @@ if (present.length !== 0) throw new Error('web surface still has: ' + present.jo @(test) global_surface_alternates_on_one_thread :: proc(t: ^testing.T) { expect_ok :: proc(t: ^testing.T, what: string, result: lava.Result) { - testing.expectf( - t, - result.status == .Ok, - "%s: status=%v message=%q", - what, - result.status, - result.message, - ) + testing.expectf(t, result.status == .Ok, "%s: status=%v message=%q", what, result.status, result.message) } first := lava.eval(NODE_NAMES_PRESENT, "", nil) @@ -306,7 +299,12 @@ global_surface_web_skips_stdio :: proc(t: ^testing.T) { node_init, node_events := surface_events_compiles(t, .Node) web_init, web_events := surface_events_compiles(t, .Web) - testing.expectf(t, node_events == 0, "node: resolving events compiled %d factories (want 0: stdio loaded it)", node_events) + testing.expectf( + t, + node_events == 0, + "node: resolving events compiled %d factories (want 0: stdio loaded it)", + node_events, + ) testing.expectf(t, web_events > 0, "web: resolving events compiled nothing — stdio was instantiated at init") testing.expectf( t, @@ -325,10 +323,12 @@ surface_events_compiles :: proc(t: ^testing.T, surface: lava.Global_Surface) -> gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx diff --git a/cmd/lava/host_native_alloc_test.odin b/cmd/lava/host_native_alloc_test.odin index 676335c0..dd0c3fc4 100644 --- a/cmd/lava/host_native_alloc_test.odin +++ b/cmd/lava/host_native_alloc_test.odin @@ -86,7 +86,9 @@ host_native_tables_are_not_charged_to_the_eval_allocator :: proc(t: ^testing.T) stray := 0 for _, entry in track.allocation_map { - if strings.contains(entry.location.file_path, "host_natives.odin") do stray += 1 + if strings.contains(entry.location.file_path, "host_natives.odin") { + stray += 1 + } } testing.expectf( t, diff --git a/cmd/lava/host_native_failclosed_test.odin b/cmd/lava/host_native_failclosed_test.odin index 8ab74ea7..e9439659 100644 --- a/cmd/lava/host_native_failclosed_test.odin +++ b/cmd/lava/host_native_failclosed_test.odin @@ -35,12 +35,18 @@ import lava "lava:pkg/runtime" host_native_dispatch_miss_fails_closed :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) // Without the private-ABI path nothing is registered, so there is no miss to // observe and every assertion below would pass vacuously. - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) diff --git a/cmd/lava/host_native_registry_test.odin b/cmd/lava/host_native_registry_test.odin index 7767e4ca..ab380636 100644 --- a/cmd/lava/host_native_registry_test.odin +++ b/cmd/lava/host_native_registry_test.odin @@ -47,22 +47,35 @@ other_cb :: proc "c" ( eval_text :: proc(ctx: jsc.JSContextRef, source: string) -> (string, bool) { c_src, err := strings.clone_to_cstring(source, context.temp_allocator) - if err != nil do return "", false + + if err != nil { + return "", false + } + js_src := jsc.JSStringCreateWithUTF8CString(c_src) defer jsc.JSStringRelease(js_src) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, js_src, nil, nil, 1, &exception) - if exception != nil || value == nil do return "", false + + if exception != nil || value == nil { + return "", false + } + // jsc_value_to_string_or_default hands back an OWNED context.allocator buffer. // The test runner installs a per-test tracking allocator and reports whatever is // still live when the test ends, so a helper that keeps it would print a leak on // every assertion here and bury a real one in the code under test. owned, got := lava.jsc_value_to_string_or_default(ctx, value) - if !got do return "", true // empty string: nothing was allocated + + if !got {return "", true} // empty string: nothing was allocated defer delete(owned) copied, clone_err := strings.clone(owned, context.temp_allocator) - if clone_err != nil do return "", false + + if clone_err != nil { + return "", false + } + return copied, true } @@ -77,10 +90,12 @@ Context :: struct { make_context :: proc() -> (Context, bool) { class := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(class) + if gctx == nil { jsc.JSClassRelease(class) return {}, false } + return Context{class = class, gctx = gctx, ctx = cast(jsc.JSContextRef)gctx}, true } @@ -93,12 +108,11 @@ destroy_context :: proc(c: Context) { // this file asserts on it rather than skipping quietly: a silently vacuous // regression test is the failure mode this whole area keeps hitting. host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { - if jsc.host_calls_active(ctx) do return true - testing.expect( - t, - false, - "private-ABI host-call path inactive — this test cannot observe what it pins", - ) + if jsc.host_calls_active(ctx) { + return true + } + + testing.expect(t, false, "private-ABI host-call path inactive — this test cannot observe what it pins") return false } @@ -110,15 +124,25 @@ host_path_active :: proc(t: ^testing.T, ctx: jsc.JSContextRef) -> bool { host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { a, a_ok := make_context() testing.expect(t, a_ok, "could not create the first JSC global context") - if !a_ok do return + + if !a_ok { + return + } + defer destroy_context(a) b, b_ok := make_context() testing.expect(t, b_ok, "could not create the second JSC global context") - if !b_ok do return + + if !b_ok { + return + } + defer destroy_context(b) - if !host_path_active(t, a.ctx) do return + if !host_path_active(t, a.ctx) { + return + } state_a := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(a.ctx), cast(rawptr)state_a) @@ -142,12 +166,7 @@ host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { lava.destroy_runtime_state(a.ctx, state_a) after, ok_after := eval_text(b.ctx, "String(probe())") - testing.expectf( - t, - ok_after && after == "42", - "tearing down context A broke context B's registry: %q", - after, - ) + testing.expectf(t, ok_after && after == "42", "tearing down context A broke context B's registry: %q", after) } // The cache exists so per-instance injections (the fs.Stats methods) reuse one @@ -158,10 +177,16 @@ host_native_sweep_is_scoped_to_its_context :: proc(t: ^testing.T) { host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) @@ -169,7 +194,10 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { first := lava.host_native_create(c.ctx, "probe", answer_cb) testing.expect(t, first != nil, "host_native_create returned nil on the host path") - if first == nil do return + + if first == nil { + return + } same := lava.host_native_create(c.ctx, "probe", answer_cb) testing.expect(t, same == first, "same (callback, name) minted a second function object") @@ -181,11 +209,7 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { testing.expect(t, renamed != nil && renamed != first, "a different name reused the same cell") different := lava.host_native_create(c.ctx, "probe", other_cb) - testing.expect( - t, - different != nil && different != first, - "a different callback reused the same cell", - ) + testing.expect(t, different != nil && different != first, "a different callback reused the same cell") } // Pins the host path's construct-result divergence require.odin documents: @@ -199,20 +223,23 @@ host_native_create_dedupes_per_callback_and_name :: proc(t: ^testing.T) { host_native_construct_returns_call_result :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } state := lava.new_runtime_state(nil) jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(c.ctx), cast(rawptr)state) defer lava.destroy_runtime_state(c.ctx, state) lava.inject_native_function(c.ctx, jsc.JSContextGetGlobalObject(c.ctx), "probe", answer_cb) - text, ok_eval := eval_text( - c.ctx, - "(function(){ var r = new probe(); return typeof r + ':' + String(r); })()", - ) + text, ok_eval := eval_text(c.ctx, "(function(){ var r = new probe(); return typeof r + ':' + String(r); })()") testing.expectf(t, ok_eval && text == "number:42", "host-path construct result changed: %q", text) } @@ -224,10 +251,16 @@ host_native_construct_returns_call_result :: proc(t: ^testing.T) { host_native_create_declines_without_state :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } // Deliberately no JSObjectSetPrivate: this is the bare embedder context. fn := lava.host_native_create(c.ctx, "probe", answer_cb) @@ -292,10 +325,16 @@ failing_allocator :: proc() -> mem.Allocator { host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) - if !host_path_active(t, c.ctx) do return + if !host_path_active(t, c.ctx) { + return + } // Built normally, so its maps and its own allocation come from the real // allocator; only the name-clone allocator is faulted. Overwriting the field @@ -317,12 +356,7 @@ host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { // The binding still has to work — an OOM in our cache is not an OOM in JSC. lava.inject_native_function(c.ctx, jsc.JSContextGetGlobalObject(c.ctx), "probe", answer_cb) text, ok_eval := eval_text(c.ctx, "String(probe())") - testing.expectf( - t, - ok_eval && text == "42", - "binding broke when the registry could not cache it: %q", - text, - ) + testing.expectf(t, ok_eval && text == "42", "binding broke when the registry could not cache it: %q", text) } // host_throw's contract is that its RETURN says whether the exception was really @@ -337,7 +371,11 @@ host_native_create_survives_allocation_failure :: proc(t: ^testing.T) { host_throw_reports_whether_it_raised :: proc(t: ^testing.T) { c, ok := make_context() testing.expect(t, ok, "could not create a JSC global context") - if !ok do return + + if !ok { + return + } + defer destroy_context(c) testing.expect( diff --git a/cmd/lava/jsc_predicates_test.odin b/cmd/lava/jsc_predicates_test.odin index ebf2e2a9..e15c63cf 100644 --- a/cmd/lava/jsc_predicates_test.odin +++ b/cmd/lava/jsc_predicates_test.odin @@ -27,7 +27,11 @@ jsc_value_predicates :: proc(t: ^testing.T) { jsc.lava_jsc_init() gctx := jsc.JSGlobalContextCreate(nil) testing.expect(t, gctx != nil, "could not create a JSC global context") - if gctx == nil do return + + if gctx == nil { + return + } + defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -126,11 +130,13 @@ predicate_probe_cb :: proc "c" ( exception: ^jsc.JSValueRef, ) -> jsc.JSValueRef { probe_called = true + if argument_count >= 4 { probe_false_is_false = jsc.JSValueToBoolean(ctx, arguments[0]) == false probe_undef_is_undefined = jsc.JSValueIsUndefined(ctx, arguments[1]) probe_obj_is_object = jsc.JSValueIsObject(ctx, arguments[2]) probe_num_not_object = !jsc.JSValueIsObject(ctx, arguments[3]) } + return jsc.JSValueMakeUndefined(ctx) } diff --git a/cmd/lava/lazy_builtins_test.odin b/cmd/lava/lazy_builtins_test.odin index f038cdef..316677a5 100644 --- a/cmd/lava/lazy_builtins_test.odin +++ b/cmd/lava/lazy_builtins_test.odin @@ -22,10 +22,12 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { gclass := lava.make_global_class() gctx := jsc.JSGlobalContextCreate(gclass) testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { jsc.JSClassRelease(gclass) return } + defer jsc.JSClassRelease(gclass) defer jsc.JSGlobalContextRelease(gctx) ctx := cast(jsc.JSContextRef)gctx @@ -41,7 +43,9 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { embedded := 0 for dir in lava.EMBEDDED_JS_DIRS { for file in dir.files { - if strings.has_suffix(file.name, ".js") do embedded += 1 + if strings.has_suffix(file.name, ".js") { + embedded += 1 + } } } @@ -91,7 +95,10 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { // ponytail: count-based for internal/ ids; record compiled ids on Runtime_State if // that coincidence ever matters. check-js-graph.test.mjs keeps this list current. for id in STATIC_EAGER { - if !strings.has_prefix(id, "node/") do continue + if !strings.has_prefix(id, "node/") { + continue + } + before := state.builtin_compiles src, _ := strings.concatenate({"require('node:", id[len("node/"):], "') != null"}, context.temp_allocator) testing.expectf(t, run_bool(ctx, src), "%s did not load", id) @@ -104,7 +111,54 @@ builtin_factories_compile_on_first_require :: proc(t: ^testing.T) { // The static eager set, sorted. Must equal eagerModules() — asserted by // scripts/check-js-graph.test.mjs, which parses this literal. @(private = "file") -STATIC_EAGER :: [?]string{"internal/abort", "internal/blob", "internal/buffer", "internal/crypto/hash", "internal/crypto/hkdf", "internal/crypto/pbkdf2", "internal/crypto/random", "internal/crypto/scrypt", "internal/crypto/util", "internal/encoding", "internal/errors", "internal/fetch", "internal/fetch/body", "internal/fetch/headers", "internal/fetch/request", "internal/fetch/response", "internal/file", "internal/idna", "internal/primordials", "internal/punycode", "internal/stdio", "internal/streams/add-abort-signal", "internal/streams/destroy", "internal/streams/duplex", "internal/streams/end-of-stream", "internal/streams/legacy", "internal/streams/passthrough", "internal/streams/pipeline", "internal/streams/readable", "internal/streams/transform", "internal/streams/utils", "internal/streams/writable", "internal/structured_clone", "internal/url", "internal/webstreams/queuingstrategies", "internal/webstreams/readablestream", "internal/webstreams/transformstream", "internal/webstreams/util", "internal/webstreams/writablestream", "node/buffer", "node/crypto", "node/events", "node/stream", "node/stream/web", "node/string_decoder", "node/url"} +STATIC_EAGER :: [?]string { + "internal/abort", + "internal/blob", + "internal/buffer", + "internal/crypto/hash", + "internal/crypto/hkdf", + "internal/crypto/pbkdf2", + "internal/crypto/random", + "internal/crypto/scrypt", + "internal/crypto/util", + "internal/encoding", + "internal/errors", + "internal/fetch", + "internal/fetch/body", + "internal/fetch/headers", + "internal/fetch/request", + "internal/fetch/response", + "internal/file", + "internal/idna", + "internal/primordials", + "internal/punycode", + "internal/stdio", + "internal/streams/add-abort-signal", + "internal/streams/destroy", + "internal/streams/duplex", + "internal/streams/end-of-stream", + "internal/streams/legacy", + "internal/streams/passthrough", + "internal/streams/pipeline", + "internal/streams/readable", + "internal/streams/transform", + "internal/streams/utils", + "internal/streams/writable", + "internal/structured_clone", + "internal/url", + "internal/webstreams/queuingstrategies", + "internal/webstreams/readablestream", + "internal/webstreams/transformstream", + "internal/webstreams/util", + "internal/webstreams/writablestream", + "node/buffer", + "node/crypto", + "node/events", + "node/stream", + "node/stream/web", + "node/string_decoder", + "node/url", +} @(private = "file") run_bool :: proc(ctx: jsc.JSContextRef, src: string) -> bool { @@ -113,6 +167,10 @@ run_bool :: proc(ctx: jsc.JSContextRef, src: string) -> bool { defer jsc.JSStringRelease(script) exception: jsc.JSValueRef value := jsc.JSEvaluateScript(ctx, script, nil, nil, 1, &exception) - if exception != nil do return false + + if exception != nil { + return false + } + return jsc.JSValueToBoolean(ctx, value) } diff --git a/cmd/lava/main.odin b/cmd/lava/main.odin index f0cf04b1..01abd6e1 100644 --- a/cmd/lava/main.odin +++ b/cmd/lava/main.odin @@ -80,10 +80,12 @@ run_command :: proc(args: []string) { // LAVA_WORKERS>1 runs the file on N shared-nothing worker loops (Slice 3a). Resolved fail-fast: // an invalid value or an unsupported platform exits non-zero rather than silently degrading. worker_count, count_ok, count_msg := lava_runtime.lava_resolve_worker_count() + if !count_ok { fmt.eprintfln("lava: %s", count_msg) os.exit(2) } + if worker_count > 1 { // args is [scriptPath, ...userArgs]; the supervisor reads the file once and runs N workers. os.exit(lava_runtime.lava_run_workers(args[0], worker_count, args[1:])) @@ -116,6 +118,7 @@ print_result :: proc(result: lava_runtime.Result, user_data: rawptr) { if len(result.message) > 0 { lava_runtime.process_write(os.stdout, result.message, "\n") } + return } @@ -146,13 +149,25 @@ html_command :: proc(args: []string) { opts.list_scripts = true case a == "--chunk": i += 1 - if i == len(args) do usage() + + if i == len(args) { + usage() + } + n, ok := strconv.parse_int(args[i]) - if !ok || n <= 0 do usage() + + if !ok || n <= 0 { + usage() + } + chunk = n case a == "--select": i += 1 - if i == len(args) do usage() + + if i == len(args) { + usage() + } + css = args[i] case len(a) > 1 && a[0] == '-', path != "": usage() @@ -160,12 +175,17 @@ html_command :: proc(args: []string) { path = a } } - if path == "" do usage() + + if path == "" { + usage() + } data: []byte err: os.Error - if path == "-" do data, err = os.read_entire_file_from_file(os.stdin, context.allocator) - else do data, err = os.read_entire_file(path, context.allocator) + + if path == + "-" {data, err = os.read_entire_file_from_file(os.stdin, context.allocator)} else {data, err = os.read_entire_file(path, context.allocator)} + if err != nil { fmt.eprintfln("lava html: cannot read %s: %v", path, err) os.exit(1) @@ -174,10 +194,18 @@ html_command :: proc(args: []string) { report :: proc(p: ^html.Parser, script: html.Node, user_data: rawptr) { o := cast(^Html_Options)user_data o.scripts += 1 - if !o.list_scripts do return + + if !o.list_scripts { + return + } + // An SVG