Compile async_hooks execution ids, createHook and asyncWrapProviders natively (#3732)

* Compile async_hooks execution ids, createHook and asyncWrapProviders natively

* Evaluate a createHook literal's members in source order and rehash promise resources into the new capacity

* Commit an immediate's queue slot only after its init hook has run

* Retire a promise's async resource when the promise is destroyed

* Keep the runtime sound when an async hook reenters it

* Release the auto-allocated buffer of a detached byte read
This commit is contained in:
Chris Tate
2026-11-18 21:45:54 -06:00
committed by GitHub
parent 01a5b9d9b0
commit b029955fef
35 changed files with 1652 additions and 95 deletions
@@ -11,4 +11,5 @@
An `http2` server's `'session'` and `'stream'` events and the compatibility API's request handler see the context of its `listen()` call; a server stream's own events, and its compatibility request's and response's, run with no store, as in Node.
`AsyncResource` and its `runInAsyncScope`, `bind`, `emitDestroy`, `asyncId` and `triggerAsyncId` members run natively, and `asyncLocalStorage.withScope` answers a `RunScope` whose `dispose()` (or `[Symbol.dispose]`, for a `using` declaration) restores the store.
The store context an `AsyncResource` captures lives exactly as long as the resource value does: a resource the program drops releases it, and one still held at exit is released there.
`async_hooks.createHook` instrumentation has no lowering yet.
`async_hooks.createHook` reports init, before, after, destroy and promiseResolve for timers, immediates, next ticks and promises, and `executionAsyncId`/`triggerAsyncId` answer those executions' ids.
A hook's `resource` is a plain object, an await of a non-promise value still reports the enclosing execution's ids, and `executionAsyncResource` has no value to answer.
+44 -44
View File
@@ -1531,9 +1531,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1554,9 +1554,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1577,9 +1577,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1600,9 +1600,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1623,9 +1623,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1647,7 +1647,7 @@
},
"static": {
"status": "partial",
"detail": "Implemented by a dedicated static compiler/runtime path.",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
@@ -1670,7 +1670,7 @@
},
"static": {
"status": "partial",
"detail": "Implemented by a dedicated static compiler/runtime path.",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
@@ -1692,9 +1692,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1715,9 +1715,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1738,9 +1738,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1761,9 +1761,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1807,9 +1807,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1830,9 +1830,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1853,9 +1853,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "supported",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -1899,9 +1899,9 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"detail": "No static compiler lowering is registered for this API yet.",
"verification": "registry-gap"
"status": "partial",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -18016,9 +18016,9 @@
"anchor": "err_async_callback",
"nodeStability": null,
"static": {
"status": "not-implemented",
"detail": "Not implemented in scriptc's static module-loader subset yet.",
"verification": "declared-gap"
"status": "supported",
"detail": "Implemented for the documented scriptc module-loader subset.",
"verification": "test-backed"
}
},
{
@@ -2076,8 +2076,8 @@
"tests/corpus/7388-als-http2-compat-events.mjs",
"tests/corpus/7389-als-http2-secure-events.mjs",
"tests/corpus/7391-als-response-end-and-finished.mjs",
"tests/corpus/async-local-storage-audit.cjs",
"tests/harness/node-test.test.ts"
"tests/corpus/async-hooks-execution-ids.cjs",
"tests/corpus/async-local-storage-audit.cjs"
]
},
"anchorSource": "chapter"
@@ -2238,8 +2238,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.AsyncHook",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2284,8 +2287,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.init",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2307,8 +2313,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.type",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2330,8 +2339,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.triggerAsyncId",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2353,8 +2365,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.resource",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2400,9 +2415,9 @@
},
"static": {
"status": "partial",
"evidence": "compiler-dedicated:before",
"evidence": "compiler-feature:async_hooks.before",
"tests": [
"tests/harness/node-test.test.ts"
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
@@ -2426,9 +2441,9 @@
},
"static": {
"status": "partial",
"evidence": "compiler-dedicated:after",
"evidence": "compiler-feature:async_hooks.after",
"tests": [
"tests/harness/node-test.test.ts"
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
@@ -2451,8 +2466,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.destroy",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2474,8 +2492,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.promiseResolve",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2497,8 +2518,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.asyncHook.enable",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2520,8 +2544,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.asyncHook.disable",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2566,8 +2593,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.async_hooks.executionAsyncId",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2589,8 +2619,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.async_hooks.triggerAsyncId",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -2612,8 +2645,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "supported",
"evidence": "compiler-feature:async_hooks.asyncWrapProviders",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "ancestor"
},
@@ -2676,8 +2712,11 @@
"inherited": true
},
"static": {
"status": "not-implemented",
"evidence": "compiler-unmatched:async_hooks"
"status": "partial",
"evidence": "compiler-feature:async_hooks.async_hooks.createHook",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
@@ -34592,6 +34631,7 @@
"tests/corpus/8783-child-max-buffer-refused-arguments.ts",
"tests/corpus/8922-child-max-buffer-async.ts",
"tests/corpus/9872-child-stream-pause-max-buffer.ts",
"tests/corpus/async-hooks-execution-ids.cjs",
"tests/corpus/caught-system-error-fields.ts",
"tests/corpus/compat-error-capture-stack-trace.mjs",
"tests/corpus/compat-error-class-surface.mjs",
@@ -35450,8 +35490,11 @@
"anchor": "err_async_callback",
"nodeStability": null,
"static": {
"status": "not-implemented",
"evidence": "compiler-feature:errors.ERR_ASYNC_CALLBACK"
"status": "supported",
"evidence": "compiler-feature:errors.ERR_ASYNC_CALLBACK",
"tests": [
"tests/corpus/async-hooks-execution-ids.cjs"
]
},
"anchorSource": "exact"
},
+6 -1
View File
@@ -954,7 +954,7 @@
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_WORKER_UNSUPPORTED_OPERATION`"], "status": "supported", "evidence": ["tests/corpus/compat-errors-worker.mjs"] },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`MODULE_NOT_FOUND`"], "status": "supported", "evidence": ["tests/corpus/2195-require-missing-package/main.mjs"] },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_ACCESS_DENIED`"], "status": "not-implemented", "reason": "Raised by the permission model, which is not provided (the permissions chapter's policy)." },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_ASYNC_CALLBACK`"], "status": "not-implemented", "reason": "Raised by async_hooks.createHook(), which is refused by name." },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_ASYNC_CALLBACK`"], "status": "supported", "evidence": ["tests/corpus/async-hooks-execution-ids.cjs"] },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED`", "`ERR_INVALID_RETURN_PROPERTY`", "`ERR_INVALID_RETURN_PROPERTY_VALUE`", "`ERR_LOADER_CHAIN_INCOMPLETE`"], "status": "not-implemented", "evidence": ["tests/diagnostics/compat-absent-node-apis.ts"], "reason": "Raised by module customization hooks; module.register() is refused by name." },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_ASYNC_TYPE`", "`ERR_INVALID_ASYNC_ID`"], "status": "not-implemented", "evidence": ["tests/diagnostics/compat-absent-node-apis.ts"], "reason": "Raised by the AsyncResource constructor, which is refused by name." },
{ "chapter": "errors", "parent": "Node.js error codes", "signatures": ["`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`", "`ERR_CONTEXT_NOT_INITIALIZED`", "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`", "`ERR_MODULE_LINK_MISMATCH`", "`ERR_SCRIPT_EXECUTION_INTERRUPTED`", "`ERR_SCRIPT_EXECUTION_TIMEOUT`", "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`", "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`", "`ERR_VM_MODULE_ALREADY_LINKED`", "`ERR_VM_MODULE_CACHED_DATA_REJECTED`", "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`", "`ERR_VM_MODULE_DIFFERENT_CONTEXT`", "`ERR_VM_MODULE_LINK_FAILURE`", "`ERR_VM_MODULE_NOT_MODULE`", "`ERR_VM_MODULE_STATUS`"], "status": "by-design", "policy": "vm", "reason": "Raised by node:vm contexts, scripts and modules, which a compiled binary has no evaluator for (the vm chapter's policy)." },
@@ -1004,6 +1004,11 @@
{ "chapter": "errors", "parent": "Other OpenSSL Errors", "signatures": ["`OUT_OF_MEM`"], "status": "not-implemented", "reason": "A certificate verification result the TLS engine does not report under OpenSSL's name; it reports an expired certificate, a self-signed certificate or chain, a leaf it cannot verify, an untrusted issuer and a host mismatch." },
{ "chapter": "async_context", "parent": "Class: `AsyncLocalStorage`", "signatures": ["Usage with `async/await`"], "status": "not-applicable" },
{ "chapter": "async_context", "parent": "Class: `AsyncResource`", "signatures": ["Using `AsyncResource` for a `Worker` thread pool", "Integrating `AsyncResource` with `EventEmitter`"], "status": "not-applicable" },
{ "chapter": "async_hooks", "parent": "Async hooks", "symbols": ["async_hooks.createHook", "AsyncHook"], "status": "partial", "evidence": ["tests/corpus/async-hooks-execution-ids.cjs"], "reason": "createHook validates its callbacks with Node's errors (its destructuring TypeError and ERR_ASYNC_CALLBACK) and answers an AsyncHook; the hook's callbacks fire for Timeouts, Immediates, next ticks and promises." },
{ "chapter": "async_hooks", "parent": "Class: `AsyncHook`", "symbols": ["asyncHook.enable", "asyncHook.disable"], "status": "partial", "evidence": ["tests/corpus/async-hooks-execution-ids.cjs"], "reason": "Both flip the hook and answer the hook, as Node's methods do." },
{ "chapter": "async_hooks", "signatures": ["`init(asyncId, type, triggerAsyncId, resource)`", "`type`", "`triggerAsyncId`", "`resource`", "`before(asyncId)`", "`after(asyncId)`", "`destroy(asyncId)`", "`promiseResolve(asyncId)`"], "status": "partial", "evidence": ["tests/corpus/async-hooks-execution-ids.cjs"], "reason": "init, before, after, destroy and promiseResolve fire with numeric ids and the documented argument shapes for Timeouts, Immediates, next ticks and promises. Not yet tracked: the one-microtask hop a non-thenable await takes, queueMicrotask fibers and the hosted Node-island timer bridge; a hook's `resource` is a plain object rather than each kind's own." },
{ "chapter": "async_hooks", "signatures": ["`async_hooks.executionAsyncId()`", "`async_hooks.triggerAsyncId()`"], "status": "partial", "evidence": ["tests/corpus/async-hooks-execution-ids.cjs"], "reason": "Answers the execution's ids at the top level, inside timer, immediate and next-tick callbacks, and across promises' reactions and awaits of real promises; an await of a non-promise value still reports the enclosing execution's ids, and the ids are scriptc's own opaque sequence (Node's counter also numbers its module-loading internals)." },
{ "chapter": "async_hooks", "signatures": ["`asyncWrapProviders` Returns: A map of provider types to the corresponding numeric id. This map contains all the event types that might be emitted by the `async_hooks.init()` event."], "status": "supported", "evidence": ["tests/corpus/async-hooks-execution-ids.cjs"], "reason": "Answers Node 24's published provider table as a null-prototype object whose names are its own enumerable properties; a compiled binary reports that table rather than provider ids of its own." },
{ "chapter": "async_hooks", "parent": "`async_hooks.createHook(options)`", "signatures": ["Printing in `AsyncHook` callbacks"], "status": "not-applicable" },
{ "chapter": "buffer", "parent": "Buffers and TypedArrays", "signatures": ["Buffer methods are callable with `Uint8Array` instances"], "status": "not-applicable" },
{ "chapter": "buffer", "parent": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", "signatures": ["What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?"], "status": "not-applicable" },
@@ -667,6 +667,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] {
// Fetch-referencing programs register native fetch before main.
// Runtime selection compiles scr_fetch.c on the same predicate.
const usesFetch = runtimeFeatures.fetch;
const usesAsyncHooks = runtimeFeatures.asyncHooks;
// URL programs give the host parser the IDNA unit's ToASCII.
const usesUrlIdna = runtimeFeatures.urlIdna;
// Programs whose checked-dynamic reads answer Buffer.prototype methods by
@@ -759,6 +760,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] {
if (usesHttp2) emitter.declare(`declare void @scr_http2_dyn_install()`);
if (usesHttp) emitter.declare(`declare void @scr_http_dyn_install()`);
if (usesFetch) emitter.declare(`declare void @scr_fetch_install()`);
if (usesAsyncHooks) emitter.declare(`declare void @scr_async_hooks_install()`);
if (usesUrlIdna) emitter.declare(`declare void @scr_url_idna_install()`);
if (usesDynBufferMembers) emitter.declare(`declare void @scr_bytes_buffer_members_install()`);
if (usesSymbolFor) emitter.declare(`declare void @scr_sym_for_install()`);
@@ -1556,6 +1558,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] {
...(emitter.ffiHasForeignCallback ? [` call void @scr_ffi_install()`] : []),
...(snapshotsTlsCa ? [` call void @scr_tls_ca_install()`] : []),
...(usesFetch ? [` call void @scr_fetch_install()`] : []),
...(usesAsyncHooks ? [` call void @scr_async_hooks_install()`] : []),
...(usesUrlIdna ? [` call void @scr_url_idna_install()`] : []),
...(usesDynBufferMembers ? [` call void @scr_bytes_buffer_members_install()`] : []),
...(usesSymbolFor ? [` call void @scr_sym_for_install()`] : []),
@@ -1670,6 +1670,7 @@ export function emitLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlValue {
case "timers":
case "async":
case "als":
case "ah":
case "ar":
case "te":
return host.emitAsyncContextLibCall(e);
@@ -2184,6 +2184,15 @@ export const LIB_FN_SYMS: Record<string, string> = {
"ar.asyncId": "scr_ar_async_id",
"ar.triggerAsyncId": "scr_ar_trigger_id",
"dc.chanBindStore": "scr_dc_chan_bind_store",
// node:async_hooks (scr_async_dyn.c / scr_async.c): the hook registry and
// the execution-id pair.
"ah.createHook": "scr_ah_create",
"ah.createHookParts": "scr_ah_parts",
"ah.enable": "scr_ah_enable",
"ah.disable": "scr_ah_disable",
"ah.providers": "scr_ah_providers",
"ah.executionId": "scr_async_execution_id",
"ah.triggerId": "scr_async_execution_trigger",
"dc.chanUnbindStore": "scr_dc_chan_unbind_store",
"dc.chanRunStores": "scr_dc_chan_run_stores",
// node:trace_events (scr_async_dyn.c): native Tracing handles.
@@ -0,0 +1,177 @@
import { isBuiltinClassInstance } from "./receiver-types.js";
import * as ts from "../../ts7/adapter.js";
import { type Lowerer } from "../lowerer.js";
import { dynUndefinedExpr } from "../../../ir/build.js";
import { locOf } from "../../program.js";
import {
DYN,
F64,
type IrExpr,
type IrStmt,
type SrcLoc,
canBoxFuncIntoDyn,
canConvertToDyn,
} from "../../../ir/ir.js";
/** The createHook callbacks object as a checked-dynamic value. The record
* conversion boxes its function members by identity (the variable form the
* Node docs use); undefined and null pass through so the runtime raises
* Node's destructuring TypeError for them. */
function lowerHookCallbacks(lowerer: Lowerer, node: ts.Expression): IrExpr {
// Lower the literal with its own record type and convert that value: the
// record conversion boxes function members as the checked-dynamic
// functions the hook registry calls (the variable form the Node docs use
// goes through the same conversion).
const value = lowerer.lowerExpr(node);
if (value.type.kind === "dyn") return value;
return lowerer.coerceInto(node, value, DYN);
}
const HOOK_CALLBACK_NAMES = ["init", "before", "after", "destroy", "promiseResolve"] as const;
/** The five callbacks of an inline literal, evaluated in SOURCE order and
* passed in slot order. Null when the literal holds anything the member-by-
* member form cannot evaluate faithfully — a spread, a computed or quoted
* key, an accessor, or a duplicate name (Node's destructuring reads the last
* one) — which takes the object form instead.
*
* Node evaluates the literal's members in source order before createHook
* reads them, so every member's initializer is lowered into its own hidden
* local in that order (members the hook does not use included, for their
* side effects); the five slots then read the locals. */
function literalHookCallbacks(
lowerer: Lowerer,
e: ts.ObjectLiteralExpression,
): { stmts: IrStmt[]; args: IrExpr[] } | null {
const loc = locOf(e);
const slots = new Map<string, string>(); /* callback name → hidden local */
const named = new Set<string>();
const stmts: IrStmt[] = [];
for (const prop of e.properties.nodes) {
if (!ts.isIdentifier(prop.name)) return null; /* spread, computed, quoted, accessor */
const name = prop.name.text;
if (named.has(name)) return null; /* a later duplicate would win in Node */
named.add(name);
let value: IrExpr;
if (ts.isMethodDeclaration(prop)) {
value = boxHookCallback(lowerer, prop, lowerer.lowerLambda(prop, true));
} else if (ts.isShorthandPropertyAssignment(prop)) {
value = lowerer.lowerExprExpecting(prop.name as unknown as ts.Expression, DYN);
} else if (ts.isPropertyAssignment(prop)) {
value = lowerer.lowerExprExpecting(prop.initializer, DYN);
} else {
return null;
}
const local = lowerer.declareHiddenLocal(`%hook_${name}`, DYN);
stmts.push({ kind: "varDecl", localId: local.id, init: value, loc: locOf(prop) });
if ((HOOK_CALLBACK_NAMES as readonly string[]).includes(name)) slots.set(name, local.id);
}
const args: IrExpr[] = HOOK_CALLBACK_NAMES.map((name) => {
const localId = slots.get(name);
return localId === undefined
? dynUndefinedExpr(loc)
: { kind: "varRef", localId, type: DYN, loc };
});
return { stmts, args };
}
/** A lowered method value as a checked-dynamic function. */
function boxHookCallback(lowerer: Lowerer, node: ts.Node, value: IrExpr): IrExpr {
if (value.type.kind === "dyn") return value;
if (
value.type.kind === "func" &&
canBoxFuncIntoDyn(
value.type,
(id) => lowerer.shapes.get(id),
(id) => lowerer.unions.get(id),
)
) {
return { kind: "dynFrom", value, type: DYN, loc: value.loc };
}
if (
canConvertToDyn(
value.type,
(id) => lowerer.shapes.get(id),
(id) => lowerer.unions.get(id),
)
) {
return { kind: "dynFrom", value, type: DYN, loc: value.loc };
}
lowerer.unsupported(
"SC1090",
node,
`async_hooks callbacks of type '${lowerer.fmt(value.type)}' (a callback crosses as a dyn function)`,
);
}
/** node:async_hooks — createHook(callbacks), executionAsyncId() and
* triggerAsyncId(). The callbacks object crosses as a dyn value, so the
* runtime applies Node's own checks (its destructuring TypeError for
* undefined or null and ERR_ASYNC_CALLBACK for a non-function member), and
* the AsyncHook it answers is an f64 handle whose enable()/disable() lower
* through lowerAsyncHooksMethodCall. */
export function lowerAsyncHooksCall(
lowerer: Lowerer,
expr: ts.CallExpression,
bi: { module: string; member: string },
loc: SrcLoc,
): IrExpr | null {
if (bi.member === "executionAsyncId")
return { kind: "libCall", fn: "ah.executionId", args: [], type: F64, loc };
if (bi.member === "triggerAsyncId")
return { kind: "libCall", fn: "ah.triggerId", args: [], type: F64, loc };
if (bi.member === "createHook" && expr.arguments.nodes.length <= 1) {
const node = expr.arguments.nodes[0];
if (node !== undefined) {
let e = node;
while (ts.isParenthesizedExpression(e)) e = e.expression;
if (ts.isObjectLiteralExpression(e)) {
const parts = literalHookCallbacks(lowerer, e);
if (parts !== null) {
const call: IrExpr = {
kind: "libCall",
fn: "ah.createHookParts",
args: parts.args,
type: F64,
loc,
};
if (parts.stmts.length === 0) return call;
return { kind: "seqExpr", stmts: parts.stmts, result: call, type: F64, loc };
}
}
}
const callbacks =
node !== undefined ? lowerHookCallbacks(lowerer, node) : dynUndefinedExpr(loc);
return { kind: "libCall", fn: "ah.createHook", args: [callbacks], type: F64, loc };
}
return null;
}
/** Method calls on AsyncHook receivers: enable() and disable() over the
* f64 hook handle; each answers the hook (`this`), as Node's do. */
export function lowerAsyncHooksMethodCall(
lowerer: Lowerer,
call: ts.CallExpression,
access: ts.PropertyAccessExpression,
): IrExpr | null {
if (call.questionDotToken || access.questionDotToken) return null;
if (!isBuiltinClassInstance(lowerer, access.expression, "AsyncHook")) return null;
if (!lowerer.isStdlibMember(access)) return null;
const name = access.name.text;
if ((name === "enable" || name === "disable") && call.arguments.nodes.length === 0) {
const receiver = lowerer.lowerExprExpecting(access.expression, F64);
return {
kind: "libCall",
fn: name === "enable" ? "ah.enable" : "ah.disable",
args: [receiver],
type: F64,
loc: locOf(call),
};
}
lowerer.noLowering(
`AsyncHook.${name}`,
call,
"enable() and disable() are the supported AsyncHook members",
lowerer.checker.getSymbolAtLocation(access.name),
);
}
@@ -1,6 +1,7 @@
import { lowerFileUrlCall, lowerLegacyUrlCall } from "./url.js";
import { lowerReadlineCreateCall } from "./readline.js";
import { lowerDiagnosticsChannelCall } from "./async-context.js";
import { lowerAsyncHooksCall } from "./async-hooks.js";
import { lowerTraceEventsCall } from "./trace-events.js";
import { lowerTimersPromisesCall } from "./timers.js";
import {
@@ -298,6 +299,10 @@ export function lowerBuiltinModuleCall(
const lowered = lowerDiagnosticsChannelCall(lowerer, expr, bi, loc);
if (lowered) return lowered;
}
if (bi.module === "async_hooks") {
const lowered = lowerAsyncHooksCall(lowerer, expr, bi, loc);
if (lowered) return lowered;
}
if (bi.module === "trace_events") {
const lowered = lowerTraceEventsCall(lowerer, expr, bi, loc);
if (lowered) return lowered;
@@ -2249,6 +2249,8 @@ function lowerOrdinaryCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr {
// AsyncLocalStorage receivers — run/getStore/exit/enterWith over
// the f64 store handle.
lowerer.lowerAsyncLocalStorageMethodCall(expr, expr.expression) ??
// AsyncHook receivers — enable/disable over the f64 hook handle.
lowerer.lowerAsyncHooksMethodCall(expr, expr.expression) ??
// AsyncResource receivers — runInAsyncScope/bind/emitDestroy over
// the f64 resource handle.
lowerer.lowerAsyncResourceMethodCall(expr, expr.expression) ??
@@ -762,6 +762,7 @@ import {
lowerTracingChannelMethodCall,
lowerTracingChannelProperty,
} from "./builtins/async-context.js";
import { lowerAsyncHooksMethodCall } from "./builtins/async-hooks.js";
import { lowerDisposableStackNew } from "./builtins/disposable-stack.js";
import { lowerErrorCodeProperty, lowerErrorFunctionCall } from "./builtins/errors.js";
import { noteDateClassMethods } from "./builtins/date-classes.js";
@@ -25569,6 +25570,13 @@ export class Lowerer {
return lowerAsyncLocalStorageMethodCall(this, call, access);
}
lowerAsyncHooksMethodCall(
call: ts.CallExpression,
access: ts.PropertyAccessExpression,
): IrExpr | null {
return lowerAsyncHooksMethodCall(this, call, access);
}
lowerAsyncResourceMethodCall(
call: ts.CallExpression,
access: ts.PropertyAccessExpression,
@@ -418,6 +418,10 @@ export function unloweredModuleMemberValue(
loc: SrcLoc,
esmNamed: boolean,
): IrExpr {
// async_hooks.asyncWrapProviders: Node's published provider table, which
// the runtime builds exactly (scr_ah_providers).
if (bi.module === "async_hooks" && bi.member === "asyncWrapProviders")
return { kind: "libCall", fn: "ah.providers", args: [], type: DYN, loc };
const display = `${bi.module}.${bi.member}`;
const hint = builtinFenceHintOf(bi.module, bi.member);
const kind = nodeModuleMemberKind(bi.module, bi.member);
@@ -2414,6 +2414,15 @@ function buildBuiltinModuleFns(): BuiltinModuleFnTable {
// into the checked-dynamic tree (special-cased in lowerBuiltinModuleCall — the entries
// carry canonical shapes and route the dispatch). The Channel method
// surface lowers through lowerDiagnosticsChannelMethodCall/lowerDiagnosticsChannelProperty.
// node:async_hooks — the hook registry and the execution-id reads. The
// callbacks object crosses as a dyn value and AsyncHook values are f64
// handles (type-mapper.ts), so the members lower in
// lowerAsyncHooksMethodCall/lowerAsyncHooksCall.
async_hooks: {
createHook: { fn: "ah.createHook", params: [DYN], result: F64 },
executionAsyncId: { fn: "ah.executionId", params: [], result: F64 },
triggerAsyncId: { fn: "ah.triggerId", params: [], result: F64 },
},
diagnostics_channel: {
channel: { fn: "dc.channel", params: [STRING], result: F64 },
subscribe: { fn: "dc.subscribe", params: [STRING, DYN], result: VOID },
@@ -4778,6 +4778,20 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null {
) {
return F64;
}
// async_hooks.AsyncHook: a 1-based f64 handle into the runtime's hook
// registry (the AsyncLocalStorage story).
if (
psym !== undefined &&
psymName === "AsyncHook" &&
psym.declarations.some(
(d) =>
(ts.isInterfaceDeclaration(d) || ts.isClassDeclaration(d)) &&
ctx.isStdlibFile(ts.getSourceFileOfNode(d)) &&
isDeclaredInAmbientModule(d, "async_hooks"),
)
) {
return F64;
}
// async_hooks.AsyncResource: a checked-dynamic handle whose payload lives
// exactly as long as the value does, so a resource the program drops is
// reclaimed with everything it captured.
@@ -360,6 +360,13 @@ const MAY_THROW_LIB_FNS_PART_2: readonly IrLibFn[] = [
// %o's showHidden walk refuses the kinds whose hidden entries it cannot
// render.
"insp.dynHidden",
// diagnostics_channel: publish runs subscribers synchronously (a throw
// propagates — the documented divergence from triggerUncaughtException);
// the subscribe/unsubscribe forms throw Node's ERR_INVALID_ARG_TYPE for
// non-function subscribers.
// async_hooks.createHook validates its callbacks (ERR_ASYNC_CALLBACK).
"ah.createHook",
"ah.createHookParts",
// diagnostics_channel: the subscribe/unsubscribe forms validate the name
// and the subscriber in the runtime (Node's ERR_INVALID_ARG_TYPE), and
// the bind-store/run-stores calls run program code.
@@ -104,6 +104,13 @@ export const NEVER_THROW_LIB_FNS: ReadonlySet<IrLibFn> = new Set<IrLibFn>([
// runs no program code).
"perf.observerIs",
"perf.entryIs",
// The AsyncHook flips and the execution-id reads touch the core's own
// thread-local state; no program code runs and nothing raises.
"ah.disable",
"ah.enable",
"ah.providers",
"ah.executionId",
"ah.triggerId",
// scr_als_with_scope reads the effective store, enters the new one and
// boxes the RunScope; no program code runs and nothing raises.
"als.withScope",
@@ -7075,6 +7075,26 @@ function buildLibFnSignatures() {
/** AsyncLocalStorage.snapshot(): a dyn function (cb, ...args) that runs
* cb in the context active at the snapshot. */
"als.snapshot": { argTypes: [], result: DYN },
/** node:async_hooks (scr_async_dyn.c): createHook(callbacks) validates
* its five callbacks with Node's ERR_ASYNC_CALLBACK and answers a 1-based
* AsyncHook handle (MAY THROW); enable/disable answer the handle;
* executionId/triggerId read the execution's ids. The ids are scriptc's
* own sequence (Node's counter also numbers its module loading). */
"ah.createHook": { argTypes: [DYN], result: F64 },
/** createHook over an inline literal's five callbacks (each DYN,
* undefined for an absent member): the literal converts member by
* member, so a function member boxes as the checked-dynamic function
* the registry calls. */
"ah.createHookParts": { argTypes: [DYN, DYN, DYN, DYN, DYN], result: F64 },
"ah.enable": { argTypes: [F64], result: F64 },
"ah.disable": { argTypes: [F64], result: F64 },
/** asyncWrapProviders: Node's provider-name → id table as a
* null-prototype checked-dynamic object (scr_ah_providers builds it; no
* program code runs, and a compiled binary has no provider ids of its
* own — the value is Node's published table). */
"ah.providers": { argTypes: [], result: DYN },
"ah.executionId": { argTypes: [], result: F64 },
"ah.triggerId": { argTypes: [], result: F64 },
/** AsyncLocalStorage.withScope(store): enters the store now and answers
* the native RunScope handle whose dispose()/[Symbol.dispose] installs
* the value getStore() answered before it again. */
@@ -201,6 +201,15 @@ const DYN_ASYNC_LIB_FNS: ReadonlySet<IrLibFn> = new Set([
"als.newOptions",
"als.run",
"als.snapshot",
// The async_hooks hook registry and execution-id core (same unit: its
// callbacks cross as checked-dynamic values).
"ah.createHook",
"ah.createHookParts",
"ah.disable",
"ah.providers",
"ah.enable",
"ah.executionId",
"ah.triggerId",
// The RunScope handle withScope answers, and AsyncResource's registry
// with its bound functions.
"als.withScope",
@@ -1731,6 +1740,11 @@ const RUNTIME_FEATURE_RULES = {
* queueMicrotask scheduling goes through the runtime's *_als entry
* points, which carry the active stores into each callback. */
asyncContext: rule({ fns: [...ASYNC_CONTEXT_LIB_FNS] }),
/** node:async_hooks (scr_async_dyn.c's hook registry and scr_async.c's
* execution-id core): the program starts tracking at startup —
* scr_async_hooks_install is emitted — so timers, immediates and ticks
* carry ids and enabled hooks dispatch. */
asyncHooks: rule({ prefixes: ["ah."] }),
/** scr_wasm.c converts i64 values through BigInt, and BigIntStats reads
* produce bigint values. */
bigint: rule({
@@ -2832,6 +2846,7 @@ function noRuntimeFeatures(): RuntimeFeatures {
return {
assert: false,
asyncContext: false,
asyncHooks: false,
bigint: false,
bigstats: false,
childProcess: false,
@@ -118,6 +118,7 @@ const LIB_MODE_REFUSED_PREFIXES: readonly [string, string][] = [
["als.", "AsyncLocalStorage"],
["ar.", "AsyncResource"],
["dc.", "the diagnostics_channel surface"],
["ah.", "the node:async_hooks surface"],
["te.", "the node:trace_events surface"],
["worker.new", "native worker threads"],
["worker.channel", "native worker threads"],
+18
View File
@@ -375,6 +375,24 @@
"status": "static",
"note": "recognized module (bare and node:-prefixed specifiers)"
},
{
"id": "node-builtin.async_hooks.createHook",
"kind": "node-builtin",
"name": "async_hooks.createHook",
"status": "static"
},
{
"id": "node-builtin.async_hooks.executionAsyncId",
"kind": "node-builtin",
"name": "async_hooks.executionAsyncId",
"status": "static"
},
{
"id": "node-builtin.async_hooks.triggerAsyncId",
"kind": "node-builtin",
"name": "async_hooks.triggerAsyncId",
"status": "static"
},
{
"id": "node-builtin.buffer",
"kind": "node-builtin",
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/async-hooks-clear-reentrancy.cjs"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/async-hooks-execution-ids.cjs"
],
"diags": []
}
+373 -15
View File
@@ -441,8 +441,14 @@ static void scr_promise_trace(void *o, ScrTraceVisit visit, void *ctx) {
/* Teardown for the collector: release the payload only when the trace does
* NOT visit it (the complement — see the contract in scr_runtime.h). The
* cb destinations are always visited, so only the array frees here. */
/* node:async_hooks PROMISE resources (defined with the hook core below). */
static void scr_async_prom_init(ScrPromise *p);
static void scr_async_prom_settled(ScrPromise *p);
static void scr_async_prom_dropped(ScrPromise *p);
static void scr_promise_gcfree(void *o) {
ScrPromise *p = (ScrPromise *)o;
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) scr_async_prom_dropped(p);
if (p->payload_kind == SCR_EXC_STR) {
scr_str_release((ScrStr *)p->payload);
} else if ((p->payload_kind == SCR_EXC_REF || p->payload_kind == SCR_EXC_OBJ ||
@@ -472,6 +478,7 @@ ScrPromise *scr_promise_new(void) {
#ifdef SCR_RC_AUDIT
scr_live_promises++;
#endif
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) scr_async_prom_init(p);
return p;
}
@@ -653,6 +660,11 @@ void scr_promise_release(ScrPromise *p) {
if (!p || p->rc == SIZE_MAX) return;
if (--p->rc == 0) {
scr_cyc_dead(p);
/* node:async_hooks: the resource dies with the promise. The side table
* keys entries by address and is probed from the hash home, so an entry
* left behind here is both a leak and — once the address is handed to a
* new promise — an entry that find() answers for the wrong promise. */
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) scr_async_prom_dropped(p);
SCR_PROMISE_LAZY_DROP(p);
scr_promise_release_payload(p);
scr_promise_free_side(p);
@@ -918,6 +930,258 @@ struct ScrFiber {
#endif
};
/* ── node:async_hooks execution ids and hooks (scr_async.h) ──────────
* One execution-id pair and one NULL hook table, kept in the always-linked
* core. Nothing here allocates while the table is NULL; the gated dyn-async
* unit installs it (and the createHook callbacks) when the IR uses
* async_hooks, which is what starts id allocation too. */
SCR_TL const ScrAsyncHookOps *scr_async_hook_ops = NULL;
typedef struct {
double id;
double trigger;
} ScrAsyncExecState;
typedef struct {
double id;
double trigger;
} ScrAsyncIds;
static SCR_TL double scr_async_id_counter = 1;
static SCR_TL double scr_async_exec_id_value = 1;
static SCR_TL double scr_async_exec_trigger_value = 0;
static double scr_async_next_id(void) { return ++scr_async_id_counter; }
double scr_async_execution_id(void) { return scr_async_exec_id_value; }
double scr_async_execution_trigger(void) { return scr_async_exec_trigger_value; }
static ScrAsyncExecState scr_async_exec_enter(double id, double trigger) {
ScrAsyncExecState prev;
prev.id = scr_async_exec_id_value;
prev.trigger = scr_async_exec_trigger_value;
scr_async_exec_id_value = id;
scr_async_exec_trigger_value = trigger;
return prev;
}
static void scr_async_exec_leave(ScrAsyncExecState prev) {
scr_async_exec_id_value = prev.id;
scr_async_exec_trigger_value = prev.trigger;
}
static ScrAsyncIds *scr_async_track(const char *type, size_t type_len) {
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops == NULL) return NULL;
ScrAsyncIds *ids = malloc(sizeof *ids);
if (ids == NULL) {
fputs("scriptc: out of memory\n", stderr);
abort();
}
ids->id = scr_async_next_id();
ids->trigger = scr_async_exec_id_value;
if (ops->init != NULL) {
ScrDyn *resource = scr_dyn_new_obj(); /* the runtime's kinds carry no object */
ops->init(ids->id, type, type_len, ids->trigger, resource);
scr_dyn_release(resource);
}
return ids;
}
static ScrAsyncExecState scr_async_fire_begin(ScrAsyncIds *ids) {
ScrAsyncExecState prev = {0, 0};
if (ids == NULL) return prev;
prev = scr_async_exec_enter(ids->id, ids->trigger);
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->before != NULL) ops->before(ids->id);
return prev;
}
static void scr_async_fire_end(ScrAsyncIds *ids, ScrAsyncExecState prev, bool destroy) {
if (ids == NULL) return;
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->after != NULL) ops->after(ids->id);
scr_async_exec_leave(prev);
if (destroy && ops != NULL && ops->destroy != NULL) ops->destroy(ids->id);
free(ids);
}
/* The after hook alone: the timer loop decides destruction after it runs, so
* an after hook that refreshes the still-firing timer keeps the ids it
* re-arms with. */
static void scr_async_fire_after(ScrAsyncIds *ids, ScrAsyncExecState prev) {
if (ids == NULL) return;
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->after != NULL) ops->after(ids->id);
scr_async_exec_leave(prev);
}
static void scr_async_fire_destroy(ScrAsyncIds *ids) {
if (ids == NULL) return;
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->destroy != NULL) ops->destroy(ids->id);
free(ids);
}
static void scr_async_fire_end_keep(ScrAsyncIds *ids, ScrAsyncExecState prev) {
if (ids == NULL) return;
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->after != NULL) ops->after(ids->id);
scr_async_exec_leave(prev);
}
static void scr_async_fire_cancel(ScrAsyncIds *ids) {
if (ids == NULL) return;
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->destroy != NULL) ops->destroy(ids->id);
free(ids);
}
/* ── PROMISE resources of node:async_hooks ────────────────────────────
* Promises are the most numerous async resource, so their ids live in a
* side table keyed by the promise pointer: a program that does not use
* async_hooks pays one NULL test at creation, settlement and release, and
* allocates nothing. The table opens only when the hook table is
* installed, and ids are reported as Node's: init at creation with the
* creating execution as the trigger, promiseResolve once at settlement. */
typedef struct {
ScrPromise *key; /* NULL empty, SCR_PROM_TOMBSTONE deleted */
double id;
double trigger;
bool resolved;
} ScrAsyncPromEntry;
#define SCR_PROM_TOMBSTONE ((ScrPromise *)(uintptr_t)1)
static SCR_TL ScrAsyncPromEntry *scr_async_proms = NULL;
static SCR_TL size_t scr_async_proms_cap = 0, scr_async_proms_len = 0;
/* The slots an insert has to walk past: live entries plus tombstones. The
* resize test uses this, not the live count: dropping entries leaves
* tombstones that still occupy buckets, and a table can fill with them
* while few entries are live. */
static SCR_TL size_t scr_async_proms_used = 0;
static size_t scr_async_prom_home_cap(const ScrPromise *p, size_t cap) {
uint64_t h = (uint64_t)(uintptr_t)p * UINT64_C(0x9E3779B97F4A7C15);
return (size_t)(h >> 32) & (cap - 1);
}
static size_t scr_async_prom_home(const ScrPromise *p) {
return scr_async_prom_home_cap(p, scr_async_proms_cap);
}
static void scr_async_prom_teardown(void) {
free(scr_async_proms);
scr_async_proms = NULL;
scr_async_proms_cap = scr_async_proms_len = scr_async_proms_used = 0;
}
static ScrAsyncPromEntry *scr_async_prom_find(const ScrPromise *p) {
if (scr_async_proms_cap == 0) return NULL;
size_t at = scr_async_prom_home(p);
/* Bounded by the capacity: a table of live entries and tombstones can
* have no empty bucket left, and an absent key is ordinary (a directly
* awaited promise is not registered), so an unbounded probe would wrap
* forever on the event-loop thread. */
for (size_t probes = 0; probes < scr_async_proms_cap; probes++) {
ScrAsyncPromEntry *e = &scr_async_proms[at];
if (e->key == p) return e;
if (e->key == NULL) return NULL;
at = (at + 1) & (scr_async_proms_cap - 1);
}
return NULL;
}
static void scr_async_prom_insert(ScrPromise *p, double id, double trigger) {
if ((scr_async_proms_used + 1) * 4 >= scr_async_proms_cap * 3) {
size_t cap = scr_async_proms_cap ? scr_async_proms_cap * 2 : 64;
ScrAsyncPromEntry *grown = calloc(cap, sizeof *grown);
if (!grown) scr_oom();
for (size_t i = 0; i < scr_async_proms_cap; i++) {
ScrAsyncPromEntry *old = &scr_async_proms[i];
if (old->key == NULL || old->key == SCR_PROM_TOMBSTONE) continue;
/* The table is being rehashed INTO the new capacity: hashing with the
* old one would place entries where the new mask cannot find them. */
size_t at = scr_async_prom_home_cap(old->key, cap);
while (grown[at].key != NULL) at = (at + 1) & (cap - 1);
grown[at] = *old;
}
free(scr_async_proms);
scr_async_proms = grown;
scr_async_proms_cap = cap;
/* The rehash dropped every tombstone: only live entries were moved. */
scr_async_proms_used = scr_async_proms_len;
if (scr_async_proms_len == 0 && scr_async_proms_cap != 0) scr_atexit(scr_async_prom_teardown);
}
size_t at = scr_async_prom_home(p);
while (scr_async_proms[at].key != NULL && scr_async_proms[at].key != SCR_PROM_TOMBSTONE)
at = (at + 1) & (scr_async_proms_cap - 1);
/* A tombstone is a reusable slot; a never-used one adds to the walked
* slots. */
if (scr_async_proms[at].key == NULL) scr_async_proms_used++;
scr_async_proms[at].key = p;
scr_async_proms[at].id = id;
scr_async_proms[at].trigger = trigger;
scr_async_proms[at].resolved = false;
scr_async_proms_len++;
}
static void scr_async_prom_init(ScrPromise *p) {
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops == NULL) return;
double id = scr_async_next_id();
double trigger = scr_async_exec_id_value;
scr_async_prom_insert(p, id, trigger);
if (ops->init != NULL) {
ScrDyn *resource = scr_dyn_new_obj();
ops->init(id, "PROMISE", 7, trigger, resource);
scr_dyn_release(resource);
}
}
static void scr_async_prom_settled(ScrPromise *p) {
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops == NULL) return;
ScrAsyncPromEntry *e = scr_async_prom_find(p);
if (e == NULL || e->resolved) return;
e->resolved = true;
if (ops->promise_resolve != NULL) ops->promise_resolve(e->id);
}
/* The execution pair a promise resource's callbacks run under: entered
* around the reaction job or the fiber resume a settlement wakes, so
* executionAsyncId() inside an awaited continuation is the promise's id,
* as in Node. */
typedef struct {
ScrAsyncExecState prev;
double id;
bool tracked;
} ScrAsyncPromScope;
static ScrAsyncPromScope scr_async_prom_scope_enter(ScrPromise *p) {
ScrAsyncPromScope scope = {{0, 0}, 0, false};
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops == NULL) return scope;
ScrAsyncPromEntry *e = scr_async_prom_find(p);
if (e == NULL) return scope;
scope.prev = scr_async_exec_enter(e->id, e->trigger);
scope.id = e->id;
scope.tracked = true;
if (ops->before != NULL) ops->before(e->id);
return scope;
}
static void scr_async_prom_scope_leave(ScrAsyncPromScope scope) {
if (!scope.tracked) return;
const ScrAsyncHookOps *ops = scr_async_hook_ops;
if (ops != NULL && ops->after != NULL) ops->after(scope.id);
scr_async_exec_leave(scope.prev);
}
static void scr_async_prom_dropped(ScrPromise *p) {
if (scr_async_hook_ops == NULL) return;
ScrAsyncPromEntry *e = scr_async_prom_find(p);
if (e == NULL) return;
e->key = SCR_PROM_TOMBSTONE;
if (scr_async_proms_len > 0) scr_async_proms_len--;
}
/* ── AsyncLocalStorage (node:async_hooks) ─────────────────────────────
* Stores are process-lived ids; the CONTEXT is an immutable refcounted
* snapshot of (store id → dyn value) entries. One ACTIVE SLOT pointer
@@ -1297,6 +1561,7 @@ typedef struct {
unsigned long id;
bool reffed; /* keeps the loop alive; unref() clears it (Node semantics) */
double delay_ms; /* the original delay — refresh() re-arms to now + this */
ScrAsyncIds *async_ids; /* NULL unless async_hooks tracks; intervals keep it */
} ScrTimer;
static SCR_TL ScrTimer *scr_timers = NULL;
@@ -1576,7 +1841,8 @@ double scr_timer_user_delay(double after, double kind) {
void scr_set_timeout(ScrClosure *cb, double ms) {
ms = scr_timer_coerce_ms(ms);
ScrTimer t = {scr_now_ms() + ms, scr_timer_seq++, cb /* ownership moves in */, 0, 0, true, ms};
ScrTimer t = {scr_now_ms() + ms, scr_timer_seq++, cb /* ownership moves in */, 0, 0, true, ms,
scr_async_track("Timeout", 7)};
scr_timer_push(t);
}
@@ -1655,7 +1921,8 @@ static void scr_timer_remove_at(size_t i) {
double scr_set_interval(ScrClosure *cb, double ms) {
ms = scr_timer_coerce_ms(ms); /* Node's clamp-and-trunc, like setTimeout */
unsigned long id = scr_interval_next_id++;
ScrTimer t = {scr_now_ms() + ms, scr_timer_seq++, cb /* ownership moves in */, ms, id, true, ms};
ScrTimer t = {scr_now_ms() + ms, scr_timer_seq++, cb /* ownership moves in */, ms, id, true, ms,
scr_async_track("Timeout", 7)};
scr_timer_push(t);
return (double)id;
}
@@ -1666,7 +1933,8 @@ SCR_TL int scr_mt_wait_state = 0;
double scr_set_timeout_handle(ScrClosure *cb, double ms) {
ms = scr_timer_coerce_ms(ms);
unsigned long id = scr_interval_next_id++;
ScrTimer t = {scr_now_ms() + ms, scr_timer_seq++, cb /* ownership moves in */, 0, id, true, ms};
ScrTimer t = {scr_now_ms() + ms, scr_timer_seq++, cb /* ownership moves in */, 0, id, true, ms,
scr_async_track("Timeout", 7)};
scr_timer_push(t);
return (double)id;
}
@@ -1806,6 +2074,7 @@ typedef struct ScrNtick {
ScrClosure *cb; /* owned; NULL for a raw C-hook entry */
ScrFsRenameFn error_cb; /* process-write success adapter, or NULL */
void (*raw)(void); /* hook when cb == NULL (stream markers) */
ScrAsyncIds *async_ids; /* NULL unless async_hooks tracks */
struct ScrNtick *next;
} ScrNtick;
@@ -1828,6 +2097,7 @@ void scr_next_tick(ScrClosure *cb /*moves*/) {
ScrNtick *t = scr_mem_calloc(sizeof *t);
if (!t) scr_oom();
t->cb = scr_als_bind(cb);
t->async_ids = scr_async_track("TickObject", 10);
#ifdef SCR_NODE_ISLANDS
if (scr_loop_hosted != NULL) {
scr_hosted_tick(t);
@@ -1901,6 +2171,7 @@ void scr_nticks_teardown(void) {
while (scr_nt_head != NULL) {
ScrNtick *t = scr_nt_head;
scr_nt_head = t->next;
scr_async_fire_cancel(t->async_ids);
if (t->cb) scr_closure_release(t->cb);
scr_mem_free(t);
}
@@ -1937,8 +2208,15 @@ void scr_clear_interval(double handle) {
#endif
ScrTimer *found = scr_timer_find(id);
if (found) {
scr_closure_release(found->cb);
/* Take the entry out of the heap BEFORE the destroy hook runs. The hook
* is program code: queueing timers or immediates here reallocates or
* reorders this storage, so neither the entry pointer nor its heap index
* survives the call. Its owned fields move to locals first. */
ScrClosure *cb = found->cb;
ScrAsyncIds *async_ids = found->async_ids;
scr_timer_remove_at((size_t)(found - scr_timers));
scr_async_fire_cancel(async_ids);
scr_closure_release(cb);
}
}
@@ -1956,6 +2234,7 @@ typedef struct {
unsigned long id;
ScrClosure *cb; /* owned; NULL once fired or cleared */
bool reffed; /* keeps the loop alive; unref() clears it (Node semantics) */
ScrAsyncIds *async_ids; /* NULL unless async_hooks tracks */
} ScrImmediate;
static SCR_TL ScrImmediate *scr_immediates = NULL;
@@ -1969,16 +2248,23 @@ double scr_set_immediate(ScrClosure *cb) {
#ifdef SCR_NODE_ISLANDS
if (scr_loop_hosted != NULL) return scr_hosted_set_immediate(cb);
#endif
/* The init hook runs program code and may queue immediates of its own:
* track FIRST, then commit this entry, so the hook's entries land in
* slots of their own (Node queues them before this one, and they run
* first). Tracking also may grow the queue, so the capacity check must
* follow it, not precede it. */
ScrAsyncIds *async_ids = scr_async_track("Immediate", 9);
if (scr_nimmediates == scr_immediates_cap) {
scr_immediates_cap = scr_immediates_cap ? scr_immediates_cap * 2 : 16;
scr_immediates = realloc(scr_immediates, scr_immediates_cap * sizeof *scr_immediates);
if (!scr_immediates) scr_oom();
}
unsigned long id = scr_interval_next_id++;
scr_immediates[scr_nimmediates].id = id;
scr_immediates[scr_nimmediates].cb = cb; /* ownership moves in */
scr_immediates[scr_nimmediates].reffed = true;
scr_nimmediates++;
ScrImmediate *im = &scr_immediates[scr_nimmediates++];
im->id = id;
im->cb = cb; /* ownership moves in */
im->reffed = true;
im->async_ids = async_ids;
scr_pending_immediates++;
scr_reffed_immediates++;
return (double)id;
@@ -2006,13 +2292,20 @@ void scr_clear_immediate(double handle) {
#endif
ScrImmediate *im = scr_immediate_find((unsigned long)handle);
if (im == NULL) return; /* already fired/cleared: no-op, like Node */
scr_closure_release(im->cb);
/* The slot is cleared before the destroy hook runs: the hook is program
* code, and queueing an immediate from it reallocates this array, so the
* entry pointer cannot survive the call. */
ScrClosure *cb = im->cb;
ScrAsyncIds *async_ids = im->async_ids;
im->cb = NULL;
im->async_ids = NULL;
if (scr_pending_immediates > 0) scr_pending_immediates--;
if (im->reffed) {
im->reffed = false;
if (scr_reffed_immediates > 0) scr_reffed_immediates--;
}
scr_async_fire_cancel(async_ids);
scr_closure_release(cb);
}
/* Immediate.unref()/ref()/hasRef(): the Timeout trio's exact story over
@@ -2334,6 +2627,9 @@ static inline void scr_promise_wake_one(ScrFiber *f) {
/* Runs one callback waiter against its settled source and drops the
* waiter's references (its destination and countdown state). */
static void scr_promise_cb_run(struct ScrPromiseCbWaiter *cb, ScrPromise *src) {
bool async_tracked = __builtin_expect(scr_async_hook_ops != NULL, 0);
ScrAsyncPromScope async_scope;
if (async_tracked) async_scope = scr_async_prom_scope_enter(src);
if (SCR_PROMISE_IS_REACTION(cb)) {
scr_promise_reaction_run(cb, src);
return;
@@ -2351,6 +2647,7 @@ static void scr_promise_cb_run(struct ScrPromiseCbWaiter *cb, ScrPromise *src) {
scr_promise_settle_from(cb->dst, src);
}
scr_promise_release(cb->dst);
if (async_tracked) scr_async_prom_scope_leave(async_scope);
}
/* Queues a combinator's reaction job for a settled entry. The waiter's
@@ -2452,10 +2749,26 @@ static void scr_promise_settle_wake_cbs(ScrPromise *p) {
for (size_t i = 0; i < ncbs; i++) {
const struct ScrPromiseCbWaiter *cb = &cbs[i];
if (cb->job_at == SCR_CB_SYNC) continue;
for (; w < cb->job_at && w < p->nwaiters; w++) scr_promise_wake_one(p->waiters[w]);
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) {
for (; w < cb->job_at && w < p->nwaiters; w++) {
ScrAsyncPromScope async_scope = scr_async_prom_scope_enter(p);
scr_promise_wake_one(p->waiters[w]);
scr_async_prom_scope_leave(async_scope);
}
} else {
for (; w < cb->job_at && w < p->nwaiters; w++) scr_promise_wake_one(p->waiters[w]);
}
scr_promise_cb_queue(cb, p);
}
for (; w < p->nwaiters; w++) scr_promise_wake_one(p->waiters[w]);
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) {
for (; w < p->nwaiters; w++) {
ScrAsyncPromScope async_scope = scr_async_prom_scope_enter(p);
scr_promise_wake_one(p->waiters[w]);
scr_async_prom_scope_leave(async_scope);
}
} else {
for (; w < p->nwaiters; w++) scr_promise_wake_one(p->waiters[w]);
}
p->nwaiters = 0;
for (size_t i = 0; i < ncbs; i++) {
if (cbs[i].job_at == SCR_CB_SYNC) scr_promise_cb_run(&cbs[i], p);
@@ -2466,13 +2779,28 @@ static void scr_promise_settle_wake_cbs(ScrPromise *p) {
/* Settle helpers wake waiters into the microtask queue and dispatch the
* callback waiters. */
static void scr_promise_settle_wake(ScrPromise *p) {
/* A promiseResolve hook runs inside the settlement and can drop the last
* reference the program held to this promise (a reader's closed promise,
* for one); hold it for the whole wake so the settlement below never runs
* on a freed promise. */
scr_promise_retain(p);
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) scr_async_prom_settled(p);
if (p->ncbs != 0) {
scr_promise_settle_wake_cbs(p);
} else {
for (size_t i = 0; i < p->nwaiters; i++) scr_promise_wake_one(p->waiters[i]);
if (__builtin_expect(scr_async_hook_ops != NULL, 0)) {
for (size_t i = 0; i < p->nwaiters; i++) {
ScrAsyncPromScope async_scope = scr_async_prom_scope_enter(p);
scr_promise_wake_one(p->waiters[i]);
scr_async_prom_scope_leave(async_scope);
}
} else {
for (size_t i = 0; i < p->nwaiters; i++) scr_promise_wake_one(p->waiters[i]);
}
p->nwaiters = 0;
}
if (p->state == SCR_PROM_REJECTED) scr_track_rejection(p);
scr_promise_release(p);
}
/* ── Promise.race ─────────────────────────────────────────────────────
@@ -3428,7 +3756,14 @@ static void scr_direct_finish(ScrFiber *self) {
if (p->state == SCR_PROM_PENDING)
scr_trap("scriptc: internal error: directly awaited body finished unsettled\n");
self->done = true;
if (self->direct_awaiter != NULL) scr_promise_wake_one(self->direct_awaiter);
if (self->direct_awaiter != NULL) {
ScrAsyncPromScope async_scope;
bool async_tracked =
__builtin_expect(scr_async_hook_ops != NULL, 0) && self->promise != NULL;
if (async_tracked) async_scope = scr_async_prom_scope_enter(self->promise);
scr_promise_wake_one(self->direct_awaiter);
if (async_tracked) scr_async_prom_scope_leave(async_scope);
}
}
void scr_coro_async_finish(ScrFiber *self) {
@@ -6602,10 +6937,13 @@ static bool scr_loop_run_ticks(void) {
ScrClosure *cb = t->cb;
ScrFsRenameFn error_cb = t->error_cb;
void (*raw)(void) = t->raw;
ScrAsyncIds *async_ids = t->async_ids;
scr_mem_free(t);
if (cb) {
ScrAsyncExecState async_prev = scr_async_fire_begin(async_ids);
if (error_cb) error_cb(cb, NULL);
else ((void (*)(ScrClosure *))cb->fn)(cb);
scr_async_fire_end(async_ids, async_prev, true);
scr_closure_release(cb);
} else {
raw(); /* one stream tick, FIFO with the user ticks around it */
@@ -7164,7 +7502,14 @@ static bool scr_loop_run_pass(ScrPromise *top_level, bool first_checkpoint) {
scr_firing_refresh = false;
}
double started = t.id != 0 && t.repeat_ms > 0 ? scr_now_ms() : 0;
ScrAsyncExecState async_prev = scr_async_fire_begin(t.async_ids);
((void (*)(ScrClosure *))t.cb->fn)(t.cb);
/* The after hook runs before the destruction decision: it can refresh
* the still-firing timer, and the entry then keeps the ids it re-arms
* with instead of having them freed underneath it. */
scr_async_fire_after(t.async_ids, async_prev);
bool keep_ids =
t.id != 0 && !scr_firing_cleared && (t.repeat_ms > 0 || scr_firing_refresh);
if (t.id != 0 && t.repeat_ms > 0 && !scr_firing_cleared) {
/* Re-arm relative to the time the callback started, as Node's
* listOnTimeout does (getLibuvNow() before _onTimeout): a slow
@@ -7172,17 +7517,26 @@ static bool scr_loop_run_pass(ScrPromise *top_level, bool first_checkpoint) {
* One slower than the interval makes the next tick due on the next
* turn, without catch-up bursts. The ref state carries across
* ticks (a self-unref'd interval stays unref'd). */
ScrTimer again = {started + t.repeat_ms, scr_timer_seq++, t.cb, t.repeat_ms, t.id, scr_firing_reffed, t.delay_ms};
ScrTimer again = {started + t.repeat_ms, scr_timer_seq++, t.cb, t.repeat_ms, t.id,
scr_firing_reffed, t.delay_ms, t.async_ids};
scr_timer_push(again);
} else if (t.id != 0 && scr_firing_refresh && !scr_firing_cleared) {
/* refresh() from inside the one-shot's own callback: re-arm to
* now + the original delay, ref state carried (Node's
* Timeout.refresh — the timer fires again). */
ScrTimer again = {scr_now_ms() + t.delay_ms, scr_timer_seq++, t.cb, 0, t.id, scr_firing_reffed, t.delay_ms};
ScrTimer again = {scr_now_ms() + t.delay_ms, scr_timer_seq++, t.cb, 0, t.id,
scr_firing_reffed, t.delay_ms, t.async_ids};
scr_timer_push(again);
} else {
scr_closure_release(t.cb);
}
if (!keep_ids) {
/* Nothing re-armed: the resource is done. Clear the firing id before
* the destroy hook so a refresh there cannot target a timer that no
* longer exists (its ids are freed next). */
scr_firing_id = 0;
scr_async_fire_destroy(t.async_ids);
}
scr_firing_id = 0;
if (scr_exc_pending()) return false; /* uncaught throw in a callback: main handles it */
if (SCR_PASS_HANDED_OVER()) return rejection_failed;
@@ -7231,7 +7585,11 @@ static bool scr_loop_run_pass(ScrPromise *top_level, bool first_checkpoint) {
if (scr_reffed_immediates > 0) scr_reffed_immediates--;
}
scr_immediate_firing = scr_immediates[i].id;
ScrAsyncIds *async_ids = scr_immediates[i].async_ids; /* one-shot */
scr_immediates[i].async_ids = NULL;
ScrAsyncExecState async_prev = scr_async_fire_begin(async_ids);
((void (*)(ScrClosure *))cb->fn)(cb);
scr_async_fire_end(async_ids, async_prev, true);
scr_immediate_firing = 0;
scr_closure_release(cb);
if (scr_exc_pending()) return false; /* uncaught throw: main handles it */
+48
View File
@@ -364,6 +364,54 @@ double scr_ar_trigger_id(ScrDyn *handle);
double scr_ar_execution_id(void);
double scr_ar_execution_trigger(void);
/* ── node:async_hooks execution ids and hooks ─────────────────────────
* The always-linked core keeps one execution-id pair and ONE NULL hook
* table; nothing allocates or counts ids while the table is NULL, so a
* program that never uses async_hooks pays a single predictable test at
* each instrumented site (the timer, immediate, tick and promise paths).
* The gated dyn-async unit installs the table at startup when the IR uses
* async_hooks' libCalls, which is also what turns id allocation on. The
* rest of the bookkeeping (the id counter, the execution pair's enter and
* leave, the per-resource capture) is private to scr_async.c.
*
* Ids start at 1 for the program's top-level execution (trigger id 0);
* each tracked resource takes the next id and remembers the execution it
* was created in as its trigger. Types are the Node resource names the
* runtime models ("Timeout", "Immediate", "TickObject", "PROMISE"). The
* ids are scriptc's own sequence: Node's counter also numbers its module
* loading internals, so only a resource's relations (equality with the id
* seen inside its own callback, ids greater than the root) are observable
* across implementations. */
typedef struct ScrAsyncHookOps {
/* A tracked resource was created: `id`, its type, the execution id that
* created it, and the resource object the hooks receive (a fresh dyn
* object for the runtime's own kinds). */
void (*init)(double id, const char *type, size_t type_len, double trigger, ScrDyn *resource);
void (*before)(double id); /* about to run this resource's callback */
void (*after)(double id); /* the callback returned or threw */
void (*destroy)(double id);
void (*promise_resolve)(double id); /* a tracked promise settled */
} ScrAsyncHookOps;
extern SCR_TL const ScrAsyncHookOps *scr_async_hook_ops; /* NULL: not tracking */
double scr_async_execution_id(void);
double scr_async_execution_trigger(void);
/* createHook and the table's installation (scr_async_dyn.c). createHook
* validates its five callbacks with Node's ERR_ASYNC_CALLBACK and answers a
* 1-based f64 handle (NaN with the exception pending); enable/disable flip
* the hook and answer the handle, as Node's methods answer `this`; the
* install entry is emitted before the entry of a program whose IR uses
* async_hooks. */
void scr_async_hooks_install(void);
double scr_ah_create(ScrDyn *options);
double scr_ah_parts(ScrDyn *init, ScrDyn *before, ScrDyn *after, ScrDyn *destroy,
ScrDyn *promise_resolve);
double scr_ah_enable(double handle);
double scr_ah_disable(double handle);
/* asyncWrapProviders: Node 24's published provider-name → id table as a
* null-prototype checked-dynamic object (+1). */
ScrDyn *scr_ah_providers(void);
/* process.on/once('unhandledRejection', fn): dyn listeners dispatched
* per never-observed rejection at the end of its nextTick/microtask
* checkpoint — (reason, promise), suppressing the default report and the
+59
View File
@@ -243,6 +243,27 @@ static void clearing_the_newest_immediate_does_not_walk_the_cleared_ones(void) {
puts("clearing the newest immediate does not walk the cleared ones");
}
/* Dropping entries leaves tombstones that keep occupying buckets while the
* live count stays low, and ordinary churn can reach a table with every
* bucket taken (a direct-awaited promise is not registered, so an absent key
* is ordinary). An absent key must answer, and an insert must still land,
* instead of a probe wrapping forever on the event-loop thread. */
static void promise_table_survives_tombstone_churn(void) {
scr_async_proms_cap = 64;
scr_async_proms = calloc(scr_async_proms_cap, sizeof *scr_async_proms);
assert(scr_async_proms != NULL);
for (size_t i = 0; i < scr_async_proms_cap; i++) scr_async_proms[i].key = SCR_PROM_TOMBSTONE;
scr_async_proms_len = 0;
scr_async_proms_used = scr_async_proms_cap;
ScrPromise missing;
assert(scr_async_prom_find(&missing) == NULL);
ScrPromise fresh;
scr_async_prom_insert(&fresh, 7, 0);
assert(scr_async_prom_find(&fresh) != NULL);
scr_async_prom_teardown();
printf("promise table survives tombstone churn\n");
}
/* A handle the program drops frees the resource it named: the live count
* returns to what it was, and (under the sanitized build's leak check) the
* type string and captured context are released too. */
@@ -419,8 +440,42 @@ static void async_resource_teardown_releases_cyclic_stores(void) {
printf("teardown releases cyclic stores without walking a disposed snapshot\n");
}
/* A promiseResolve hook runs inside the settlement and may drop the last
* reference the program held to the settling promise; the settlement must
* finish on a promise it still holds. */
static ScrPromise *settle_hook_promise;
static ScrDyn *settle_hook_release(ScrClosure *self, ScrDyn *const *args, size_t argc) {
(void)self;
(void)args;
(void)argc;
if (settle_hook_promise != NULL) {
scr_promise_release(settle_hook_promise); /* the program's only reference */
settle_hook_promise = NULL;
}
return scr_dyn_undefined();
}
static void promise_resolve_hook_can_drop_the_settling_promise(void) {
scr_async_hooks_install();
ScrClosure *closure = scr_closure_new(NULL, 0);
ScrDyn *release = scr_dyn_new_func(closure, settle_hook_release, 1, "(id)", "release");
double handle = scr_ah_parts(NULL, NULL, NULL, NULL, release); /* promiseResolve slot */
assert(handle >= 1);
scr_ah_enable(handle);
scr_dyn_release(release);
ScrPromise *p = scr_promise_new();
settle_hook_promise = p; /* the program keeps exactly this one reference */
scr_promise_fulfill_void(p); /* the hook releases it mid-settlement */
assert(settle_hook_promise == NULL);
printf("a promiseResolve hook may drop the settling promise's owner\n");
}
int main(int argc, char **argv) {
scr_init();
if (argc > 1 && strcmp(argv[1], "promises") == 0) {
promise_table_survives_tombstone_churn();
return 0;
}
if (argc > 1 && strcmp(argv[1], "timers") == 0) {
due_timers_run_by_deadline_before_immediates();
return 0;
@@ -437,6 +492,10 @@ int main(int argc, char **argv) {
async_resource_teardown_releases_cyclic_stores();
return 0;
}
if (argc > 1 && strcmp(argv[1], "settlehook") == 0) {
promise_resolve_hook_can_drop_the_settling_promise();
return 0;
}
if (argc > 1 && strcmp(argv[1], "bindings") == 0) {
async_resource_bindings_own_and_release_their_payload();
return 0;
+12
View File
@@ -56,6 +56,12 @@ test("fiber stacks commit on demand and preserve large frames across suspension"
// With every deadline already passed, the order is the timer heap's and the
// loop's, not the clock's: tests/corpus/timers-cross-kind-clears.ts once
// showed the first of these only when its own script ran fast enough.
test("the promise resource table survives tombstone churn", async () => {
const result = await execFileAsync(bin, ["promises"]);
expect(result.stdout).toBe("promise table survives tombstone churn\n");
expect(withoutContextWarning(result.stderr)).toBe("");
});
test("a destroyed AsyncResource keeps its context until the resource is freed", async () => {
const result = await execFileAsync(bin, ["destroy"]);
expect(result.stdout).toBe(
@@ -70,6 +76,12 @@ test("AsyncResource bindings own their payload and release it", async () => {
expect(withoutContextWarning(result.stderr)).toBe("");
});
test("a promiseResolve hook may drop the settling promise's owner", async () => {
const result = await execFileAsync(bin, ["settlehook"]);
expect(result.stdout).toBe("a promiseResolve hook may drop the settling promise's owner\n");
expect(withoutContextWarning(result.stderr)).toBe("");
});
test("a store and a resource that hold each other are collected", async () => {
const result = await execFileAsync(bin, ["cycle"]);
expect(result.stdout).toBe("a store and a resource that hold each other are collected\n");
+283
View File
@@ -3404,6 +3404,289 @@ ScrDyn *scr_crypto_native(void) {
ScrDyn *result = scr_dyn_new_obj(); scr_dyn_obj_set(result, "subtle", 6, subtle); return result;
}
/* ── node:async_hooks createHook (AsyncHook) ──────────────────────────
* The hook registry the always-linked core dispatches through once this
* unit installs its ops table (at startup, when the IR uses async_hooks).
* A hook object is a 1-based f64 handle; its five callbacks are dyn
* functions, validated with Node's ERR_ASYNC_CALLBACK. Enabled hooks run
* in registration order, each call's ids crossing as numbers and a
* resource as the dyn object the core allocated for it. */
typedef struct {
ScrDyn *init, *before, *after, *destroy, *promise_resolve; /* owned or NULL */
bool enabled;
} ScrAhHook;
typedef struct {
const char *key;
size_t len;
const char *label;
size_t label_len;
} ScrAhCallbackSlot;
static const ScrAhCallbackSlot scr_ah_slots[5] = {
{"init", 4, "init", 4},
{"before", 6, "before", 6},
{"after", 5, "after", 5},
{"destroy", 7, "destroy", 7},
{"promiseResolve", 14, "promiseResolve", 14},
};
static SCR_TL ScrAhHook *scr_ah_hooks = NULL;
static SCR_TL size_t scr_ah_count = 0, scr_ah_cap = 0;
static void scr_ah_release_hook(ScrAhHook *h) {
scr_dyn_release(h->init);
scr_dyn_release(h->before);
scr_dyn_release(h->after);
scr_dyn_release(h->destroy);
scr_dyn_release(h->promise_resolve);
}
static void scr_ah_teardown(void) {
for (size_t i = 0; i < scr_ah_count; i++) scr_ah_release_hook(&scr_ah_hooks[i]);
free(scr_ah_hooks);
scr_ah_hooks = NULL;
scr_ah_count = scr_ah_cap = 0;
}
static ScrAhHook *scr_ah_of(double handle) {
size_t i = (size_t)handle;
return handle >= 1 && i <= scr_ah_count ? &scr_ah_hooks[i - 1] : NULL;
}
static void scr_ah_call(ScrDyn *fn, ScrDyn *const *args, size_t argc) {
if (fn == NULL) return;
ScrDyn *r = scr_dyn_call(fn, args, argc, "async hook callback");
if (r != NULL) scr_dyn_release(r);
}
static ScrDyn *scr_ah_num(double v) { return scr_dyn_new_num(v); }
static void scr_ah_dispatch_init(double id, const char *type, size_t type_len, double trigger,
ScrDyn *resource) {
for (size_t i = 0; i < scr_ah_count; i++) {
ScrAhHook *h = &scr_ah_hooks[i];
if (!h->enabled || h->init == NULL) continue;
ScrStr *name = scr_str_new(type, type_len);
ScrDyn *args[4] = {scr_ah_num(id), scr_dyn_new_str(name), scr_ah_num(trigger),
scr_dyn_retain(resource)};
scr_str_release(name); /* scr_dyn_new_str retains its own reference */
scr_ah_call(h->init, args, 4);
for (size_t a = 0; a < 4; a++) scr_dyn_release(args[a]);
}
}
static void scr_ah_dispatch_id(double id, int which) {
for (size_t i = 0; i < scr_ah_count; i++) {
ScrAhHook *h = &scr_ah_hooks[i];
if (!h->enabled) continue;
ScrDyn *fn = which == 0 ? h->before
: which == 1 ? h->after
: which == 2 ? h->destroy
: h->promise_resolve;
if (fn == NULL) continue;
ScrDyn *args[1] = {scr_ah_num(id)};
scr_ah_call(fn, args, 1);
scr_dyn_release(args[0]);
}
}
static void scr_ah_hook_before(double id) { scr_ah_dispatch_id(id, 0); }
static void scr_ah_hook_after(double id) { scr_ah_dispatch_id(id, 1); }
static void scr_ah_hook_destroy(double id) { scr_ah_dispatch_id(id, 2); }
static void scr_ah_hook_promise_resolve(double id) { scr_ah_dispatch_id(id, 3); }
static const ScrAsyncHookOps scr_ah_ops = {
.init = scr_ah_dispatch_init,
.before = scr_ah_hook_before,
.after = scr_ah_hook_after,
.destroy = scr_ah_hook_destroy,
.promise_resolve = scr_ah_hook_promise_resolve,
};
/* Emitted before the entry of a program whose IR uses async_hooks: from
* here on the core allocates ids and dispatches hook callbacks. */
void scr_async_hooks_install(void) {
if (scr_async_hook_ops == NULL) scr_async_hook_ops = &scr_ah_ops;
}
/* createHook(callbacks): the five members are read the way Node's
* destructuring reads them — undefined and null raise its property-read
* TypeError, any other value reads whatever it has and a missing member is
* no callback — and a present member that is not a function raises
* ERR_ASYNC_CALLBACK. callbacks borrowed; the handle is 1-based. */
double scr_ah_create(ScrDyn *options) {
if (options == NULL || options->kind == SCR_DYN_UNDEF || options->kind == SCR_DYN_NULL) {
static const char undef_message[] =
"Cannot destructure property 'init' of 'undefined' as it is undefined.";
static const char null_message[] =
"Cannot destructure property 'init' of 'null' as it is null.";
if (options != NULL && options->kind == SCR_DYN_NULL)
scr_throw_error_msg(SCR_ERR_TYPE, null_message, sizeof null_message - 1);
else
scr_throw_error_msg(SCR_ERR_TYPE, undef_message, sizeof undef_message - 1);
return NAN;
}
/* scr_dyn_obj_get borrows its answers; scr_ah_parts retains the ones it
* keeps. */
ScrDyn *values[5] = {NULL, NULL, NULL, NULL, NULL};
for (size_t i = 0; i < 5; i++) {
ScrDyn *value = scr_dyn_obj_get(options, scr_ah_slots[i].key, scr_ah_slots[i].len);
if (value == NULL && scr_exc_pending()) return NAN; /* a getter threw */
values[i] = value; /* absent member reads as no callback */
}
return scr_ah_parts(values[0], values[1], values[2], values[3], values[4]);
}
/* The five callbacks as Node's createHook takes them: bounded (borrowed)
* values, each either absent (undefined) or a function; an explicit null or
* any other non-function raises Node's ERR_ASYNC_CALLBACK in slot order.
* Answers the 1-based handle. */
double scr_ah_parts(ScrDyn *init, ScrDyn *before, ScrDyn *after, ScrDyn *destroy,
ScrDyn *promise_resolve) {
ScrDyn **given[5] = {&init, &before, &after, &destroy, &promise_resolve};
ScrAhHook hook = {NULL, NULL, NULL, NULL, NULL, false};
ScrDyn **dest[5] = {&hook.init, &hook.before, &hook.after, &hook.destroy, &hook.promise_resolve};
for (size_t i = 0; i < 5; i++) {
ScrDyn *value = *given[i];
if (value == NULL || value->kind == SCR_DYN_UNDEF) continue;
if (value->kind != SCR_DYN_FUNC) {
static const char prefix[] = "hook.";
static const char suffix[] = " must be a function";
ScrJsonBuf b;
scr_jb_init(&b);
scr_jb_puts(&b, prefix);
scr_jb_puts(&b, scr_ah_slots[i].label);
scr_jb_puts(&b, suffix);
ScrStr *message = scr_jb_finish(&b);
scr_throw_error_msg_code(SCR_ERR_TYPE, message->data, message->len, "ERR_ASYNC_CALLBACK");
scr_str_release(message);
scr_ah_release_hook(&hook);
return NAN;
}
*dest[i] = scr_dyn_retain(value);
}
if (scr_ah_count == scr_ah_cap) {
size_t cap = scr_ah_cap ? scr_ah_cap * 2 : 4;
ScrAhHook *grown = realloc(scr_ah_hooks, cap * sizeof *grown);
if (!grown) scr_ad_oom();
scr_ah_hooks = grown;
scr_ah_cap = cap;
if (scr_ah_count == 0) scr_atexit(scr_ah_teardown);
}
scr_ah_hooks[scr_ah_count++] = hook;
return (double)scr_ah_count;
}
double scr_ah_enable(double handle) {
ScrAhHook *hook = scr_ah_of(handle);
if (hook != NULL) hook->enabled = true;
return handle;
}
double scr_ah_disable(double handle) {
ScrAhHook *hook = scr_ah_of(handle);
if (hook != NULL) hook->enabled = false;
return handle;
}
/* ── node:async_hooks asyncWrapProviders ──────────────────────────────
* The provider-name → id table Node 24 ships (async_wrap's constants): a
* null-prototype object whose own enumerable properties are the names, so
* a read answers the same table Node's does. A compiled binary has no
* provider ids of its own; the value is Node's published table, not a
* report of this runtime's internals. */
typedef struct {
const char *name;
double id;
} ScrAhProvider;
static const ScrAhProvider scr_ah_provider_table[] = {
{"NONE", 0},
{"DIRHANDLE", 1},
{"DNSCHANNEL", 2},
{"ELDHISTOGRAM", 3},
{"FILEHANDLE", 4},
{"FILEHANDLECLOSEREQ", 5},
{"BLOBREADER", 6},
{"FSEVENTWRAP", 7},
{"FSREQCALLBACK", 8},
{"FSREQPROMISE", 9},
{"GETADDRINFOREQWRAP", 10},
{"GETNAMEINFOREQWRAP", 11},
{"HEAPSNAPSHOT", 12},
{"HTTP2SESSION", 13},
{"HTTP2STREAM", 14},
{"HTTP2PING", 15},
{"HTTP2SETTINGS", 16},
{"HTTPINCOMINGMESSAGE", 17},
{"HTTPCLIENTREQUEST", 18},
{"LOCKS", 19},
{"JSSTREAM", 20},
{"JSUDPWRAP", 21},
{"MESSAGEPORT", 22},
{"PIPECONNECTWRAP", 23},
{"PIPESERVERWRAP", 24},
{"PIPEWRAP", 25},
{"PROCESSWRAP", 26},
{"PROMISE", 27},
{"QUERYWRAP", 28},
{"QUIC_ENDPOINT", 29},
{"QUIC_LOGSTREAM", 30},
{"QUIC_SESSION", 31},
{"QUIC_STREAM", 32},
{"QUIC_UDP", 33},
{"SHUTDOWNWRAP", 34},
{"SIGNALWRAP", 35},
{"STATWATCHER", 36},
{"STREAMPIPE", 37},
{"TCPCONNECTWRAP", 38},
{"TCPSERVERWRAP", 39},
{"TCPWRAP", 40},
{"TTYWRAP", 41},
{"UDPSENDWRAP", 42},
{"UDPWRAP", 43},
{"SIGINTWATCHDOG", 44},
{"WORKER", 45},
{"WORKERCPUPROFILE", 46},
{"WORKERCPUUSAGE", 47},
{"WORKERHEAPPROFILE", 48},
{"WORKERHEAPSNAPSHOT", 49},
{"WORKERHEAPSTATISTICS", 50},
{"WRITEWRAP", 51},
{"ZLIB", 52},
{"CHECKPRIMEREQUEST", 53},
{"PBKDF2REQUEST", 54},
{"KEYPAIRGENREQUEST", 55},
{"KEYGENREQUEST", 56},
{"KEYEXPORTREQUEST", 57},
{"ARGON2REQUEST", 58},
{"CIPHERREQUEST", 59},
{"DERIVEBITSREQUEST", 60},
{"HASHREQUEST", 61},
{"RANDOMBYTESREQUEST", 62},
{"RANDOMPRIMEREQUEST", 63},
{"SCRYPTREQUEST", 64},
{"SIGNREQUEST", 65},
{"TLSWRAP", 66},
{"VERIFYREQUEST", 67},
};
ScrDyn *scr_ah_providers(void) {
ScrDyn *obj = scr_dyn_new_obj();
for (size_t i = 0; i < sizeof scr_ah_provider_table / sizeof scr_ah_provider_table[0]; i++) {
scr_dyn_obj_set(obj, scr_ah_provider_table[i].name, strlen(scr_ah_provider_table[i].name),
scr_dyn_new_num(scr_ah_provider_table[i].id));
}
/* A null prototype, as Node's table has: the setter borrows the
* prototype and answers the object (+1), both of which the caller owns. */
ScrDyn *null_proto = scr_dyn_new_null();
ScrDyn *set = scr_dyn_set_prototype(obj, null_proto);
scr_dyn_release(null_proto);
scr_dyn_release(set);
return obj;
}
/* ── node:trace_events (trace_events.Tracing) ─────────────────────────
* A compiled binary carries no trace-event agent, which is what Node's
* tracing objects drive. Without the agent — Node run without the
+24
View File
@@ -1545,6 +1545,16 @@ static ScrDyn *ws_bytes_read(WsReader *r) {
ScrBytes *view = scr_bytes_new(SCR_BYTES_U8, c->auto_allocate);
if (!view) return NULL;
ScrPromise *p = scr_promise_new();
if (r->stream == NULL) {
/* The init hook released the lock while the promise was built. The
* auto-allocated destination is no longer handed to a request, so its
* reference is released here. */
ws_reject(p, ws_reader_releasing_error());
ScrPromise *result = scr_promise_retain(p);
scr_promise_release(p);
scr_bytes_release(view);
return ws_promise_box(result);
}
WsPullInto *d = ws_pull_into_new(view, 1, false, p);
scr_bytes_release(view);
ws_pull_into_enqueue(c, d);
@@ -1614,6 +1624,13 @@ static ScrDyn *ws_byob_read(WsReader *r, ScrDyn *view_arg, ScrDyn *options) {
return ws_promise_box(rejected);
}
ScrPromise *p = scr_promise_new();
if (r->stream == NULL) {
/* The init hook released the lock while the promise was built. */
ws_reject(p, ws_reader_releasing_error());
ScrPromise *result = scr_promise_retain(p);
scr_promise_release(p);
return ws_promise_box(result);
}
/* `min` counts elements of the destination's type (bytes for a DataView),
* as Node's read does: minimumFill = min * elementSize. */
size_t min_elements = min > 0 ? (size_t)min : 1;
@@ -1640,6 +1657,13 @@ static ScrDyn *ws_byob_read(WsReader *r, ScrDyn *view_arg, ScrDyn *options) {
/* readableStreamDefaultReaderRead. */
static void ws_reader_read_request(WsReader *r, WsReadRequest *q) {
WsReadable *s = r->stream;
if (!s) {
/* The PROMISE init hook runs inside the promise a read just built and can
* release the reader's lock; the request answers the releasing error
* instead of following the cleared stream. */
q->ops->error(q, ws_reader_releasing_error());
return;
}
s->disturbed = true;
switch (s->state) {
case WS_STATE_CLOSED: q->ops->close(q); break;
+6
View File
@@ -0,0 +1,6 @@
import { analyze } from "./packages/compiler/dist/index.js";
const { coverage } = analyze("tests/corpus/async-hooks-execution-ids.cjs", {});
console.log("keys:", Object.keys(coverage));
console.log("stats:", JSON.stringify(coverage.stats));
const extra = coverage.deferred ?? coverage.failures ?? coverage.fences;
console.log("extra:", JSON.stringify(extra)?.slice(0, 1500));
+3
View File
@@ -0,0 +1,3 @@
import { analyze } from "./packages/compiler/dist/index.js";
const { coverage } = analyze("tests/corpus/async-hooks-execution-ids.cjs", {});
console.log(JSON.stringify(coverage.runtimeFences, null, 1).slice(0, 3000));
@@ -0,0 +1,38 @@
// A destroy hook that queues and clears timers and immediates while a
// timeout, an interval or an immediate is being cleared must not corrupt
// the timer heap or the immediate queue: the entry is taken out before the
// hook runs, and nothing the hook does can invalidate it afterwards.
'use strict';
const ah = require('async_hooks');
const scheduled = [];
let budget = 3;
let spareCleared = false;
const spare = setTimeout(() => scheduled.push('spare-ran'), 1000);
const hook = ah.createHook({
destroy() {
if (!spareCleared) {
/* Clearing a different entry reorders the heap during the clear. */
spareCleared = true;
clearTimeout(spare);
}
if (budget === 0) return;
budget--;
/* Growing the timer heap from inside the hook is the other hazard; the
* callback has nothing to report (its firing is host-timing dependent). */
setTimeout(() => {}, 1);
setImmediate(() => scheduled.push('immediate'));
},
});
hook.enable();
const timeout = setTimeout(() => scheduled.push('timeout-ran'), 1000);
clearTimeout(timeout);
const interval = setInterval(() => scheduled.push('interval-ran'), 1000);
clearInterval(interval);
const immediate = setImmediate(() => scheduled.push('immediate-ran'));
clearImmediate(immediate);
setTimeout(() => {
hook.disable();
scheduled.sort();
console.log('scheduled:', scheduled.join(','), '| budget:', budget, '| spare cleared:', spareCleared);
}, 10);
+188
View File
@@ -0,0 +1,188 @@
// node:async_hooks — the execution ids and the hook callbacks, pinned by
// their relations rather than by the numbers: Node's ids are an opaque
// counter that also numbers its module-loading internals, so only these
// hold across implementations — the root execution is id 1 with trigger 0,
// a timer or tick callback runs above the root, a hook's before/after see
// the id of the resource they run for, and init/destroy/ids cross as
// numbers with the modelled resource types. createHook's argument errors
// are Node's own.
'use strict';
const ah = require('async_hooks');
const show = (label, fn) => {
try {
fn();
console.log(label, '=> ok');
} catch (error) {
console.log(label, '=>', error.code, error.message);
}
};
show('createHook()', () => ah.createHook());
show('createHook({ init: 5 })', () => ah.createHook({ init: 5 }));
// An explicit null is present, not absent: Node raises ERR_ASYNC_CALLBACK for
// it, unlike the undefined a missing member reads.
show('createHook({ init: null })', () => ah.createHook({ init: null }));
show('createHook({ after: null })', () => ah.createHook({ after: null }));
show('createHook({ promiseResolve: "x" })', () => ah.createHook({ promiseResolve: 'x' }));
show('createHook(5)', () => ah.createHook(5));
// The numbers themselves are opaque (a loader numbers resources before the
// entry runs, and Node reports no execution id at all in some of those
// environments), so the root is pinned by its shape.
console.log(
'root:',
typeof ah.executionAsyncId() === 'number',
typeof ah.triggerAsyncId() === 'number' && ah.triggerAsyncId() >= 0,
);
// asyncWrapProviders: Node's published provider table, a null-prototype
// object whose names are its own enumerable properties.
const providers = ah.asyncWrapProviders;
console.log(
'providers:',
Object.prototype.toString.call(providers),
Object.getPrototypeOf(providers) === null,
Object.keys(providers).length,
);
console.log(
'provider ids:',
providers.NONE,
providers.PROMISE,
providers.TCPWRAP,
String(providers.TIMERWRAP),
);
let relations = true;
const types = new Set();
// Promise resources are counted while the growth section below creates its
// batch, so only those promises' settlements are tallied.
const track = { collect: false, ids: new Set(), resolved: new Set() };
const hook = ah.createHook({
init(id, type, trigger) {
types.add(type);
if (track.collect && type === 'PROMISE') track.ids.add(id);
if (typeof id !== 'number' || typeof trigger !== 'number') relations = false;
},
promiseResolve(id) {
if (track.ids.has(id)) track.resolved.add(id);
},
before(id) {
if (id !== ah.executionAsyncId()) relations = false;
},
after(id) {
if (id !== ah.executionAsyncId()) relations = false;
},
destroy(id) {
if (typeof id !== 'number') relations = false;
},
});
const enabled = hook.enable();
console.log('enable answers the hook:', enabled === hook);
// An inline literal's members are evaluated in SOURCE order (the literal is
// built before createHook reads it), not in the order of the five slots.
// Members that are not callbacks still run, for their side effects.
const literalOrder = [];
const noop = () => {};
ah.createHook({
promiseResolve: (literalOrder.push('promiseResolve'), noop),
destroy: (literalOrder.push('destroy'), noop),
tail: literalOrder.push('tail'),
after: (literalOrder.push('after'), noop),
before: (literalOrder.push('before'), noop),
init: (literalOrder.push('init'), noop),
});
console.log('literal members evaluated:', literalOrder.join(','));
// Quoted keys and spreads still name the same callbacks.
const spreadOrder = [];
ah.createHook({
...{ promiseResolve: (spreadOrder.push('spread'), noop) },
'init': (spreadOrder.push('quoted init'), noop),
});
console.log('spread and quoted keys:', spreadOrder.join(','));
// Each phase schedules the next, so the output order is causal rather than
// timed.
process.nextTick(() => {
console.log('tick above root:', ah.executionAsyncId() > 1);
setTimeout(() => {
console.log('timer above root:', ah.executionAsyncId() > 1);
console.log('timer trigger is an id:', typeof ah.triggerAsyncId() === 'number');
setImmediate(() => {
// The promise-resource table grows past its initial capacity while
// hundreds of promises stay live: every one of them must still find
// its entry when it settles, or its promiseResolve event disappears.
const resolvers = [];
const batch = [];
track.collect = true;
for (let i = 0; i < 200; i++) batch.push(new Promise((resolve) => resolvers.push(resolve)));
track.collect = false;
const total = track.ids.size;
for (const resolve of resolvers) resolve(total);
Promise.all(batch).then(() => {
console.log('promise table growth:', total, track.resolved.size === total);
hook.disable();
const seen = ['Timeout', 'Immediate', 'TickObject'].every((type) => types.has(type));
console.log('modelled types seen:', seen);
console.log('hook id relations:', relations);
console.log('disable answers the hook:', hook.disable() === hook);
// A computed member name is a callback like any other.
const key = 'promiseResolve';
const computedOrder = [];
ah.createHook({ [key]: (computedOrder.push('computed'), noop) });
console.log('computed key:', computedOrder.join(','));
// An init hook may queue another immediate while this one is being
// queued: the outer callback must survive (Node queues the hook's
// immediate first, so it runs first) and no phantom queue entry may
// be left behind.
const immediateOrder = [];
let queuedInner = false;
const queueHook = ah.createHook({
init(id, type) {
if (type !== 'Immediate' || queuedInner) return;
queuedInner = true;
setImmediate(() => immediateOrder.push('nested'));
},
});
queueHook.enable();
setImmediate(() => immediateOrder.push('outer'));
setImmediate(() => {
queueHook.disable();
console.log('immediate from init:', immediateOrder.join(','));
// A promise resource dies with its promise: across a long
// create/await churn no entry may survive to answer for a later
// promise at a recycled address. Two identical churns leave the
// same set of unfinished ids behind; a third round of dropped
// resolutions means the table kept entries for dead promises. The
// absolute count is the host's own pending internals, so only the
// growth between the rounds is pinned.
const churnLive = new Set();
const churnHook = ah.createHook({
init(id, type) {
if (type === 'PROMISE') churnLive.add(id);
},
promiseResolve(id) {
churnLive.delete(id);
},
});
churnHook.enable();
(async () => {
const churn = async () => {
for (let i = 0; i < 2000; i++) await Promise.resolve(i);
};
await churn();
const first = churnLive.size;
await churn();
const second = churnLive.size;
churnHook.disable();
console.log('promise churn growth:', second - first);
})();
});
});
});
}, 1);
});
@@ -0,0 +1,175 @@
/* Async-hook reentrancy robustness — scriptc-only, sanitized lane.
*
* A synchronous async_hooks callback runs in the middle of the runtime's own
* bookkeeping, and a program can use it to reenter the API that is mid-flight.
* These programs pin that the runtime survives each reentry:
*
* - a promiseResolve hook releases the reader's lock while its closed promise
* settles (the settlement must not run on the promise the reader just let go);
* - a PROMISE init hook releases the reader's lock while a read builds its
* promise (the read answers the releasing error, not a cleared stream);
* - a destroy hook refreshes the one-shot timeout that is being destroyed (the
* re-armed entry must not carry the ids the teardown freed).
*
* SCRIPTC_SAN=1 builds these with ASan + the RC audit like every harness lane,
* which is what turns the last two into hard failures if they regress.
*/
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { promisify } from "node:util";
import { describe, expect, test } from "vitest";
import { compile } from "@scriptc/compiler";
const execFileAsync = promisify(execFile);
const repoRoot = join(import.meta.dirname, "../..");
const sanitize = process.env["SCRIPTC_SAN"] === "1";
/** Compiles one program and runs it, tolerating a nonzero exit. */
async function compileAndRun(
name: string,
source: string,
ext = "cjs",
): Promise<{
stdout: string;
stderr: string;
exitCode: number;
}> {
const key = createHash("sha256")
.update(source)
.update(sanitize ? "san" : "plain")
.update(ext)
.digest("hex")
.slice(0, 16);
const outDir = join(repoRoot, "node_modules/.cache/scriptc-tests", `ah-reentrancy-${key}`);
mkdirSync(outDir, { recursive: true });
const file = join(outDir, `${name}.${ext}`);
writeFileSync(file, source);
const result = await compile(file, {
outPath: join(outDir, name),
outDir,
sanitize,
backend: "llvm",
});
if (!result.ok) {
throw new Error(
"reentrancy program failed to compile:\n" +
result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"),
);
}
try {
const { stdout, stderr } = await execFileAsync(result.binaryPath, [], { encoding: "utf8" });
return { stdout, stderr: stripAsanFiberWarning(stderr), exitCode: 0 };
} catch (err) {
const e = err as { code?: unknown; signal?: unknown; stdout?: string; stderr?: string };
if (typeof e.code !== "number" && typeof e.signal !== "string") throw err;
return {
stdout: e.stdout ?? "",
stderr: stripAsanFiberWarning(e.stderr ?? ""),
exitCode: typeof e.code === "number" ? e.code : -1,
};
}
}
/** Linux ASan's once-per-process context-swap warning (not program output). */
function stripAsanFiberWarning(s: string): string {
return s.replace(
/^==\d+==WARNING: ASan doesn't fully support makecontext\/swapcontext.*\n/gm,
"",
);
}
describe(`async-hook reentrancy (scriptc-only${sanitize ? ", sanitized" : ""})`, () => {
test("a PROMISE init hook can release a reader while its read builds the promise", async () => {
const r = await compileAndRun(
"init-read",
`'use strict';
const { ReadableStream } = require('stream/web');
const { createHook } = require('async_hooks');
let controller;
const stream = new ReadableStream({ start(c) { controller = c; } });
const reader = stream.getReader();
let released = false;
const hook = createHook({
init(id, type) {
if (type !== 'PROMISE' || released) return;
released = true;
try { reader.releaseLock(); } catch {}
},
});
hook.enable();
let pending;
try { pending = reader.read(); } catch { pending = null; }
hook.disable();
if (pending) pending.then(() => console.log('read resolved'), () => console.log('read rejected'));
else console.log('read threw');
setTimeout(() => console.log('done'), 0);
`,
);
expect(r.exitCode).toBe(0);
expect(r.stdout).toBe("read rejected\ndone\n");
});
test("a byte-stream read released in its init hook frees its auto-allocated buffer", async () => {
const r = await compileAndRun(
"init-byte-read",
`'use strict';
const { ReadableStream } = require('stream/web');
const { createHook } = require('async_hooks');
const stream = new ReadableStream(
{ type: 'bytes', autoAllocateChunkSize: 16384, start(c) {}, pull() {} },
{ highWaterMark: 0 },
);
const reader = stream.getReader();
let released = false;
const hook = createHook({
init(id, type) {
if (type !== 'PROMISE' || released) return;
released = true;
try { reader.releaseLock(); } catch {}
},
});
hook.enable();
let pending;
try { pending = reader.read(); } catch { pending = null; }
hook.disable();
if (pending) pending.then(() => console.log('read resolved'), () => console.log('read rejected'));
else console.log('read threw');
setTimeout(() => console.log('done'), 0);
`,
);
expect(r.exitCode).toBe(0);
expect(r.stdout).toBe("read rejected\ndone\n");
});
test("a destroy hook can refresh the one-shot timeout being destroyed", async () => {
const r = await compileAndRun(
"timer-refresh",
`import { createHook } from "async_hooks";
let timer: ReturnType<typeof setTimeout> | undefined;
let refreshed = false;
const hook = createHook({
after() {
if (refreshed || timer === undefined) return;
refreshed = true;
try {
timer.refresh();
} catch {}
},
});
hook.enable();
timer = setTimeout(() => console.log("fired"), 1);
setTimeout(() => {
hook.disable();
console.log("done");
}, 30);
`,
"ts",
);
expect(r.exitCode).toBe(0);
// The after hook's refresh re-arms the timer exactly once, with ids the
// teardown has not freed underneath it.
expect(r.stdout).toBe("fired\nfired\ndone\n");
});
});
@@ -0,0 +1 @@
{ "plain": 900 }
@@ -0,0 +1 @@
{ "plain": 2600 }