From 1a322ab75b7c5a0ce09fd200b9c3e580a72fab6b Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:22:43 +0800 Subject: [PATCH] fix(javascript): preserve intrinsic invocation read identity --- docs/javascript-artifact-reconstruction.md | 5 +- .../electronIntrinsicCapture.test.ts | 70 ++++++++++ .../javascript/electronModuleInterop.test.ts | 4 + .../javascriptElectronMemberWrites.ts | 100 +++++++------- .../javascriptIntrinsicInvocation.ts | 6 + .../javascript/javascriptModuleInterop.ts | 124 +++++++++++++----- .../electronModuleInteropCli.test.ts | 8 +- 7 files changed, 231 insertions(+), 86 deletions(-) create mode 100644 src/domain/javascript/electronIntrinsicCapture.test.ts diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md index 7442fc746..f4de7e972 100644 --- a/docs/javascript-artifact-reconstruction.md +++ b/docs/javascript-artifact-reconstruction.md @@ -348,7 +348,10 @@ argument prefixes and the original bound receiver through `call`, `apply`, and `Reflect.apply`, including generic `Function.prototype` invocation and binding creation. Visibly replaced invocation intrinsics produce unknown effects instead of using their former call semantics; captured function aliases retain their -earlier identity. Unexamined +earlier identity. Invocation member reads are checked separately from the earlier function capture. +Comma-expression callees use their final value while all preceding expressions +remain in the effect traversal. Call effects are classified after callee and +argument effects have been collected. Unexamined targets remain unresolved. `Reflect.set` examines its explicit receiver as well as its target, retaining unknown receiver effects. Creating an unused binding does not itself mutate an intrinsic. Variable redeclarations retain a single unconditional initializer diff --git a/src/domain/javascript/electronIntrinsicCapture.test.ts b/src/domain/javascript/electronIntrinsicCapture.test.ts new file mode 100644 index 000000000..f2690ff3d --- /dev/null +++ b/src/domain/javascript/electronIntrinsicCapture.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; + +import { ROLLDOWN_MODULE_INTEROP } from "./javascriptModuleInterop.fixture.js"; +import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js"; + +const CAPTURED_INTEROP = ROLLDOWN_MODULE_INTEROP.replace( + "__defProp = Object.defineProperty", + "__defProp = define", +); +const WINDOW = `let electron = require("electron"); + electron = __toESM(electron, 1); new electron.BrowserWindow({});`; + +describe("captured intrinsic invocation reads", () => { + it("retains callee-prefix effects before classifying the invocation", () => { + const result = analyzeJavaScriptStaticSource(` + const define = Object.defineProperty; + const metadata = {}; + (Object.defineProperty = replacement, Object.defineProperty)(metadata,"x",{value:1}); + ${CAPTURED_INTEROP} ${WINDOW} + `); + expect(result.electron.browser_windows).toEqual([]); + }); + + it("retains a callee selected before an argument replaces its global property", () => { + const result = analyzeJavaScriptStaticSource(` + const define = Object.defineProperty; + const metadata = {}; + Object.defineProperty(metadata,"x",(Object.defineProperty = replacement,{value:1})); + ${CAPTURED_INTEROP} ${WINDOW} + `); + expect(result.electron.browser_windows).toHaveLength(1); + }); + + it.each([ + 'define.call(null,metadata,"x",{value:1});', + 'define.apply(null,[metadata,"x",{value:1}]);', + 'const change = define.bind(null,metadata,"x"); change({value:1});', + 'const also = define; also.call(null,metadata,"x",{value:1});', + ])("retains a function captured before global replacement: %s", (invoke) => { + const result = analyzeJavaScriptStaticSource(` + const define = Object.defineProperty; + Object.defineProperty = replacement; + const metadata = {}; ${invoke} + ${CAPTURED_INTEROP} ${WINDOW} + `); + expect(result.electron.browser_windows).toHaveLength(1); + }); + + it.each([ + ["call", 'define.call(null,metadata,"x",{value:1});'], + ["apply", 'define.apply(null,[metadata,"x",{value:1}]);'], + [ + "bind", + 'const change = define.bind(null,metadata,"x"); change({value:1});', + ], + ])( + "checks the later %s property read on a captured function", + (method, invoke) => { + for (const owner of ["define", "Function.prototype"]) { + const result = analyzeJavaScriptStaticSource(` + const define = Object.defineProperty; + ${owner}.${method} = replacement; + const metadata = {}; ${invoke} + ${CAPTURED_INTEROP} ${WINDOW} + `); + expect(result.electron.browser_windows, owner).toEqual([]); + } + }, + ); +}); diff --git a/src/domain/javascript/electronModuleInterop.test.ts b/src/domain/javascript/electronModuleInterop.test.ts index bdaf113bf..fa5605d4e 100644 --- a/src/domain/javascript/electronModuleInterop.test.ts +++ b/src/domain/javascript/electronModuleInterop.test.ts @@ -571,6 +571,9 @@ describe("Electron module interop bound mutators", () => { 'const change = Object.defineProperty.call; change(null,Object,"create",{value:customCreate});', 'const {apply:change} = Object.defineProperty; change(null,[Object,"create",{value:customCreate}]);', 'const change = Reflect.apply.call; change(null,Object.defineProperty,null,[Object,"create",{value:customCreate}]);', + '(0, Object.defineProperty)(Object,"create",{value:customCreate});', + 'const change = Object.defineProperty.bind(null,Object,"create"); (0, change)({value:customCreate});', + '(0, Reflect.apply)(Object.defineProperty,null,[Object,"create",{value:customCreate}]);', ])("rejects intrinsic writes through a bound mutator: %s", (write) => { expect( analyzeJavaScriptStaticSource( @@ -597,6 +600,7 @@ describe("Electron module interop bound mutators", () => { 'const {apply:change} = Object.defineProperty; change(null,[metadata,"x",{value:1}]);', 'Reflect.set(metadata,"x",1,{});', 'const receiver = {}; Reflect.set({},"x",1,receiver);', + '(0, Object.defineProperty)(metadata,"x",{value:1});', ])("keeps a fresh bound target or unused binding separate: %s", (write) => { expect( analyzeJavaScriptStaticSource( diff --git a/src/domain/javascript/javascriptElectronMemberWrites.ts b/src/domain/javascript/javascriptElectronMemberWrites.ts index 003b495e0..453b7667f 100644 --- a/src/domain/javascript/javascriptElectronMemberWrites.ts +++ b/src/domain/javascript/javascriptElectronMemberWrites.ts @@ -79,60 +79,60 @@ export function* collectJavaScriptIdentityWritesSteps( "setPrototypeOf", ]); const keyedMutators = new Set(["set", "deleteProperty", "defineProperty"]); - yield* traverseJavaScriptAstSteps(program, { - enter: (node) => { - if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) { - const invocation = intrinsicInvocation(node); - if (invocation?.kind === "opaque") { + const retainCallEffects = ( + node: t.CallExpression | t.OptionalCallExpression, + ): void => { + const invocation = intrinsicInvocation(node); + if (invocation?.kind === "opaque") { + const scope = origin(node, "opaque-call"); + if (scope !== undefined) retain(node, scope); + return; + } + const callee = invocation?.path; + const arguments_ = invocation?.arguments; + const method = callee?.at(-1); + const owner = callee?.length === 3 ? callee[1] : undefined; + if ( + (owner === "Object" && objectMutators.has(method ?? "")) || + (owner === "Reflect" && reflectMutators.has(method ?? "")) + ) { + // Reflect.set can write through its explicit receiver as well as + // dispatching through its target. Both identities need examination. + const targets = + owner === "Reflect" && + method === "set" && + arguments_ !== undefined && + (arguments_.length >= 4 || arguments_.some(t.isSpreadElement)) + ? [ + arguments_[0], + arguments_.some(t.isSpreadElement) ? undefined : arguments_[3], + ] + : [arguments_?.[0]]; + for (const target of targets) { + // A known mutator with an opaque argument list can overwrite any + // captured intrinsic. Do not turn an unexamined target into proof. + if (target === undefined || t.isSpreadElement(target)) { const scope = origin(node, "opaque-call"); if (scope !== undefined) retain(node, scope); - return; } - const callee = invocation?.path; - const arguments_ = invocation?.arguments; - const method = callee?.at(-1); - const owner = callee?.length === 3 ? callee[1] : undefined; - if ( - (owner === "Object" && objectMutators.has(method ?? "")) || - (owner === "Reflect" && reflectMutators.has(method ?? "")) - ) { - // Reflect.set can write through its explicit receiver as well as - // dispatching through its target. Both identities need examination. - const targets = - owner === "Reflect" && - method === "set" && - arguments_ !== undefined && - (arguments_.length >= 4 || arguments_.some(t.isSpreadElement)) - ? [ - arguments_[0], - arguments_.some(t.isSpreadElement) - ? undefined - : arguments_[3], - ] - : [arguments_?.[0]]; - for (const target of targets) { - // A known mutator with an opaque argument list can overwrite any - // captured intrinsic. Do not turn an unexamined target into proof. - if (target === undefined || t.isSpreadElement(target)) { - const scope = origin(node, "opaque-call"); - if (scope !== undefined) retain(node, scope); - } - if (t.isNode(target) && !t.isSpreadElement(target)) { - const { root, members } = electronMemberPath(target); - const exported = origin(root, "member"); - if (exported !== undefined) { - const key = keyedMutators.has(method ?? "") - ? [staticString(arguments_?.[1]) ?? null] - : []; - retain(node, [...exported, ...members, ...key]); - } else if (!freshObject(target)) { - const scope = origin(node, "opaque-call"); - if (scope !== undefined) retain(node, scope); - } - } + if (t.isNode(target) && !t.isSpreadElement(target)) { + const { root, members } = electronMemberPath(target); + const exported = origin(root, "member"); + if (exported !== undefined) { + const key = keyedMutators.has(method ?? "") + ? [staticString(arguments_?.[1]) ?? null] + : []; + retain(node, [...exported, ...members, ...key]); + } else if (!freshObject(target)) { + const scope = origin(node, "opaque-call"); + if (scope !== undefined) retain(node, scope); } } } + } + }; + yield* traverseJavaScriptAstSteps(program, { + enter: (node) => { const target = t.isAssignmentExpression(node) ? node.left : t.isUpdateExpression(node) @@ -154,5 +154,9 @@ export function* collectJavaScriptIdentityWritesSteps( if (exported !== undefined) retain(node, [...exported, ...members]); } }, + exit: (node) => { + if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) + retainCallEffects(node); + }, }); } diff --git a/src/domain/javascript/javascriptIntrinsicInvocation.ts b/src/domain/javascript/javascriptIntrinsicInvocation.ts index e34efe04a..ff905b93b 100644 --- a/src/domain/javascript/javascriptIntrinsicInvocation.ts +++ b/src/domain/javascript/javascriptIntrinsicInvocation.ts @@ -40,6 +40,12 @@ export const resolveJavaScriptIntrinsicInvocation = ( let receiver: t.Node | undefined; for (;;) { callee = unwrapJavaScriptExpression(callee).node; + if (t.isSequenceExpression(callee)) { + const finalExpression = callee.expressions.at(-1); + if (finalExpression === undefined) return undefined; + callee = finalExpression; + continue; + } if (visited.has(callee)) return undefined; visited.add(callee); let path = intrinsicPath(callee); diff --git a/src/domain/javascript/javascriptModuleInterop.ts b/src/domain/javascript/javascriptModuleInterop.ts index 35e1c9ef1..ab9e1a387 100644 --- a/src/domain/javascript/javascriptModuleInterop.ts +++ b/src/domain/javascript/javascriptModuleInterop.ts @@ -20,7 +20,7 @@ import { type JavaScriptIntrinsicInvocation, } from "./javascriptElectronMemberWrites.js"; import { resolveJavaScriptIntrinsicInvocation } from "./javascriptIntrinsicInvocation.js"; -import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js"; +import { semanticPropertyPathKeyMatches } from "./javascriptSemanticPropertyPaths.js"; import { readExactJavaScriptLiteral, unwrapJavaScriptExpression, @@ -71,6 +71,16 @@ interface InteropHelper { readonly identity: boolean; } +const intrinsicWriteCovers = ( + written: readonly (string | null)[], + read: readonly string[], +): boolean => + written.length <= read.length && + written.every((key, index) => { + const name = read[index]; + return name !== undefined && semanticPropertyPathKeyMatches(key, name); + }); + /** Prove one inert namespace conversion without relaxing general assignment semantics. */ export const createSemanticModuleInterop = ( state: JavaScriptSemanticAnalysisState, @@ -82,7 +92,7 @@ export const createSemanticModuleInterop = ( const writes: { readonly scope: string; readonly offset: number; - readonly coverage: SemanticPropertyPathCoverage; + readonly path: readonly (string | null)[]; }[] = []; const invalidatedBindings = new Map(); const invalidatedCalls = new WeakMap(); @@ -117,6 +127,12 @@ export const createSemanticModuleInterop = ( const { root, members } = electronMemberPath(current); if (members.some((member) => member === null)) return finish(undefined); suffix = [...(members as readonly string[]), ...suffix]; + if (t.isSequenceExpression(root)) { + const value = root.expressions.at(-1); + if (value === undefined) return finish(undefined); + current = value; + continue; + } for (const global of ["Object", "Function", "Reflect"]) if (isUnshadowedGlobal(root, state, global)) return finish(["intrinsic", global, ...suffix]); @@ -157,8 +173,20 @@ export const createSemanticModuleInterop = ( let capturedAt = node; let suffixLength = 0; for (;;) { + current = unwrapJavaScriptExpression(current).node; + if (suffixLength === 0) + capturedAt = + t.isMemberExpression(current) || t.isOptionalMemberExpression(current) + ? current.property + : current; const { root, members } = electronMemberPath(current); suffixLength += members.length; + if (t.isSequenceExpression(root)) { + const value = root.expressions.at(-1); + if (value === undefined) return undefined; + current = value; + continue; + } if (!t.isIdentifier(root)) return undefined; const binding = resolveSemanticBindingState(state, root, root.name); if (binding === undefined) return { path, capturedAt }; @@ -209,24 +237,56 @@ export const createSemanticModuleInterop = ( node: t.Node, path: readonly string[], ): boolean => { - const capture = capturedIntrinsic(node)?.capturedAt ?? node; - const scope = opaqueMutationPath(capture).join("."); - const method = path.at(-1); - const invocationMethod = - method === "bind" || method === "call" || method === "apply"; - return writes.some( - (write) => - (write.scope === scope || write.scope === "intrinsic") && - write.offset < (capture.start ?? -1) && - (write.coverage.covers(path) || - (invocationMethod && - write.coverage.covers([ - "intrinsic", - "Function", - "prototype", - method, - ]))), - ); + let current = unwrapJavaScriptExpression(node).node; + let currentPath = path; + for (;;) { + const method = currentPath.at(-1); + const invocationMethod = + method === "bind" || method === "call" || method === "apply"; + if ( + invocationMethod && + (t.isMemberExpression(current) || t.isOptionalMemberExpression(current)) + ) { + // Reading an invocation member does not recapture the stored function. + // Check member writes now, then check its base at the earlier capture. + const scope = opaqueMutationPath(current).join("."); + const offset = current.property.start ?? -1; + if ( + writes.some( + (write) => + (write.scope === scope || write.scope === "intrinsic") && + write.offset < offset && + ((write.path.length >= currentPath.length && + intrinsicWriteCovers(write.path, currentPath)) || + intrinsicWriteCovers(write.path, [ + "intrinsic", + "Function", + "prototype", + method, + ])), + ) + ) + return true; + current = unwrapJavaScriptExpression(current.object).node; + currentPath = currentPath.slice(0, -1); + continue; + } + const capture = capturedIntrinsic(current)?.capturedAt ?? current; + const scope = opaqueMutationPath(capture).join("."); + return writes.some( + (write) => + (write.scope === scope || write.scope === "intrinsic") && + write.offset < (capture.start ?? -1) && + (intrinsicWriteCovers(write.path, currentPath) || + (invocationMethod && + intrinsicWriteCovers(write.path, [ + "intrinsic", + "Function", + "prototype", + method, + ]))), + ); + } }; const resolveBoundIntrinsic = ( @@ -270,7 +330,7 @@ export const createSemanticModuleInterop = ( if (members.at(-1) === "bind") { // A direct .bind may continue a bound callable, without discarding members. if (!terminal && members.length !== 1) return undefined; - bindReads.push(captured?.capturedAt ?? current.callee); + bindReads.push(current.callee); } else { // Reuse the invocation owner for generic call/apply/Reflect.apply of bind. const invocation = resolveJavaScriptIntrinsicInvocation( @@ -290,6 +350,8 @@ export const createSemanticModuleInterop = ( captured = capturedIntrinsic(bindTarget); terminal = captured !== undefined; path = captured?.path; + opaqueArguments ||= + path !== undefined && intrinsicReadChanged(bindTarget, path); } receiver = bindingArguments?.[0]; const ownArguments = bindingArguments?.slice(1) ?? []; @@ -304,17 +366,9 @@ export const createSemanticModuleInterop = ( continue; } const boundPath = [...path, "bind"]; - const functionBind = ["intrinsic", "Function", "prototype", "bind"]; - opaqueArguments ||= bindReads.some((capture) => { - const scope = opaqueMutationPath(capture).join("."); - return writes.some( - (write) => - (write.scope === scope || write.scope === "intrinsic") && - write.offset < (capture.start ?? -1) && - (write.coverage.covers(boundPath) || - write.coverage.covers(functionBind)), - ); - }); + opaqueArguments ||= bindReads.some((capture) => + intrinsicReadChanged(capture, boundPath), + ); return { kind: opaqueArguments ? "opaque" : "known", path, @@ -602,7 +656,7 @@ export const createSemanticModuleInterop = ( (write) => (write.scope === scope || write.scope === "intrinsic") && write.offset < (capturedAt.start ?? -1) && - write.coverage.covers(path), + intrinsicWriteCovers(write.path, path), ); }) ?? false; return { @@ -621,12 +675,10 @@ export const createSemanticModuleInterop = ( isFreshObject, opaqueMutationPath, retainWrite: (node: t.Node, path: readonly (string | null)[]) => { - const coverage = new SemanticPropertyPathCoverage(); - coverage.retain(path[0] === "opaque-intrinsic" ? ["intrinsic"] : path); writes.push({ scope: opaqueMutationPath(node).join("."), offset: node.start ?? Infinity, - coverage, + path: path[0] === "opaque-intrinsic" ? ["intrinsic"] : path, }); }, invalidated: (binding: JavaScriptSemanticBindingState): boolean => { diff --git a/tests/acceptance/applications/electronModuleInteropCli.test.ts b/tests/acceptance/applications/electronModuleInteropCli.test.ts index badad8696..3cefe1d80 100644 --- a/tests/acceptance/applications/electronModuleInteropCli.test.ts +++ b/tests/acceptance/applications/electronModuleInteropCli.test.ts @@ -37,6 +37,10 @@ const INTRINSIC_MUTATIONS = [ 'const change = Object.defineProperty.bind(null,Object,"create"); change({value:customCreate});', ], ["receiver.cjs", 'Reflect.set({},"create",customCreate,Object);'], + [ + "sequence.cjs", + '(0,Object.defineProperty)(Object,"create",{value:customCreate});', + ], ] as const; cliTest.for(["CLI", "stdio MCP"] as const)( @@ -75,6 +79,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)( function hoistedFunction() {} const captured = Object.defineProperty; Object.defineProperty = custom; + captured.call(null,metadata,"captured",{value:1}); ${ROLLDOWN_MODULE_INTEROP.replace("__defProp = Object.defineProperty", "__defProp = captured")} let electron = require("electron"); electron = __toESM(electron, 1); @@ -105,6 +110,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)( require("./generic-bind.cjs"); require("./replaced-apply.cjs"); require("./receiver.cjs"); + require("./sequence.cjs"); throw new Error("must not execute main"); `; await writeFile(join(root, "main.cjs"), source); @@ -131,7 +137,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)( preload_entrypoints: 1, }); expect(result.statistics.parse_failures).toBe(0); - expect(result.statistics.parsed_javascript_files).toBe(10); + expect(result.statistics.parsed_javascript_files).toBe(11); const windows = result.graph.nodes.filter( ({ kind }) => kind === "browser-window", );