diff --git a/packages/compiler/src/backend/native-toolchain.test.ts b/packages/compiler/src/backend/native-toolchain.test.ts index 1ef33bf2c2..e45cf8dbbb 100644 --- a/packages/compiler/src/backend/native-toolchain.test.ts +++ b/packages/compiler/src/backend/native-toolchain.test.ts @@ -3078,7 +3078,11 @@ exec "$SCRIPTC_TEST_REAL_CLANG" "$@" outPath: firstOut, cacheIdentity: TEST_CACHE_IDENTITY, }); - const deadline = Date.now() + 10_000; + // This is a hang detector, not a latency bound: the runtime compile + // that reaches scr_number.c shares the machine with every other test + // worker in the shard, and a loaded runner can take far longer than + // the ten seconds this used to allow. + const deadline = Date.now() + 120_000; while (!existsSync(signal)) { if (Date.now() > deadline) throw new Error("timed out waiting for runtime compile"); await new Promise((resolveWait) => setTimeout(resolveWait, 10)); diff --git a/packages/runtime-pack-common/test/runtime-profile.test.ts b/packages/runtime-pack-common/test/runtime-profile.test.ts index cb91ece346..e4fc2d1bb3 100644 --- a/packages/runtime-pack-common/test/runtime-profile.test.ts +++ b/packages/runtime-pack-common/test/runtime-profile.test.ts @@ -105,6 +105,10 @@ test.skipIf(helper?.features.includes("profile-functions") !== true)( if (/[/\\]/.test(name)) return true; const local = /^([\w-]+\.c);(.+)$/.exec(name); if (local !== null) return !sources.has(local[1]!); + // The link-contract marker is a runtime function whose name carries the + // ABI version; the committed profile keeps the spelling it was collected + // under, which the current sources no longer declare after a bump. + if (/^scr_runtime_abi_v\d+$/.test(name)) return false; return name === "main" || name.startsWith("sc_") || !identifiers.has(name); }); expect(foreign, "records that are not runtime functions").toEqual([]); diff --git a/packages/runtime/src/scr_dyn_invoke.c b/packages/runtime/src/scr_dyn_invoke.c index 401e036da6..a7b1a380da 100644 --- a/packages/runtime/src/scr_dyn_invoke.c +++ b/packages/runtime/src/scr_dyn_invoke.c @@ -2572,19 +2572,75 @@ static ScrDyn *dyn_worker_channel(void) { return scr_worker_message_channel(); } static ScrDyn *dyn_worker_channel(void) { return NULL; } #endif /* The runtime-provided host classes whose constructors the runtime builds: - * the abort unit (scr_abort.c / scr_fetch.c), the event-target unit, and the - * base error unit's DOMException. */ + * the abort unit (scr_fetch.c), the event-target unit, and the base error + * unit's DOMException. */ +extern ScrError *scr_domex_new(const ScrDyn *message, const ScrDyn *name_or_options) + __attribute__((weak)); +/* Mach-O refuses an undefined weak *reference* in an executable, so the + * optional constructor units get weak definitions there: a program that + * links none of them still links, and the units' strong definitions replace + * them. The linked flags answer the capability tests the NULL checks give on + * the other formats — a defined stub can no longer be told apart by its + * address. */ +#if defined(__APPLE__) +__attribute__((weak)) int scr_dyn_abort_unit_linked = 0; +__attribute__((weak)) int scr_dyn_event_target_unit_linked = 0; +__attribute__((weak)) ScrDyn *scr_fetch_abort_controller_new(void) { return NULL; } +__attribute__((weak)) ScrDyn *scr_event_target_new(void) { return NULL; } +__attribute__((weak)) ScrDyn *scr_event_new(ScrDyn *args) { + (void)args; + return NULL; +} +__attribute__((weak)) ScrDyn *scr_custom_event_new(ScrDyn *args) { + (void)args; + return NULL; +} +static bool dyn_abort_available(void) { return scr_dyn_abort_unit_linked != 0; } +static bool dyn_event_available(void) { return scr_dyn_event_target_unit_linked != 0; } +#else extern ScrDyn *scr_fetch_abort_controller_new(void) __attribute__((weak)); extern ScrDyn *scr_event_target_new(void) __attribute__((weak)); extern ScrDyn *scr_event_new(ScrDyn *args) __attribute__((weak)); extern ScrDyn *scr_custom_event_new(ScrDyn *args) __attribute__((weak)); -extern ScrError *scr_domex_new(const ScrDyn *message, const ScrDyn *name_or_options) - __attribute__((weak)); +static bool dyn_abort_available(void) { return scr_fetch_abort_controller_new != NULL; } +static bool dyn_event_available(void) { + return scr_event_new != NULL && scr_custom_event_new != NULL && scr_event_target_new != NULL; +} +#endif +/* Mach-O refuses an undefined weak *reference* in an executable, so the + * regex entries get weak definitions there: a program that links no regex + * unit still links, and the unit's strong definitions replace them. The + * linked flag answers the capability test the NULL check gives on the other + * formats — a defined stub can no longer be told apart by its address. */ +#if defined(__APPLE__) +__attribute__((weak)) int scr_dyn_regex_unit_linked = 0; +__attribute__((weak)) ScrRegex *scr_regex_new_checked(const ScrDyn *pattern, + const ScrDyn *flags) { + (void)pattern; + (void)flags; + return NULL; +} +__attribute__((weak)) ScrDyn *scr_dyn_native_regex(ScrRegex *value) { + (void)value; + return NULL; +} +__attribute__((weak)) bool scr_dyn_native_regex_is(const ScrDyn *value) { + (void)value; + return false; +} +__attribute__((weak)) void scr_regex_release(ScrRegex *value) { (void)value; } +static bool dyn_regex_available(void) { return scr_dyn_regex_unit_linked != 0; } +#else extern ScrRegex *scr_regex_new_checked(const ScrDyn *pattern, const ScrDyn *flags) __attribute__((weak)); extern ScrDyn *scr_dyn_native_regex(ScrRegex *value) __attribute__((weak)); extern bool scr_dyn_native_regex_is(const ScrDyn *value) __attribute__((weak)); extern void scr_regex_release(ScrRegex *value) __attribute__((weak)); +static bool dyn_regex_available(void) { + return scr_regex_new_checked != NULL && scr_dyn_native_regex != NULL && + scr_dyn_native_regex_is != NULL && scr_regex_release != NULL; +} +#endif /* `new RegExp(pattern, flags)` and `RegExp(pattern, flags)` through the * interned constructor: the same native engine the regex literals and the @@ -2594,8 +2650,7 @@ extern void scr_regex_release(ScrRegex *value) __attribute__((weak)); * `constructor` that step compares, since a write of that member is * refused); `new` always builds a copy. */ static ScrDyn *dyn_regex_construct(const ScrDyn *pattern, const ScrDyn *flags, bool identity) { - if (scr_regex_new_checked == NULL || scr_dyn_native_regex == NULL || - scr_dyn_native_regex_is == NULL || scr_regex_release == NULL) { + if (!dyn_regex_available()) { char message[128]; int length = snprintf(message, sizeof message, identity ? dyn_s0 : dyn_s33, dyn_s25, dyn_s32); scr_throw_error_msg_code(SCR_ERR_ERROR, message, (size_t)length, dyn_s27); @@ -2692,13 +2747,13 @@ static bool dyn_global_construct(const ScrDyn *callee, const ScrDyn *args, ScrDy ScrDyn *channel = dyn_worker_channel(); if (channel != NULL) *result = channel; else dyn_unsupported_constructor(name, result); - } else if (strcmp(name, dyn_s52) == 0 && scr_fetch_abort_controller_new != NULL) { + } else if (strcmp(name, dyn_s52) == 0 && dyn_abort_available()) { *result = scr_fetch_abort_controller_new(); - } else if (strcmp(name, dyn_s53) == 0 && scr_event_new != NULL) { + } else if (strcmp(name, dyn_s53) == 0 && dyn_event_available()) { *result = scr_event_new((ScrDyn *)args); - } else if (strcmp(name, dyn_s54) == 0 && scr_custom_event_new != NULL) { + } else if (strcmp(name, dyn_s54) == 0 && dyn_event_available()) { *result = scr_custom_event_new((ScrDyn *)args); - } else if (strcmp(name, dyn_s55) == 0 && scr_event_target_new != NULL) { + } else if (strcmp(name, dyn_s55) == 0 && dyn_event_available()) { *result = scr_event_target_new(); } else if (strcmp(name, dyn_s56) == 0 && scr_domex_new != NULL) { ScrError *error = scr_domex_new(first, argc > 1 ? items[1] : scr_dyn_undefined()); diff --git a/packages/runtime/src/scr_event_target.c b/packages/runtime/src/scr_event_target.c index aa6b878599..1b267c33a8 100644 --- a/packages/runtime/src/scr_event_target.c +++ b/packages/runtime/src/scr_event_target.c @@ -12,6 +12,13 @@ */ #include "scr_runtime.h" +#if defined(__APPLE__) +/* scr_dyn_invoke.c defines this weakly for Mach-O's linker; the event-target + * unit's strong definition tells it that Event, CustomEvent and EventTarget + * construction is available. */ +int scr_dyn_event_target_unit_linked = 1; +#endif + #include #include #include diff --git a/packages/runtime/src/scr_fetch.c b/packages/runtime/src/scr_fetch.c index 265a5d846d..d4ee64a8ef 100644 --- a/packages/runtime/src/scr_fetch.c +++ b/packages/runtime/src/scr_fetch.c @@ -14,6 +14,12 @@ #include "scr_system_errors.h" #include "scr_url_internal.h" +#if defined(__APPLE__) +/* scr_dyn_invoke.c, scr_http.c and scr_test.c define this weakly for Mach-O's + * linker; the abort unit's strong definition tells them it is available. */ +int scr_dyn_abort_unit_linked = 1; +#endif + #include #include #include diff --git a/packages/runtime/src/scr_http.c b/packages/runtime/src/scr_http.c index 445fe64172..10a965ac3e 100644 --- a/packages/runtime/src/scr_http.c +++ b/packages/runtime/src/scr_http.c @@ -317,22 +317,41 @@ void scr_http_req_set_encoding(ScrHttpReq *r, ScrStr *enc /*borrowed*/) { } /* IncomingMessage.signal's abort controller comes from the abort unit - * (scr_abort.c or fetch). Weak bindings keep a program that never reads - * req.signal from linking it. */ + * (scr_fetch.c). Weak bindings keep a program that never reads req.signal + * from linking it; Mach-O refuses an undefined weak reference, so Apple gets + * weak definitions and the unit's linked flag as the capability test. */ +#if defined(__APPLE__) +__attribute__((weak)) int scr_dyn_abort_unit_linked = 0; +__attribute__((weak)) ScrDyn *scr_abort_signal_controller_new(void) { return NULL; } +__attribute__((weak)) ScrDyn *scr_abort_signal_signal(ScrDyn *controller) { + (void)controller; + return NULL; +} +__attribute__((weak)) void scr_abort_signal_abort(ScrDyn *controller) { (void)controller; } +__attribute__((weak)) void scr_abort_signal_drop_listeners(ScrDyn *controller) { + (void)controller; +} +static bool scr_http_abort_available(void) { return scr_dyn_abort_unit_linked != 0; } +#else extern ScrDyn *scr_abort_signal_controller_new(void) __attribute__((weak)); extern ScrDyn *scr_abort_signal_signal(ScrDyn *controller) __attribute__((weak)); extern void scr_abort_signal_abort(ScrDyn *controller) __attribute__((weak)); extern void scr_abort_signal_drop_listeners(ScrDyn *controller) __attribute__((weak)); +static bool scr_http_abort_available(void) { + return scr_abort_signal_controller_new != NULL && scr_abort_signal_signal != NULL && + scr_abort_signal_abort != NULL && scr_abort_signal_drop_listeners != NULL; +} +#endif static void scr_http_req_abort_signal(ScrHttpReq *r) { - if (r != NULL && r->abort_controller != NULL && scr_abort_signal_abort != NULL) + if (r != NULL && r->abort_controller != NULL && scr_http_abort_available()) scr_abort_signal_abort(r->abort_controller); } /* req.signal (+1): one native AbortSignal per request, created on first * read and aborted when the request is destroyed before it completes. */ ScrDyn *scr_http_req_signal(ScrHttpReq *r) { - if (scr_abort_signal_controller_new == NULL || scr_abort_signal_signal == NULL) { + if (!scr_http_abort_available()) { static const char msg[] = "IncomingMessage.signal is not supported by this runtime build"; scr_throw_error_msg_code(SCR_ERR_ERROR, msg, sizeof msg - 1, "SC2020"); return NULL; @@ -3521,7 +3540,7 @@ static void scr_http_proto_sweep(void) { /* The signal's abort listeners captured the request (and usually the * response); release them so the settled request is collectable once * the program drops it. */ - if (req->abort_controller != NULL && scr_abort_signal_drop_listeners != NULL) + if (req->abort_controller != NULL && scr_http_abort_available()) scr_abort_signal_drop_listeners(req->abort_controller); } break; diff --git a/packages/runtime/src/scr_lib.c b/packages/runtime/src/scr_lib.c index a6dbb09025..4e2b3b956d 100644 --- a/packages/runtime/src/scr_lib.c +++ b/packages/runtime/src/scr_lib.c @@ -7198,19 +7198,36 @@ void scr_mkdtemp_result_release_v(void *p) { scr_mkdtemp_result_release((ScrMkdtempResult *)p); } -/* The promise entries the fs.mkdtempDisposable helpers need, referenced - * weakly: the promise unit (scr_async.c) defines them, and a program that - * links scr_lib.c without it (a runtime unit test, or a hello build) must - * not pull the promise machinery into its binary — a constructor that named - * them did. A program can only reach these helpers after linking the unit, - * whose own references resolve them; scr_dyn_invoke.c's worker channel uses - * the same weak-reference pattern. */ -extern ScrPromise *scr_promise_new(void) __attribute__((weak)); -extern void scr_promise_reject_pending(ScrPromise *p) __attribute__((weak)); -extern ScrPromise *scr_promise_settled_ref( - void *v, void *(*retain)(void *), void (*release)(void *), ScrTraceFn trace) - __attribute__((weak)); -extern ScrPromise *scr_promise_settled_void(void) __attribute__((weak)); +/* The promise entries the fs.mkdtempDisposable helpers need. The promise + * unit (scr_async.c) defines them strongly; these weak definitions answer a + * program that links scr_lib.c without it (a runtime unit test, or a hello + * build) without pulling the promise machinery into its binary — a + * constructor that named the unit did — and they leave no undefined runtime + * symbol behind, which a localized library archive would otherwise carry to + * the embedder's link. Only a program that linked the unit can reach the + * helpers (they answer promises), so the fallback traps; the weak + * definition loses to the unit's strong one. */ +__attribute__((weak)) ScrPromise *scr_promise_new(void) { + scr_trap("scriptc: the promise unit is not linked\n"); + return NULL; +} +__attribute__((weak)) void scr_promise_reject_pending(ScrPromise *p) { + (void)p; + scr_trap("scriptc: the promise unit is not linked\n"); +} +__attribute__((weak)) ScrPromise *scr_promise_settled_ref( + void *v, void *(*retain)(void *), void (*release)(void *), ScrTraceFn trace) { + (void)v; + (void)retain; + (void)release; + (void)trace; + scr_trap("scriptc: the promise unit is not linked\n"); + return NULL; +} +__attribute__((weak)) ScrPromise *scr_promise_settled_void(void) { + scr_trap("scriptc: the promise unit is not linked\n"); + return NULL; +} /* A promise already rejected by the pending exception, through the promise * unit's entries. */ diff --git a/packages/runtime/src/scr_regex.c b/packages/runtime/src/scr_regex.c index 63032f2c09..d2b0c5966f 100644 --- a/packages/runtime/src/scr_regex.c +++ b/packages/runtime/src/scr_regex.c @@ -9,6 +9,13 @@ #include "libregexp.h" #include "scr_regex_native.h" +#if defined(__APPLE__) +/* scr_dyn_invoke.c defines this weakly for Mach-O's linker: the regex + * unit's strong definition tells a linked program that RegExp construction + * is available. */ +int scr_dyn_regex_unit_linked = 1; +#endif + static void scr_regex_oom(void) { scr_trap("scriptc: out of memory\n"); } diff --git a/packages/runtime/src/scr_stream.c b/packages/runtime/src/scr_stream.c index fa1755c3d8..639cf1fa6b 100644 --- a/packages/runtime/src/scr_stream.c +++ b/packages/runtime/src/scr_stream.c @@ -301,6 +301,10 @@ struct ScrStreamState { /* The watcher must also report at the stream's close step when the * stream does not emit 'close' (an adapter that has to let go). */ bool *close_step; + /* Registered after the stream was destroyed: Node's eos inspects the + * state at registration, so a silent destroy with a recorded error + * reports it, while a watcher that predates the destroy stays pending. */ + bool *after_destroy; size_t n, cap; } fin; @@ -506,6 +510,7 @@ static void scr_stream_state_drop(ScrStreamState *st, bool gc) { free(st->fin.cb); free(st->fin.inv); free(st->fin.close_step); + free(st->fin.after_destroy); free(st->pipes.dst); free(st->pipes.end); free(st->drain_srcs.src); @@ -3714,17 +3719,21 @@ void scr_stream_init_passthrough_dyn(ScrStream *s, ScrDyn *opts, * error no longer crashes (the SCR_ST_ERROR suppression above). */ static void scr_stream_fin_add(ScrStreamState *st, ScrClosure *cb /*moves*/, ScrStreamErrInv inv, - bool close_step) { + bool close_step, bool after_destroy) { if (st->fin.n == st->fin.cap) { st->fin.cap = st->fin.cap ? st->fin.cap * 2 : 2; st->fin.cb = realloc(st->fin.cb, st->fin.cap * sizeof *st->fin.cb); st->fin.inv = realloc(st->fin.inv, st->fin.cap * sizeof *st->fin.inv); st->fin.close_step = realloc(st->fin.close_step, st->fin.cap * sizeof *st->fin.close_step); - if (!st->fin.cb || !st->fin.inv || !st->fin.close_step) scr_stream_oom(); + st->fin.after_destroy = + realloc(st->fin.after_destroy, st->fin.cap * sizeof *st->fin.after_destroy); + if (!st->fin.cb || !st->fin.inv || !st->fin.close_step || !st->fin.after_destroy) + scr_stream_oom(); } st->fin.cb[st->fin.n] = cb; st->fin.inv[st->fin.n] = inv; st->fin.close_step[st->fin.n] = close_step; + st->fin.after_destroy[st->fin.n] = after_destroy; st->fin.n++; } @@ -3757,27 +3766,33 @@ static ScrError *scr_stream_finish_status(ScrStream *s) { /* Report the watchers. `close_step_only` is the close-step notification of a * stream that does not emit 'close': only the watchers that asked for it fire, - * and the others stay registered (Node's finished() stays pending there). */ -static void scr_stream_notify_finished_mode(ScrStream *s, bool close_step_only) { + * and the others stay registered (Node's finished() stays pending there). + * `late_too` adds the watchers registered after the stream was destroyed, + * which Node's eos answers from the state it inspects at registration even + * though a watcher registered before the destroy stays pending. */ +static void scr_stream_notify_finished_mode(ScrStream *s, bool close_step_only, bool late_too) { ScrStreamState *st = s->st; if (st->fin.n == 0) return; ScrClosure **cbs = st->fin.cb; ScrStreamErrInv *invs = st->fin.inv; bool *close_steps = st->fin.close_step; + bool *after_destroys = st->fin.after_destroy; size_t n = st->fin.n; st->fin.cb = NULL; st->fin.inv = NULL; st->fin.close_step = NULL; + st->fin.after_destroy = NULL; st->fin.n = 0; st->fin.cap = 0; ScrError *err = scr_stream_finish_status(s); size_t kept = 0; for (size_t i = 0; i < n; i++) { - if (close_step_only && !close_steps[i]) { + if (close_step_only && !close_steps[i] && !(late_too && after_destroys[i])) { /* Still waiting for a report Node would not give at the close step. */ cbs[kept] = cbs[i]; invs[kept] = invs[i]; close_steps[kept] = close_steps[i]; + after_destroys[kept] = after_destroys[i]; kept++; continue; } @@ -3789,17 +3804,19 @@ static void scr_stream_notify_finished_mode(ScrStream *s, bool close_step_only) free(cbs); free(invs); free(close_steps); + free(after_destroys); return; } st->fin.cb = cbs; st->fin.inv = invs; st->fin.close_step = close_steps; + st->fin.after_destroy = after_destroys; st->fin.n = kept; st->fin.cap = n; } static void scr_stream_notify_finished(ScrStream *s) { - scr_stream_notify_finished_mode(s, false); + scr_stream_notify_finished_mode(s, false, false); } static void scr_stream_finished_cleanup_fn(ScrClosure *self) { @@ -3813,6 +3830,8 @@ static void scr_stream_finished_cleanup_fn(ScrClosure *self) { memmove(&st->fin.inv[i], &st->fin.inv[i + 1], (st->fin.n - i - 1) * sizeof *st->fin.inv); memmove(&st->fin.close_step[i], &st->fin.close_step[i + 1], (st->fin.n - i - 1) * sizeof *st->fin.close_step); + memmove(&st->fin.after_destroy[i], &st->fin.after_destroy[i + 1], + (st->fin.n - i - 1) * sizeof *st->fin.after_destroy); st->fin.n--; break; } @@ -3824,11 +3843,18 @@ static void scr_stream_finished_cleanup_fn(ScrClosure *self) { static ScrClosure *scr_stream_finish_register(ScrStream *s, ScrClosure *cb /*moves*/, ScrStreamErrInv inv, bool close_step) { ScrStreamState *st = s->st; - scr_stream_fin_add(st, scr_closure_retain(cb), inv, close_step); + scr_stream_fin_add(st, scr_closure_retain(cb), inv, close_step, st->destroyed); bool will_close = scr_stream_will_emit_close(st); if ((close_step && st->close_emitted) || (st->emit_close && st->close_emitted) || - st->destroyed || (!will_close && st->w.finished && (!st->has_r || st->r.end_emitted))) { - /* Already terminal: Node's eos still calls back asynchronously. */ + (st->destroyed && (st->errored == NULL || st->error_emitted || st->close_emitted)) || + (!will_close && st->w.finished && (!st->has_r || st->r.end_emitted))) { + /* Already terminal: Node's eos still calls back asynchronously. A + * destroyed stream with a pending error waits for its own error tick, + * which reports the watcher and consumes the error as Node's eos + * does; ticking it here would drop the watcher first, so the + * AbortError asyncDispose destroyed with would emit unhandled. A + * cleanly destroyed stream, one whose error was already reported, or + * one whose close step already ran has nothing left to wait for. */ scr_st_tick(s, SCR_ST_FIN, NULL, NULL); } ScrClosure *cleanup = scr_closure_new((void *)&scr_stream_finished_cleanup_fn, 2); @@ -8713,13 +8739,17 @@ static void scr_stream_run_tick(ScrStreamTick *t) { if (w) scr_stream_next_fulfill(st, w, NULL, SCR_ENTRY_BYTES); } /* eos ordering: the finished()/pipeline watchers fire right after - * 'close' (Node's willEmitClose stance); a stream without the - * 'close' event reports at 'finish' or, for a destroy before it, - * not at all (Node leaves that watcher pending). */ + * 'close' (Node's willEmitClose stance). A destroyed stream with a + * recorded error reports the watchers registered after the destroy + * even without the 'close' event (Node's eos calls back with that + * error, including one a destroy callback swallowed), while a + * watcher that predates the destroy stays pending, as Node leaves + * it; a clean silent destroy answers only a close-step watcher (an + * adapter that has to let go). */ if (st->emit_close) { scr_stream_notify_finished(s); } else { - scr_stream_notify_finished_mode(s, true); + scr_stream_notify_finished_mode(s, true, st->destroyed && st->errored != NULL); } /* Fully closed: nothing calls the option callbacks again (Node's * contract), so drop them here — this breaks the reference cycle diff --git a/packages/runtime/src/scr_stream_iterator.c b/packages/runtime/src/scr_stream_iterator.c index c2358102c3..08cbae6ada 100644 --- a/packages/runtime/src/scr_stream_iterator.c +++ b/packages/runtime/src/scr_stream_iterator.c @@ -170,11 +170,14 @@ ScrDyn *scr_stream_dyn_iterator(ScrStream *s, ScrDyn *const *args, size_t argc) scr_dyn_arg_type_fail("options", "of type object", options); return NULL; } - ScrDyn *flag = scr_dyn_obj_get(options, "destroyOnReturn", 16); - if (flag) { - destroy_on_return = scr_dyn_truthy(flag); - scr_dyn_release(flag); - } + /* Node tests `options?.destroyOnReturn !== false`: only the boolean + * false turns the destroy off, so an explicit undefined (and every other + * non-false value) keeps Node's default cleanup. obj_get answers a + * BORROWED value; the key is the property's fifteen bytes, NUL + * excluded. */ + ScrDyn *flag = scr_dyn_obj_get(options, "destroyOnReturn", 15); + if (flag != NULL && flag->kind == SCR_DYN_BOOL && flag->v.b == false) + destroy_on_return = false; } if (scr_exc_pending()) return NULL; return scr_stream_iterator(s, destroy_on_return); diff --git a/packages/runtime/src/scr_stream_iterator.test.c b/packages/runtime/src/scr_stream_iterator.test.c new file mode 100644 index 0000000000..2d2a308f94 --- /dev/null +++ b/packages/runtime/src/scr_stream_iterator.test.c @@ -0,0 +1,75 @@ +#undef NDEBUG +#include "scr_runtime.h" +#include "scr_stream.h" +#include "scr_string_methods.h" + +#include +#include +#include + +/* scr_stream.c links the readline unit for its terminal streams; that unit + * reaches the regex engine's escape stripping, which this fixture never + * runs. Answer the one symbol here instead of linking a second engine. */ +ScrStr *scr_util_strip_vt(const ScrDyn *input) { + (void)input; + return NULL; +} + +/* The destroyed answer of an early return() over options carrying `value` + * (or no destroyOnReturn member at all). The graph is leaked deliberately; + * the fixture exits without the collector teardown below. */ +static bool destroyed_by_return(ScrDyn *value, bool present) { + ScrStream *s = scr_stream_new_readable(1, true, true, NULL, NULL, NULL, NULL); + ScrDyn *options = scr_dyn_new_obj(); + if (present) scr_dyn_obj_set(options, "destroyOnReturn", 15, value); + ScrDyn *iterator = scr_stream_dyn_iterator(s, &options, 1); + assert(iterator != NULL); + assert(!scr_exc_pending()); + ScrDyn *return_fn = scr_dyn_obj_get(iterator, "return", 6); + assert(return_fn != NULL && return_fn->kind == SCR_DYN_FUNC); + (void)scr_dyn_call(return_fn, NULL, 0, "return"); + return scr_stream_prop(s, "destroyed") != 0; +} + +/* Only the boolean false turns the destroy off, as Node tests + * `options?.destroyOnReturn !== false`: an explicit undefined, null, zero + * or any other non-false value keeps the default cleanup. */ +static void destroy_on_return_follows_node(void) { + assert(!destroyed_by_return(scr_dyn_new_bool(false), true)); + assert(destroyed_by_return(scr_dyn_new_bool(true), true)); + assert(destroyed_by_return(scr_dyn_undefined(), true)); + assert(destroyed_by_return(scr_dyn_new_null(), true)); + assert(destroyed_by_return(scr_dyn_new_num(0), true)); + assert(destroyed_by_return(NULL, false)); +} + +/* JSON can spell a property name with a trailing NUL, which the old 16-byte + * lookup matched. Its value was released even though obj_get borrows it, so + * dropping the options object freed the string a second time. */ +static void borrowed_value_is_not_released(void) { + static const char nul_suffixed[] = "destroyOnReturn\0"; + ScrDyn *options = scr_dyn_new_obj(); + ScrDyn *value = scr_dyn_new_str(scr_str_new("yes", 3)); + scr_dyn_obj_set(options, nul_suffixed, sizeof nul_suffixed - 1, value); + scr_dyn_release(value); + ScrDyn *iterator = scr_stream_dyn_iterator(NULL, &options, 1); + assert(iterator != NULL); + assert(!scr_exc_pending()); + scr_dyn_release(iterator); + scr_dyn_release(options); +} + +int main(void) { + scr_init(); + scr_lib_init(0, NULL); + /* The borrowed-value case runs first: with the release bug present it is + * the sanitizer that reports, before the option cases below. */ + borrowed_value_is_not_released(); + destroy_on_return_follows_node(); + puts("stream iterator options parse without a borrowed release"); + fflush(stdout); + /* The fixture leaves the process-wide runtime's event loop and collector + * unrun; the assertions above are the contract, so exit without the + * teardown the entry point would perform. */ + _exit(0); +} diff --git a/packages/runtime/src/scr_stream_iterator.test.ts b/packages/runtime/src/scr_stream_iterator.test.ts new file mode 100644 index 0000000000..974365a9c3 --- /dev/null +++ b/packages/runtime/src/scr_stream_iterator.test.ts @@ -0,0 +1,66 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { expect, test } from "vitest"; +import { EXECUTABLE_RUNTIME_SOURCES } from "../../compiler/src/backend/native-toolchain.js"; + +const exec = promisify(execFile); + +/* The dynamic readable.iterator options parser reads a property from an + * untrusted object: its lookup must use the property's byte length and the + * value obj_get yields is borrowed. The fixture builds the NUL-suffixed + * property JSON can spell; a release of the borrowed value is a double free + * at options teardown, which the sanitized run proves. */ +test.skipIf(process.platform === "win32")( + "dynamic readable.iterator options borrow their property value", + async () => { + const dir = await mkdtemp(join(tmpdir(), "scriptc-stream-iterator-")); + try { + const bin = join(dir, "stream-iterator"); + await exec( + "clang", + [ + "-std=c11", + "-O1", + "-fsanitize=address", + "-Wno-deprecated-declarations", + ...(process.platform === "linux" ? ["-D_GNU_SOURCE"] : []), + ...[ + "scr_stream_iterator.test.c", + "scr_stream_iterator.c", + "scr_stream.c", + "scr_stream_ops.c", + "scr_stream_defaults.c", + "scr_symbol.c", + "scr_events.c", + "scr_events_emitter.c", + "scr_async_dyn.c", + "scr_assert.c", + "scr_dyn_handle.c", + "scr_readline.c", + "scr_readline_tty.c", + ...EXECUTABLE_RUNTIME_SOURCES, + ].map((name) => join(import.meta.dirname, name)), + ...(process.platform === "linux" ? ["-lm"] : []), + "-o", + bin, + ], + { maxBuffer: 64 << 20 }, + ); + const result = await exec(bin, [], { + timeout: 60_000, + env: { + ...process.env, + UBSAN_OPTIONS: "halt_on_error=1", + ASAN_OPTIONS: "detect_leaks=0", + }, + }); + expect(result.stdout).toBe("stream iterator options parse without a borrowed release\n"); + expect(result.stderr).toBe(""); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, +); diff --git a/packages/runtime/src/scr_test.c b/packages/runtime/src/scr_test.c index ffc4df7dda..54357a41f0 100644 --- a/packages/runtime/src/scr_test.c +++ b/packages/runtime/src/scr_test.c @@ -199,13 +199,32 @@ struct ScrTestCtx { ScrPromise *plan_met; /* owned */ }; -/* t.signal's abort unit face (scr_abort.c). The compiler links that unit +/* t.signal's abort unit face (scr_fetch.c). The compiler links that unit * only for a program that reads a test's signal (the abortSignal runtime * feature), so these declarations are weak: a program without it leaves - * them null, and nothing else in the runner touches them. */ + * them null, and nothing else in the runner touches them. Mach-O refuses an + * undefined weak reference, so Apple gets weak definitions and the unit's + * linked flag as the capability test. */ +#if defined(__APPLE__) +__attribute__((weak)) int scr_dyn_abort_unit_linked = 0; +__attribute__((weak)) ScrDyn *scr_test_abort_controller_new(void) { return NULL; } +__attribute__((weak)) ScrDyn *scr_test_abort_controller_signal(ScrDyn *controller) { + (void)controller; + return NULL; +} +__attribute__((weak)) void scr_test_abort_controller_abort(ScrDyn *controller) { + (void)controller; +} +static bool scr_test_abort_available(void) { return scr_dyn_abort_unit_linked != 0; } +#else extern ScrDyn *scr_test_abort_controller_new(void) __attribute__((weak)); extern ScrDyn *scr_test_abort_controller_signal(ScrDyn *controller) __attribute__((weak)); extern void scr_test_abort_controller_abort(ScrDyn *controller) __attribute__((weak)); +static bool scr_test_abort_available(void) { + return scr_test_abort_controller_new != NULL && scr_test_abort_controller_signal != NULL && + scr_test_abort_controller_abort != NULL; +} +#endif /* Aborts a test's t.signal when it finished, timed out or was cancelled, as * Node's Test#run does for every non-root test (its hooks see the signal @@ -214,7 +233,7 @@ extern void scr_test_abort_controller_abort(ScrDyn *controller) __attribute__((w static void scr_test_abort_now(ScrTestCtx *t) { if (!t) return; t->signal_aborted = true; - if (t->abort_controller && scr_test_abort_controller_abort) + if (t->abort_controller && scr_test_abort_available()) scr_test_abort_controller_abort(t->abort_controller); } @@ -3950,13 +3969,12 @@ double scr_test_worker_id(void) { * the checked-dynamic handle rule (tag + pointer). +1, or undefined when * the unit is absent. */ ScrDyn *scr_test_ctx_signal(ScrTestCtx *t) { - if (!scr_test_abort_controller_new || !scr_test_abort_controller_signal) - return scr_dyn_undefined(); + if (!scr_test_abort_available()) return scr_dyn_undefined(); if (!t->abort_controller) { t->abort_controller = scr_test_abort_controller_new(); /* The test may have finished before anything read its signal: the * controller made now starts aborted then. */ - if (t->signal_aborted && scr_test_abort_controller_abort) + if (t->signal_aborted && scr_test_abort_available()) scr_test_abort_controller_abort(t->abort_controller); } return scr_test_abort_controller_signal(t->abort_controller); diff --git a/tests/corpus/fs-watch-ref-unref.ts b/tests/corpus/fs-watch-ref-unref.ts index dc78722ae1..9f110bc502 100644 --- a/tests/corpus/fs-watch-ref-unref.ts +++ b/tests/corpus/fs-watch-ref-unref.ts @@ -4,7 +4,10 @@ // unref'd watcher still delivers events while something else holds the // loop, and the program ends with it still open — nothing reffed is left. // Event counts and coalescing stay unobserved, as elsewhere; only "did one -// arrive" is printed. +// arrive" is printed. Each write repeats until the watcher answers: a write +// made right after watch() can precede the platform event stream's start +// (Node's FSEvents watcher on macOS misses it), and a single write made the +// sections race that start. The event itself is awaited, not a fixed timer. import * as fs from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; @@ -13,31 +16,69 @@ const dir = fs.mkdtempSync(join(tmpdir(), "scr-watch-ref-")); const file = join(dir, "data.txt"); fs.writeFileSync(file, "a"); -// ref(): nothing else holds the loop here, so the event below arrives only -// while the reffed watcher keeps the process running. -const reffed = fs.watch(file, { persistent: false }, () => { +// A watcher callback's first delivery: the promise settles on the event, or +// after a generous timeout so a broken watch fails the corpus instead of +// hanging it. The timer is unref'd: a section whose reffed watcher stopped +// holding the loop ends the process instead of being kept alive by the +// guard. +function firstEvent( + label: string, + abandon?: () => void, +): { ready: Promise; arrived: () => void } { + let arrived: () => void = () => {}; + const ready = new Promise((resolve) => { + const timer = setTimeout(() => { + console.log(`${label} timed out`); + abandon?.(); + resolve(); + }, 5000); + timer.unref(); + arrived = () => { + clearTimeout(timer); + resolve(); + }; + }); + return { ready, arrived }; +} + +// ref(): nothing else holds the loop here — both the guard timer and the +// repeated-write ticker are unref'd — so the event arrives only while the +// reffed watcher keeps the process running. +let reffed: fs.FSWatcher; +const reffedFirst = firstEvent("reffed watcher", () => reffed.close()); +reffed = fs.watch(file, { persistent: false }, () => { reffed.close(); reffed.close(); console.log("reffed watcher delivered"); + reffedFirst.arrived(); }); reffed.ref(); fs.appendFileSync(file, "x"); +const reffedTicker = setInterval(() => fs.appendFileSync(file, "x"), 20); +reffedTicker.unref(); +await reffedFirst.ready; +clearInterval(reffedTicker); // Two watchers on one path share the kernel's watch: closing one leaves -// the other delivering. +// the other delivering. The second's event is awaited; the closed one has +// had its chance by then. let peerClosed = 0; let peerOpen = 0; +const peerFirst = firstEvent("peer watcher"); const first = fs.watch(file, () => { peerClosed++; }); const second = fs.watch(file, () => { peerOpen++; + peerFirst.arrived(); }); first.close(); -await new Promise((resolve) => { - fs.appendFileSync(file, "z"); - setTimeout(resolve, 100); -}); +fs.appendFileSync(file, "z"); +const peerTicker = setInterval(() => fs.appendFileSync(file, "z"), 20); +peerTicker.unref(); +await peerFirst.ready; +clearInterval(peerTicker); +await new Promise((resolve) => setTimeout(resolve, 50)); console.log("peer after close", peerClosed === 0, peerOpen > 0); second.close(); diff --git a/tests/fixtures/dual-run/refused.ts b/tests/fixtures/dual-run/refused.ts index 656474252a..0920a2bd1b 100644 --- a/tests/fixtures/dual-run/refused.ts +++ b/tests/fixtures/dual-run/refused.ts @@ -1,4 +1,12 @@ -// MessageChannel has no scriptc lowering yet: the build refuses with SC2020, -// which the program API reports as a DualRunBuildError. -const channel = new MessageChannel(); -console.log(channel.port1); +// WebSocket is a Node global the native runtime does not provide: the +// ambient declaration makes the name a global (as @types/node does), and +// constructing it refuses with SC2020, which the program API reports as a +// DualRunBuildError. +interface HostSocket { + readonly readyState: number; +} +declare var WebSocket: { + new (url: string): HostSocket; +}; +const socket = new WebSocket("ws://localhost:8080"); +console.log(socket.readyState); diff --git a/tests/harness/errors.test.ts b/tests/harness/errors.test.ts index b2be8d7a64..61db6066cd 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -289,9 +289,9 @@ level2(-2); `, ); expect(r.exitCode).toBe(1); - expect(r.stdout).toBe("3\n"); + expect(r.stdout).toBe("4\n"); expect(r.stderr).toMatch( - /^Uncaught RangeError: negative input: -2\n at helper \(.*uncaught-frames\.ts\)\n at level2 \(.*uncaught-frames\.ts\)\n$/, + /^Uncaught RangeError: negative input: -2\n at helper \(.*uncaught-frames\.ts:\d+:\d+\)\n at level2 \(.*uncaught-frames\.ts:\d+:\d+\)\n at .*uncaught-frames\.ts:\d+:\d+\n$/, ); }); @@ -308,9 +308,9 @@ setTimeout(() => { `, ); expect(r.exitCode).toBe(1); - expect(r.stdout).toBe("1\n"); + expect(r.stdout).toBe("2\n"); expect(r.stderr).toMatch( - /^Uncaught Error: callback failed in timer\n at fail \(.*uncaught-timer-frames\.ts\)\n/, + /^Uncaught Error: callback failed in timer\n at fail \(.*uncaught-timer-frames\.ts:\d+:\d+\)\n/, ); }); @@ -339,7 +339,7 @@ main(); expect(r.exitCode).toBe(1); expect(r.stdout).toBe("2\n"); expect(r.stderr).toMatch( - /^Unhandled promise rejection: TypeError: bad n 5\n at load \(.*unhandled-rejection-frames\.ts\)\n$/, + /^Unhandled promise rejection: TypeError: bad n 5\n at load \(.*unhandled-rejection-frames\.ts:\d+:\d+\)\n$/, ); }); @@ -354,9 +354,9 @@ new Promise((resolve, reject) => reject(make())); `, ); expect(r.exitCode).toBe(1); - expect(r.stdout).toBe("2\n"); + expect(r.stdout).toBe("3\n"); expect(r.stderr).toMatch( - /^Unhandled promise rejection: Error: boom\n at make \(.*unhandled-dyn-rejection-frames\.ts\)\n at \(.*unhandled-dyn-rejection-frames\.ts\)\n$/, + /^Unhandled promise rejection: Error: boom\n at make \(.*unhandled-dyn-rejection-frames\.ts:\d+:\d+\)\n at \(.*unhandled-dyn-rejection-frames\.ts:\d+:\d+\)\n at .*unhandled-dyn-rejection-frames\.ts:\d+:\d+\n$/, ); }); }); @@ -3614,16 +3614,15 @@ console.log(count(require("./lib.cjs"))); describe("builtin constructor values (JS lane)", () => { test("constructing one without a lowering throws the refusal that names it", async () => { - // `AsyncResource` has no lowering, so a JavaScript source reads the - // import as a function value that refuses when it is used + // `Intl.PluralRules` has no lowering, so a JavaScript source reads the + // global class as a value that refuses when it is constructed // (builtin-function-fences.ts). Node constructs the class, so "… is not // a constructor" would be the wrong error class and a fabricated // message: the construction is refused by name where it is written. const r = await compileAndRun( "builtin-token-construction", - `import { AsyncResource } from "node:async_hooks"; -function run() { - return new AsyncResource("demo"); + `function run() { + return new Intl.PluralRules("en"); } console.log("before"); run(); @@ -3633,7 +3632,7 @@ run(); expect(r.stdout).toBe("before\n"); expect(r.exitCode).toBe(1); expect(r.stderr).toMatch( - /^Uncaught Error: 'new async_hooks\.AsyncResource' is part of the standard library types but has no scriptc lowering yet \[SC2020 at .*builtin-token-construction\.mjs:3\]\n$/, + /^Uncaught Error: 'new Intl\.PluralRules' is part of the standard library types but has no scriptc lowering yet \[SC2020 at .*builtin-token-construction\.mjs:2\]\n$/, ); }); @@ -3792,10 +3791,11 @@ refuse("assign", () => Object.assign(Date.prototype, { getTime: () => 42 })); }); // WebCrypto's native slice is crypto.subtle's secret-key methods and its -// ECDSA, Ed25519 and RSA algorithms. Algorithms Node recognizes outside -// that slice reject with a coded SC2020 -// Error instead of a Node-shaped success, and a JavaScript call of a -// method outside it meets its named fence when it runs. +// ECDSA, Ed25519, X448 and RSA algorithms. Algorithms Node recognizes +// outside that slice reject with a coded SC2020 Error instead of a +// Node-shaped success, and a JavaScript call of a method outside it meets +// its named fence when it runs. An X448 call that the key's usage refuses +// still reports Node's ExperimentalWarning as the algorithm normalizes. // Node's own rejections (unknown names, bad usages) are corpus-pinned // (6292, 6294); these refusals have no Node twin, so they live here. describe("WebCrypto refusals (JS lane)", () => { @@ -3832,12 +3832,17 @@ await attempt("unwrap an ecdsa key", () => "mjs", ); expect(r.exitCode).toBe(0); - expect(r.stderr).toBe(""); + // X448 normalizes before the refusal, so the runtime reports Node's + // one-per-process ExperimentalWarning (its prefix carries the pid). + expect(r.stderr.replace(/\(node:\d+\)/, "(node:PID)")).toBe( + "(node:PID) ExperimentalWarning: The X448 Web Crypto API algorithm is an experimental feature and might change at any time\n" + + "(Use `node --trace-warnings ...` to show where the warning was created)\n", + ); expect(r.stdout).toBe( "ed448 Error SC2020 crypto.subtle.sign with the Ed448 algorithm is not supported yet\n" + "ecdsa with an hmac key InvalidAccessError 15 Key algorithm mismatch\n" + "cshake TypeError ERR_MISSING_OPTION Failed to normalize algorithm: passed algorithm cannot be converted to 'CShakeParams' because 'outputLength' is required in 'CShakeParams'.\n" + - "x448 bits Error SC2020 crypto.subtle.deriveBits with the X448 algorithm is not supported yet\n" + + "x448 bits InvalidAccessError 15 baseKey does not have deriveBits usage\n" + "ecdh bits InvalidAccessError 15 baseKey does not have deriveBits usage\n" + "rsa-oaep wrap Error SC2020 crypto.subtle.wrapKey with the RSA-OAEP algorithm is not supported yet\n" + "wrap an ecdsa key Error SC2020 crypto.subtle.wrapKey with an ECDSA, Ed25519 or RSA key is not supported yet\n" +