fix(javascript): qualify releases after resource method mutation (#10166)

* fix(javascript): qualify releases after resource method mutation

* fix(javascript): qualify releases after opaque receiver mutation

* fix(javascript): preserve release ordering and mutation facts

* fix(javascript): order mutations of fresh resource receivers

* fix(javascript): match release mutations to captured receivers

* fix(javascript): check delegated release method identity

* fix(javascript): track paths back to native resource prototypes

* fix(javascript): respect native release member ownership

* fix(javascript): retain shared prototype effects across calls

* fix(javascript): order release effects after definite acquisition

* fix(javascript): preserve prototype effects across receiver replacement

* fix(javascript): preserve native release identity across proven effects

* fix(javascript): preserve shared prototype uncertainty after opaque calls

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
RRFZandmorluto authored and GitHub committed 2026-11-18 17:02:04 -05:00
1 parent 2191896f3b
commit caab34d0de
8 files changed
+812 -56

No files matched your search

@@ -20,18 +20,43 @@ export const BUILTIN_RESOURCE_METHODS = {
* `FileHandle` and a `net.Socket`/`TLSSocket` each expose only their own subset,
* so a family-blind release list claims a teardown that throws instead.
*/
export const BUILTIN_RESOURCE_RELEASE_METHODS = {
"fs:open": [],
"fs:openSync": [],
"fs:createReadStream": ["close", "destroy"],
"fs:createWriteStream": ["close", "destroy", "end"],
"fs/promises:open": ["close"],
"net:connect": ["destroy", "end"],
"net:createConnection": ["destroy", "end"],
"tls:connect": ["destroy", "end"],
} as const satisfies Readonly<
Record<string, readonly ("close" | "destroy" | "end")[]>
>;
type ReleaseMethod = "close" | "destroy" | "end";
export interface BuiltinResourceReleaseMember {
readonly owner: "instance" | "prototype";
readonly definingPrototypeDepth?: number;
readonly delegates?: readonly ReleaseMethod[];
}
const inherited = { owner: "prototype" } as const;
// Each entry lists the release methods looked up inside the native call.
const releases: Readonly<
Record<string, Partial<Record<ReleaseMethod, BuiltinResourceReleaseMember>>>
> = {
"fs:createReadStream": {
close: {
owner: "prototype",
definingPrototypeDepth: 1,
delegates: ["destroy"],
},
destroy: { owner: "prototype", definingPrototypeDepth: 2 },
},
"fs:createWriteStream": {
close: {
owner: "prototype",
definingPrototypeDepth: 1,
delegates: ["end", "destroy"],
},
destroy: { owner: "prototype", definingPrototypeDepth: 2 },
end: { owner: "prototype", definingPrototypeDepth: 2 },
},
"fs/promises:open": { close: { owner: "instance" } },
"net:connect": { destroy: inherited, end: inherited },
"net:createConnection": { destroy: inherited, end: inherited },
"tls:connect": { destroy: inherited, end: inherited },
};
export const builtinResourceReleases = (specifier: string, method: string) =>
releases[`${specifier}:${method}`];
export const BUILTIN_RESOURCE_SPECIFIERS = Object.keys(
BUILTIN_RESOURCE_METHODS,
@@ -0,0 +1,443 @@
import { expect, it } from "vitest";
import { analyzeCommonJsSemanticFixture } from "../../../tests/fixtures/javascriptCommonJsAnalysis.js";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
const releases = (source: string) =>
analyzeJavaScriptSemantics(source).resourceOperations.filter(
({ kind }) => kind === "release",
);
it("keeps a method mutation on a candidate CommonJS acquisition", () => {
expect(
releases(`
const { createReadStream } = require("node:fs");
const stream = createReadStream("fixture.txt");
stream.close = replacement;
stream.close();
`),
).toMatchObject([{ builtinAuthority: "candidate", resolution: "partial" }]);
});
it.each([
"stream.destroy = () => stream;",
"const alias = stream; alias.destroy = () => alias;",
"Object.assign(stream, { destroy: () => stream });",
"Object.defineProperty(stream, 'destroy', { value: () => stream });",
"delete stream.destroy;",
"stream[key] = replacement;",
"Object.setPrototypeOf(stream, replacement);",
"decorate(stream);",
])("qualifies release after a receiver effect: %s", (effect) => {
const result = releases(`
import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
${effect}
stream.destroy();
`);
expect(result).toMatchObject([{ method: "destroy", resolution: "partial" }]);
expect(result[0]?.linkedResourceIds).toHaveLength(1);
});
it("qualifies FileHandle.close and writable stream end methods too", () => {
expect(
releases(`
import { open } from "node:fs/promises";
import { createWriteStream } from "node:fs";
const file = await open("fixture.txt");
file.close = () => {};
file.close();
const stream = createWriteStream("output.txt");
stream.end = () => stream;
stream.end();
`).map(({ resolution }) => resolution),
).toEqual(["partial", "partial"]);
});
it("keeps unrelated properties and writes after the release complete", () => {
expect(
releases(`
import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
stream.label = "fixture";
stream.destroy.label = "metadata";
stream.destroy();
stream.destroy = () => stream;
`),
).toMatchObject([{ resolution: "complete" }]);
});
it.each([
"stream.destroy",
"stream.__proto__.destroy",
"stream.__proto__.constructor.prototype.destroy",
])("keeps the callable identity after observing %s", (observed) => {
expect(
releases(`
import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
observe(${observed});
stream.destroy();
`),
).toMatchObject([{ resolution: "complete" }]);
});
it.each([
"stream.__proto__.constructor.prototype",
"stream.constructor",
"stream.constructor.prototype",
"stream.__proto__.constructor.prototype.__proto__",
"stream[key].prototype",
])(
"qualifies releases after handing out a possible prototype via %s",
(prototype) => {
expect(
releases(`import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
decorate(${prototype});
stream.destroy();`),
).toMatchObject([{ resolution: "partial" }]);
},
);
it.each([
["stream.constructor.prototype.destroy = replacement", "partial"],
["stream.constructor.prototype = {}", "complete"],
["stream.__proto__.constructor.prototype = {}", "complete"],
["stream.__proto__ = replacement", "partial"],
["stream.constructor.prototype.__proto__ = replacement", "partial"],
["stream.__proto__.constructor.prototype.label = 1", "complete"],
])("checks the written prototype slot in %s", (write, resolution) => {
expect(
releases(`import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
${write};
stream.destroy();`),
).toMatchObject([{ resolution }]);
});
it.each([
["file.__proto__.close = replacement", "complete"],
["file.constructor.prototype.close = replacement", "complete"],
["decorate(file.__proto__)", "complete"],
["file.__proto__ = replacement", "complete"],
["file.close = replacement", "partial"],
["delete file.close", "partial"],
["decorate(file)", "partial"],
])("checks the FileHandle instance field after %s", (effect, resolution) => {
expect(
releases(`import { open } from "node:fs/promises";
const file = await open("fixture.txt");
${effect};
file.close();`),
).toMatchObject([{ method: "close", resolution }]);
});
it.each([
["createReadStream", "stream.destroy = () => {}; stream.close()", "partial"],
[
"createReadStream",
"stream.close(stream.destroy = () => stream)",
"partial",
],
["createWriteStream", "stream.end = () => {}; stream.close()", "partial"],
["createReadStream", "observe(stream.__proto__); stream.close()", "partial"],
["createReadStream", "stream.end = () => {}; stream.close()", "complete"],
])("checks %s release dependencies in %s", (factory, body, resolution) => {
expect(
releases(
`import { ${factory} } from "node:fs"; const stream = ${factory}("fixture.txt"); ${body};`,
),
).toMatchObject([{ method: "close", resolution }]);
});
it.each([
["createReadStream", "close", 1, "partial"],
["createReadStream", "close", 2, "complete"],
["createReadStream", "destroy", 2, "partial"],
["createWriteStream", "close", 2, "complete"],
["createWriteStream", "end", 2, "partial"],
])(
"respects %s close lookup after a %s write at depth %i",
(factory, method, depth, resolution) => {
expect(
releases(`
import { ${factory} } from "node:fs";
const stream = ${factory}("fixture.txt");
stream${".__proto__".repeat(depth)}.${method} = replacement;
stream.close();
`),
).toMatchObject([{ method: "close", resolution }]);
},
);
it.each([
["await file.close(); await file.close();", ["complete", "complete"]],
[
'file.once("close", () => { file.close = replacement; }); file.close(); file.close();',
["partial", "partial"],
],
[
"file.close(); file.close = replacement; file.close();",
["complete", "partial"],
],
])("checks each FileHandle release in %s", (body, resolutions) => {
expect(
releases(`
import { open } from "node:fs/promises";
const file = await open("fixture.txt");
${body}
`).map(({ resolution }) => resolution),
).toEqual(resolutions);
});
it("keeps uncertainty when the exported stream constructor was replaced", () => {
expect(
releases(`
import fs, { createReadStream } from "node:fs";
class Base { close() {} }
class Custom extends Base {}
fs.ReadStream = Custom;
const stream = createReadStream("fixture.txt");
stream.__proto__.__proto__.close = replacement;
stream.close();
`),
).toMatchObject([{ resolution: "partial" }]);
});
it.each(["EventEmitter", "default"])(
"retains FileHandle receiver effects if the %s event emitter can run user code",
(origin) => {
expect(
releases(`
import { ${origin} as Emitter } from "node:events";
import { open } from "node:fs/promises";
Emitter.prototype.emit = function (event) {
if (event === "close") this.close = replacement;
};
const file = await open("fixture.txt");
await file.close();
await file.close();
`).map(({ resolution }) => resolution),
).toEqual(["complete", "partial"]);
},
);
it.each([
'eval("stream.destroy = () => stream");',
'const alias = stream; eval("alias.destroy = () => alias");',
'const mutate = () => { eval("stream.destroy = () => stream"); }; mutate();',
])("qualifies a constant receiver after direct eval: %s", (effect) => {
const result = releases(`
import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
${effect}
stream.destroy();
`);
expect(result).toMatchObject([{ method: "destroy", resolution: "partial" }]);
expect(result[0]?.linkedResourceIds).toHaveLength(1);
});
it("qualifies sibling release methods after opaque reference mutation", () => {
expect(
releases(`
import { open } from "node:fs/promises";
import { createWriteStream } from "node:fs";
const file = await open("fixture.txt");
const stream = createWriteStream("output.txt");
eval("file.close = () => {}; stream.end = () => stream");
file.close();
stream.end();
`).map(({ resolution }) => resolution),
).toEqual(["partial", "partial"]);
});
it("keeps releases before eval and calls to shadowed eval complete", () => {
expect(
releases(`
import { createReadStream } from "node:fs";
const stream = createReadStream("fixture.txt");
stream.destroy();
eval("stream.destroy = () => stream");
`),
).toMatchObject([{ resolution: "complete" }]);
expect(
releases(`
import { createReadStream } from "node:fs";
function run(eval) {
const stream = createReadStream("fixture.txt");
eval("stream.destroy = () => stream");
stream.destroy();
}
`),
).toMatchObject([{ resolution: "complete" }]);
});
it("captures release methods before argument-side replacements", () => {
expect(
releases(`
import { createReadStream, createWriteStream } from "node:fs";
import { open } from "node:fs/promises";
const stream = createReadStream("fixture.txt");
stream.close(stream.close = () => {});
const output = createWriteStream("output.txt");
output.end("done", output.end = () => {});
const file = await open("fixture.txt");
file.close(file.close = () => {});
`).map(({ resolution }) => resolution),
).toEqual(["complete", "complete", "complete"]);
});
it("retains shared module escapes after collecting resource receiver paths", () => {
const result = analyzeCommonJsSemanticFixture(`
const fs = require("node:fs");
const other = require("fs");
other.readFileSync("before.json");
const stream = other.createReadStream("before.json");
stream.destroy();
patch(fs);
other.readFileSync("wrong-after.json");
`);
expect(result.configurationOperations.map(({ key }) => key)).toEqual([
"before.json",
]);
expect(
result.resourceOperations.filter(({ kind }) => kind === "release"),
).toMatchObject([{ resolution: "complete" }]);
});
it("keeps a fresh local release before an instance write complete", () => {
expect(
releases(`
import { createReadStream } from "node:fs";
function run() {
const stream = createReadStream("fixture.txt");
stream.close();
stream.close = () => {};
}
`),
).toMatchObject([{ resolution: "complete" }]);
});
it.each([
["stream.close(); stream.close = () => {};", "complete"],
["stream.close(); decorate(stream);", "partial"],
['stream.close(); eval("stream.__proto__.close = () => {}");', "partial"],
["stream.close(); stream.__proto__.close = () => {};", "partial"],
["stream.close = () => {}; stream.close();", "partial"],
])(
"orders local placeholder acquisition and effects: %s",
(body, resolution) => {
expect(
releases(`
import { createReadStream } from "node:fs";
function run() {
let stream = null;
stream = createReadStream("fixture.txt");
${body}
}
run(); run();
`),
).toMatchObject([{ resolution }]);
},
);
it("keeps a fresh local method captured before argument evaluation complete", () => {
expect(
releases(`
import { createReadStream } from "node:fs";
function run() {
const stream = createReadStream("fixture.txt");
stream.close(stream.close = () => {});
}
`),
).toMatchObject([{ resolution: "complete" }]);
});
it.each([
["stream.__proto__.destroy = replacement", "partial"],
["stream.constructor.prototype.destroy = replacement", "partial"],
["decorate(stream.__proto__)", "partial"],
["decorate(stream.constructor)", "partial"],
["stream.__proto__ = replacement", "complete"],
["stream.destroy = replacement", "complete"],
["observe(stream.__proto__.destroy)", "complete"],
])(
"accounts for effects shared with the next invocation: %s",
(effect, resolution) => {
expect(
releases(`import { createReadStream } from "node:fs";
function run() {
const stream = createReadStream("fixture.txt");
stream.destroy();
${effect};
}
run(); run();`),
).toMatchObject([{ resolution }]);
},
);
it("retains prior mutations and persistent receiver effects", () => {
expect(
releases(`
import { createReadStream } from "node:fs";
const shared = createReadStream("fixture.txt");
function prior() {
const stream = createReadStream("fixture.txt");
stream.close = () => {};
stream.close();
}
function persistent() {
shared.close();
shared.close = () => {};
}
`).map(({ resolution }) => resolution),
).toEqual(["partial", "partial"]);
});
it.each([
'stream.close=()=>{}; stream=createReadStream("new");',
'const old=stream; old.close=()=>{}; stream=createReadStream("new");',
'const old=stream; stream=createReadStream("new"); old.close=()=>{};',
])(
"does not transfer an incoming receiver effect to its replacement: %s",
(body) => {
expect(
releases(
`import {createReadStream} from "node:fs"; function run(stream) {${body} stream.close();}`,
),
).toMatchObject([{ resolution: "complete" }]);
},
);
it.each([
"stream.__proto__.destroy = () => {};",
"stream.constructor.prototype.destroy = () => {};",
"decorate(stream.__proto__);",
"Object.getPrototypeOf(stream).destroy = () => {};",
"decorate(stream);",
])(
"keeps a shared prototype effect through receiver replacement: %s",
(effect) => {
expect(
releases(`
import { createReadStream } from "node:fs";
function run(stream) {
${effect}
stream = createReadStream("new");
stream.destroy();
}
`),
).toMatchObject([{ resolution: "partial" }]);
},
);
it.each([
'stream.close=()=>{}; if (flag) stream=createReadStream("new");',
'stream=createReadStream("new"); const alias=stream; alias.close=()=>{};',
])("keeps effects on a possible current receiver: %s", (body) => {
expect(
releases(
`import {createReadStream} from "node:fs"; function run(stream) {${body} stream.close();}`,
),
).toMatchObject([{ resolution: "partial" }]);
});
@@ -848,7 +848,7 @@ const processSnapshotObjectRoot = (
};
/** Check shared exports at the use or method-capture point, not at every later call. */
const requiredModuleChanged = (
export const requiredModuleChanged = (
specifier: string,
selected: readonly string[],
capture: t.Node,
@@ -40,6 +40,7 @@ import {
semanticBindingLookupAt,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticBindingState,
type JavaScriptSemanticMemberEffect,
type JavaScriptSemanticReferenceEffectsAtSite,
} from "./javascriptSemanticState.js";
@@ -587,11 +588,131 @@ export const prototypeMutationMayPrecede = (
semanticEffectTiming(read, effect.node, state) !== "after",
);
/**
* Whether the `method` a read selects from `binding`'s object may have been
* replaced before the read: by direct eval that can reach the object (a const
* binding still exposes its properties), or by a write to the object, to
* `method` or to its prototype, or by an escape of the object or its
* prototype. Passing the method itself cannot replace its native [[Call]], and
* the call that receives the object has already selected the method.
* With `fresh`, each activation initializes a new instance. Writes to a
* shared prototype can still reach later activations or replacement receivers.
* `targets` filters only effects confined to the selected instance.
*/
export const bindingMethodMayHaveChanged = (
binding: JavaScriptSemanticBindingState,
method: string,
read: t.Node,
state: JavaScriptSemanticAnalysisState,
{
fresh,
inherited,
definingPrototypeDepth,
isolatedNativeCloses,
targets,
}: {
fresh: boolean;
inherited: boolean;
definingPrototypeDepth: number | undefined;
isolatedNativeCloses: boolean;
targets: (effect: JavaScriptSemanticMemberEffect) => boolean;
},
): boolean => {
// A prototype hop stays on the receiver chain. A constructor hop can
// return to that chain through .prototype. A wildcard may do either.
const reachesReceiver = (
path: JavaScriptSemanticPropertyPath,
length: number,
escape = false,
) => {
if (!inherited) return length === 0;
let receiver = true;
let constructor = false;
for (let i = 0; i < length && (receiver || constructor); i++) {
const key = path[i]!;
const nextConstructor: boolean =
receiver && semanticPropertyPathKeyMatches(key, "constructor");
receiver =
(receiver && semanticPropertyPathKeyMatches(key, "__proto__")) ||
(constructor && semanticPropertyPathKeyMatches(key, "prototype"));
constructor = nextConstructor;
}
// The native constructor itself also exposes its mutable prototype.
return receiver || (escape && constructor);
};
const mayPrecede = (
effect: t.Node | undefined,
onInstance: boolean,
): boolean =>
semanticEffectTiming(read, effect, state) !== "after" &&
!(
fresh &&
onInstance &&
effect !== undefined &&
semanticReadPrecedesEffectWithinActivation(
read,
effect,
state.parentsByNode,
)
);
for (const effect of semanticOpaqueBindingEffects(
binding,
state,
"reference",
))
if (mayPrecede(effect, !inherited)) return true;
const shadowedWrite = (path: JavaScriptSemanticPropertyPath): boolean =>
definingPrototypeDepth !== undefined &&
path.length - 1 > definingPrototypeDepth &&
path.at(-1) === method &&
path.slice(0, -1).every((key) => key === "__proto__");
return (
binding.memberWrites.some(
(effect) =>
(effect.path.length > 1 || targets(effect)) &&
!shadowedWrite(effect.path) &&
// A write changes a slot on its parent. Rebinding C.prototype
// leaves the prototype of an already acquired receiver intact.
(effect.path.length === 0 ||
(reachesReceiver(effect.path, effect.path.length - 1) &&
(semanticPropertyPathKeyMatches(effect.path.at(-1)!, method) ||
(inherited &&
semanticPropertyPathKeyMatches(
effect.path.at(-1)!,
"__proto__",
))))) &&
mayPrecede(effect.node, effect.path.length <= 1),
) ||
binding.escapedPaths.some((effect) => {
// An opaque caller handed an instance can still reach its shared prototype.
const instanceOnly = effect.path.length === 0 && !inherited;
return (
!(isolatedNativeCloses && effect.path.length === 0) &&
(!instanceOnly || targets(effect)) &&
reachesReceiver(effect.path, effect.path.length, true) &&
effect.node !== state.parentsByNode.get(read) &&
mayPrecede(effect.node, instanceOnly)
);
})
);
};
/** Whether a member write to `binding`'s object is recorded. */
export const bindingHasMemberWrites = (
binding: JavaScriptSemanticBindingState,
): boolean => binding.memberWrites.length > 0;
/** An opaque release can see the receiver only through its recorded effects. */
export const bindingEffectsConfinedToReceiverCalls = (
binding: JavaScriptSemanticBindingState,
matchesCall: (node: t.Node) => boolean,
): boolean =>
!bindingHasMemberWrites(binding) &&
binding.escapedPaths.every(
({ node, path }) =>
path.length === 0 && node !== undefined && matchesCall(node),
);
/**
* The nodes recorded member writes to `binding`'s object involve, in record
* order: each write's site (undefined when it was recorded without one), then
@@ -1,3 +1,4 @@
import { builtinResourceReleases } from "./javascriptBuiltinResourceMethods.js";
import * as t from "@babel/types";
import { semanticKnownSymbolKey } from "./javascriptSemanticPropertyKeys.js";
import {
@@ -35,6 +36,7 @@ import {
clearSemanticValueCaches,
evaluateSemanticBinding,
evaluateSemanticExpression,
evaluateSemanticExpressionProvenance,
} from "./javascriptSemanticValues.js";
import { semanticContainer } from "./javascriptSemanticSlots.js";
import {
@@ -1388,14 +1390,18 @@ export function* collectSemanticMemberMutationsSteps(
// Stored receiver projections preserve their raw capture authority.
// Initializer origins retain the normalized mutation traversal below.
retainsInitializers = receiver?.retainsOrigin !== false;
// A direct receiver keeps its alias capture. Projected receivers
// select their child at the member read, after capturing the root.
const receiverAt =
current.path.length > 1
? (current.memberReadAt ?? current.originAt)
: current.originAt;
if (effect === "escape")
recordBindingEffect(binding.escapedPaths, {
path,
node: mutation,
receiverInitializers,
...(current.originAt === undefined
? {}
: { receiverAt: current.memberReadAt ?? current.originAt }),
...(receiverAt === undefined ? {} : { receiverAt }),
});
else
recordBindingEffect(binding.memberWrites, {
@@ -1403,9 +1409,7 @@ export function* collectSemanticMemberMutationsSteps(
path,
node: mutation,
receiverInitializers,
...(current.originAt === undefined
? {}
: { receiverAt: current.memberReadAt ?? current.originAt }),
...(receiverAt === undefined ? {} : { receiverAt }),
...(assignedSources === undefined ? {} : { assignedSources }),
});
clearSemanticValueCaches(state);
@@ -2420,6 +2424,34 @@ const observableMutationPaths = (
const selected = pendingExpressions.pop();
if (selected === undefined) break;
const { expression, observer } = selected;
if (
t.isCallExpression(expression) ||
t.isOptionalCallExpression(expression)
) {
// Retain possible resource slots from provenance alone. Final built-in
// admission depends on the mutations this pass is still collecting.
if (
evaluateSemanticExpressionProvenance(
expression.callee,
state,
).origins.some(({ specifier, importedPath }) => {
const identity = semanticRequireExportsIdentity(
specifier,
importedPath[0] === "default"
? importedPath.slice(1)
: importedPath,
);
return (
identity.path.length === 1 &&
builtinResourceReleases(
identity.specifier,
identity.path[0]!,
) !== undefined
);
})
)
(observer.origins ??= new Set()).add("opaque");
}
if (t.isFunction(expression))
// Keep own-member writes precise without replacing the existing
// links to references handed to a function's eventual caller.
@@ -1920,22 +1920,20 @@ export const semanticBindingEffectFollowsRead = (
effect: t.Node,
parents: WeakMap<t.Node, t.Node>,
): boolean => {
const initializer = binding.initializers[0];
if (binding.initializers.length !== 1 || initializer === undefined)
return false;
const declaration = parents.get(initializer.node);
// A logical/compound assignment may preserve a value from a prior call.
if (
!t.isVariableDeclarator(declaration) ||
declaration.init !== initializer.node
)
return false;
const initialized = initializerPosition(initializer, parents);
const selected = bindingReadPosition(read, parents).position;
return (
initialized !== null &&
selected !== null &&
positionPrecedes(initialized, selected) &&
binding.initializers.some((initializer) => {
const declaration = parents.get(initializer.node);
// Later assignments do not undo the declaration's reset each activation.
if (
!t.isVariableDeclarator(declaration) ||
declaration.init !== initializer.node
)
return false;
const initialized = initializerPosition(initializer, parents);
return initialized !== null && positionPrecedes(initialized, selected);
}) &&
semanticReadPrecedesEffectWithinActivation(read, effect, parents)
);
};
@@ -1813,6 +1813,9 @@ export const semanticRequireExportsIdentity = <Key>(
): { readonly specifier: string; readonly path: readonly (Key | string)[] } => {
const name = specifier.replace(/^node:/u, "");
if (name === "fs/promises") return { specifier: name, path };
// The events export and its EventEmitter alias expose the same constructor.
if (name === "events" && path[0] === "EventEmitter" && path.length > 1)
return { specifier: name, path: path.slice(1) };
if (["path", "path/posix", "path/win32"].includes(name)) {
let selected = name;
let remaining = path;
@@ -1835,6 +1838,7 @@ const MUTABLE_BUILTIN_DEFAULTS = new Set([
"http",
"https",
"child_process",
"events",
"timers",
"process",
"path",
@@ -1856,6 +1860,8 @@ export const semanticMutableBuiltinOrigin = <Key = never>(
const specifier = origin.specifier.replace(/^node:/u, "");
if (!MUTABLE_BUILTIN_DEFAULTS.has(specifier)) return undefined;
if (path[0] === "default") return { specifier, path: path.slice(1) };
if (specifier === "events" && path[0] === "EventEmitter" && path.length > 1)
return { specifier, path };
if (specifier === "process" && (path[0] === "env" || path[0] === "argv"))
return { specifier, path };
return specifier === "fs" && path[0] === "promises"
@@ -4,7 +4,8 @@ import { rejectsSemanticEventListener } from "./javascriptSemanticAsyncEffects.j
import {
BUILTIN_RESOURCE_SPECIFIERS,
BUILTIN_RESOURCE_METHODS,
BUILTIN_RESOURCE_RELEASE_METHODS,
builtinResourceReleases,
type BuiltinResourceReleaseMember,
} from "./javascriptBuiltinResourceMethods.js";
import type {
JavaScriptSemanticCallable,
@@ -22,6 +23,8 @@ import {
} from "./javascriptAstValues.js";
import { isUnmodifiedGlobalReference } from "./javascriptSemanticGlobalReference.js";
import {
bindingEffectsConfinedToReceiverCalls,
bindingMethodMayHaveChanged,
opaqueCodeMayRebindBinding,
prototypeMutationMayPrecede,
} from "./javascriptSemanticEffectLog.js";
@@ -30,11 +33,13 @@ import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticBindingState,
type JavaScriptSemanticMemberEffect,
} from "./javascriptSemanticState.js";
import {
builtinDataEffectIdentity,
dataEffectMemberCallee,
outerDataEffectBinding,
requiredModuleChanged,
traverseDataEffects,
type DataEffectTraversalContext,
} from "./javascriptSemanticDataEffectHelpers.js";
@@ -42,20 +47,6 @@ import { FS_OPEN_FLAGS, range } from "./javascriptStaticAnalysisHelpers.js";
const RELEASE_METHODS = ["close", "destroy", "end"] as const;
/**
* Release methods the value from this acquisition actually has. An unlisted
* specifier/method pair admits none, so a call to it emits no release fact.
*/
const releaseMethodsFor = (
acquisition: ResourceCandidate,
): readonly ("close" | "destroy" | "end")[] => {
const key = `${acquisition.specifier}:${acquisition.method}`;
const table: Readonly<
Record<string, readonly ("close" | "destroy" | "end")[]>
> = BUILTIN_RESOURCE_RELEASE_METHODS;
return table[key] ?? [];
};
interface ResourceCandidate {
readonly builtinAuthority?: "candidate";
readonly node: t.CallExpression | t.OptionalCallExpression;
@@ -426,6 +417,25 @@ const collectAcquisitions = (
return output;
};
/** FileHandle.close can run close listeners. Exempt receiver effects only
* when the binding has no writes or exposures besides direct native closes. */
const hasOnlyDirectCloseInvocations = (
binding: JavaScriptSemanticBindingState,
state: JavaScriptSemanticAnalysisState,
): boolean =>
bindingEffectsConfinedToReceiverCalls(binding, (node) => {
if (!t.isCallExpression(node) || node.arguments.length !== 0) return false;
const member = dataEffectMemberCallee(node);
return (
member !== null &&
t.isIdentifier(member.object) &&
semanticStaticPropertyName(member.property, member.computed) ===
"close" &&
resolveSemanticBindingState(state, member.object, member.object.name) ===
binding
);
});
const collectReleases = (
program: t.Program,
context: DataEffectTraversalContext,
@@ -439,6 +449,7 @@ const collectReleases = (
byBinding.set(acquisition.resultBindingId, existing);
}
const output: JavaScriptSemanticResourceOperation[] = [];
const isolatedFileHandles = new Map<string, boolean>();
traverseDataEffects(program, context, (node) => {
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) return;
const member = dataEffectMemberCallee(node);
@@ -462,21 +473,38 @@ const collectReleases = (
context.state,
member.object,
);
const receiver = candidates.some(({ resultIsPromise }) => resultIsPromise)
? semanticBindingAtRead(binding, member.object, context.state).binding
: binding;
const receiver = semanticBindingAtRead(
binding,
member.object,
context.state,
);
const knownAcquisitions = new Set<t.Node>(
candidates
.filter(({ builtinAuthority }) => builtinAuthority === undefined)
.map(({ node }) => node),
);
const selectedSources = [
...receiver.binding.initializers,
...receiver.binding.referenceInitializers,
];
const fresh =
receiver.status === "ordered" &&
receiver.hasDefiniteInitializer &&
selectedSources.length > 0 &&
selectedSources.every(
({ node, projection }) =>
projection.length === 0 &&
knownAcquisitions.has(resourceInitializer(node).value),
);
const releasesFor = (acquisition: ResourceCandidate) =>
builtinResourceReleases(acquisition.specifier, acquisition.method);
const linked = candidates.filter(
(acquisition) =>
releaseMethodsFor(acquisition).includes(method) &&
releasesFor(acquisition)?.[method] !== undefined &&
(!acquisition.resultIsPromise ||
opaqueReceiver ||
mayReceiveFulfilledHandle(
receiver,
receiver.binding,
acquisition,
knownAcquisitions,
context.state,
@@ -485,6 +513,47 @@ const collectReleases = (
// No linked acquisition exposes this release method, so the call is not a
// release of it at all: Node throws at the call site instead.
if (linked.length === 0) return;
const possibleAcquisitions = new Set(linked.map(({ node }) => node));
const [first] = linked;
const members =
linked.length === 1 && first ? releasesFor(first) : undefined;
const release = members?.[method];
const streamConstructor =
first?.specifier !== "fs"
? undefined
: first.method === "createReadStream"
? "ReadStream"
: first.method === "createWriteStream"
? "WriteStream"
: undefined;
const streamConstructorMayHaveChanged =
first !== undefined &&
streamConstructor !== undefined &&
requiredModuleChanged(
"fs",
[streamConstructor],
first.node,
context.state,
);
let isolatedNativeCloses = false;
if (
fresh &&
first?.specifier === "fs/promises" &&
release?.owner === "instance"
) {
isolatedNativeCloses =
isolatedFileHandles.get(binding.bindingId) ??
hasOnlyDirectCloseInvocations(binding, context.state);
isolatedFileHandles.set(binding.bindingId, isolatedNativeCloses);
isolatedNativeCloses =
isolatedNativeCloses &&
!requiredModuleChanged(
"events",
["prototype", "emit"],
member,
context.state,
);
}
output.push({
resourceId: `resource:release:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
kind: "release",
@@ -498,10 +567,27 @@ const collectReleases = (
: {}),
resolution:
!opaqueReceiver &&
linked.length === 1 &&
(binding.kind !== "parameter" ||
semanticBindingAtRead(binding, member.object, context.state)
.hasDefiniteInitializer) &&
!streamConstructorMayHaveChanged &&
release !== undefined &&
!releaseMethodMayHaveChanged(
binding,
method,
member,
context.state,
possibleAcquisitions,
{ fresh, release, isolatedNativeCloses },
) &&
!release.delegates?.some((dependency) =>
releaseMethodMayHaveChanged(
binding,
dependency,
node,
context.state,
possibleAcquisitions,
{ fresh, release: members?.[dependency] },
),
) &&
(binding.kind !== "parameter" || receiver.hasDefiniteInitializer) &&
holdsOnlyAcquisitions(binding, linked, context.state)
? "complete"
: "partial",
@@ -510,6 +596,51 @@ const collectReleases = (
return output;
};
/** Receiver identity alone cannot prove a release method survived mutation. */
const releaseMethodMayHaveChanged = (
binding: JavaScriptSemanticBindingState,
method: string,
read: t.Node,
state: JavaScriptSemanticAnalysisState,
acquisitions: ReadonlySet<t.Node>,
{
fresh,
release,
isolatedNativeCloses = false,
}: {
fresh: boolean;
release: BuiltinResourceReleaseMember | undefined;
isolatedNativeCloses?: boolean;
},
): boolean => {
const targetsAcquisition = (
effect: JavaScriptSemanticMemberEffect,
): boolean => {
const capture = effect.receiverAt ?? effect.node;
if (capture === undefined) return true;
const selected = semanticBindingAtRead(binding, capture, state);
if (selected.status !== "ordered") return true;
// Empty incoming values cannot be the fresh acquisition selected later.
// Keep ambiguous aliases and projections unless the owner excludes them.
return [
...selected.binding.initializers,
...selected.binding.referenceInitializers,
].some(
({ node, projection }) =>
projection.length > 0 ||
!binding.initializers.some((source) => source.node === node) ||
acquisitions.has(resourceInitializer(node).value),
);
};
return bindingMethodMayHaveChanged(binding, method, read, state, {
fresh,
inherited: release?.owner !== "instance",
definingPrototypeDepth: fresh ? release?.definingPrototypeDepth : undefined,
isolatedNativeCloses,
targets: targetsAcquisition,
});
};
/** Unwrap only direct awaits; a standalone await does not write its operand. */
const resourceInitializer = (node: t.Node) => {
let value = unwrapJavaScriptExpression(node).node;