fix(javascript): trace wrapped Electron IPC paths in large bundles (#1874)

Co-authored-by: David <17119984+fengdwx@users.noreply.github.com>
This commit is contained in:
David
2026-10-12 09:28:59 +08:00
committed by GitHub
co-authored by David
parent d93fbda390
commit 87b9793c53
46 changed files with 3213 additions and 355 deletions
@@ -0,0 +1,616 @@
import * as t from "@babel/types";
import {
semanticStaticPropertyKey,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import { javascriptBootstrapAt } from "./javascriptBootstrap.js";
import { symbolicLogicalRight } from "./javascriptSymbolicControlFlow.js";
import {
moduleFactory,
modulePropertyName,
} from "./javascriptStaticAnalysisHelpers.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import {
symbolicUnion,
symbolicUnknown,
symbolicVariants,
symbolicTruth,
type SymbolicValue,
type SymbolicEnvironment,
type SymbolicFunction,
} from "./javascriptSymbolicValues.js";
interface PropertyWrite {
readonly path: readonly string[];
readonly value: t.Node;
readonly site: t.Node;
}
interface SymbolicReturnFlow {
readonly values: readonly SymbolicValue[];
readonly fallsThrough: boolean;
}
const emptyEnvironment: SymbolicEnvironment = { values: new Map() };
/** Demand-driven substitutions for local bindings, closures and literal module tables. */
export class JavaScriptSymbolicBindings {
readonly #writes = new Map<string, PropertyWrite[]>();
readonly #environments = new WeakMap<t.Node, SymbolicEnvironment>();
readonly #cache = new WeakMap<
SymbolicEnvironment,
WeakMap<t.Node, SymbolicValue>
>();
readonly #active = new Set<t.Node>();
readonly #activeFunctions = new Set<t.Function>();
readonly #exportAliases = new Map<string, string>();
readonly #moduleBindings = new Set<string>();
readonly #replacements = new Map<string, t.Node>();
readonly #propertyActive = new WeakMap<object, Set<string>>();
readonly #mutated = new Set<string>();
readonly #namespaceOwners = new Map<string, t.Function>();
readonly #unsafeExports = new Set<string>();
#remainingEvaluations = 1_000_000;
#depth = 0;
truncated = false;
constructor(
readonly state: JavaScriptSemanticAnalysisState,
program: t.Program,
) {
traverseJavaScriptAst(program, {
enter: (node) => {
if (t.isCallExpression(node)) this.#indexBootstrap(node);
},
});
traverseJavaScriptAst(program, {
enter: (node) => {
if (t.isAssignmentExpression(node))
this.#indexWrite(node.left, node.right, node);
if (
t.isCallExpression(node) &&
t.isMemberExpression(node.callee) &&
t.isIdentifier(node.callee.object, { name: "Object" }) &&
!resolveSemanticBindingState(state, node.callee.object, "Object") &&
semanticStaticPropertyKey(
node.callee.property,
node.callee.computed,
) === "defineProperty"
) {
const [target, key, descriptor] = node.arguments;
if (
t.isIdentifier(target) &&
t.isStringLiteral(key) &&
t.isObjectExpression(descriptor)
) {
const value = descriptor.properties.find(
(p) =>
t.isObjectProperty(p) &&
semanticStaticPropertyKey(p.key, p.computed) === "value",
);
if (t.isObjectProperty(value))
this.#addWrite(target, [key.value], value.value, node);
}
}
},
});
}
environmentAt(node: t.Node): SymbolicEnvironment {
let current: t.Node | undefined = node;
while (current) {
const found = this.#environments.get(current);
if (found) return found;
current = this.state.parentsByNode.get(current);
}
return emptyEnvironment;
}
evaluate(
input: t.Node | null | undefined,
environment?: SymbolicEnvironment,
): SymbolicValue {
if (!input) return { kind: "literal", value: undefined };
if (--this.#remainingEvaluations < 0 || this.#depth >= 128) {
this.truncated = true;
return symbolicUnknown("symbolic resource limit");
}
const node = unwrapJavaScriptExpression(input).node;
const env = environment ?? this.environmentAt(node);
const cache = this.#cache.get(env) ?? new WeakMap<t.Node, SymbolicValue>();
this.#cache.set(env, cache);
const cached = cache.get(node);
if (cached) return cached;
if (this.#active.has(node)) return symbolicUnknown("cyclic binding");
this.#active.add(node);
this.#depth += 1;
try {
const value = this.#evaluate(node, env);
cache.set(node, value);
return value;
} finally {
this.#active.delete(node);
this.#depth -= 1;
}
}
property(value: SymbolicValue, key: string): SymbolicValue {
const active = this.#propertyActive.get(value) ?? new Set<string>();
if (active.has(key)) return symbolicUnknown("cyclic property");
active.add(key);
this.#propertyActive.set(value, active);
try {
return this.#property(value, key);
} finally {
active.delete(key);
}
}
#property(value: SymbolicValue, key: string): SymbolicValue {
if (value.kind === "union")
return symbolicUnion(value.values.map((v) => this.property(v, key)));
if (value.kind === "external")
return { kind: "external", path: [...value.path, key] };
if (value.kind === "record")
return value.values.get(key) ?? symbolicUnknown("missing property");
if (value.kind === "namespace") {
if (
this.#mutated.has(value.bindingId) ||
this.#unsafeExports.has(`${value.bindingId}:${key}`)
)
return symbolicUnknown("ambiguous export writes");
const replacement = this.#replacements.get(value.bindingId);
if (replacement)
return this.property(
this.evaluate(replacement, value.environment),
key,
);
const writes = (this.#writes.get(value.bindingId) ?? []).filter(
(w) => w.path.length === 1 && w.path[0] === key,
);
const write = writes.at(-1);
return write
? this.evaluate(write.value, value.environment)
: symbolicUnknown("unresolved module export");
}
if (value.kind === "object") {
for (const p of [...value.node.properties].reverse()) {
if (t.isSpreadElement(p)) {
const spread = this.evaluate(p.argument, value.environment);
const found = this.property(spread, key);
if (found.kind !== "unknown") return found;
if (
this.unknownMembers(spread) > 0 ||
this.members(spread).includes(key)
)
return found;
} else if (semanticStaticPropertyKey(p.key, p.computed) === key) {
return t.isObjectMethod(p) && p.kind !== "method"
? symbolicUnknown("accessor property")
: this.evaluate(
t.isObjectProperty(p) ? p.value : p,
value.environment,
);
} else if (semanticStaticPropertyKey(p.key, p.computed) === null)
return symbolicUnknown("dynamic property overwrite");
}
}
if (value.kind === "array" && /^\d+$/u.test(key))
return value.values[Number(key)] ?? symbolicUnknown("missing argument");
return symbolicUnknown("unresolved property");
}
members(
value: SymbolicValue,
active = new Set<SymbolicValue>(),
): readonly string[] {
if (active.has(value)) return [];
active.add(value);
if (value.kind === "union")
return [...new Set(value.values.flatMap((v) => this.members(v, active)))];
if (value.kind === "record") return [...value.values.keys()];
if (value.kind === "namespace") {
const replacement = this.#replacements.get(value.bindingId);
return replacement
? this.members(this.evaluate(replacement, value.environment), active)
: [
...new Set(
(this.#writes.get(value.bindingId) ?? []).flatMap((w) =>
w.path.length === 1 ? w.path : [],
),
),
];
}
if (value.kind !== "object") return [];
return [
...new Set(
value.node.properties.flatMap((p) =>
t.isSpreadElement(p)
? this.members(this.evaluate(p.argument, value.environment), active)
: [semanticStaticPropertyKey(p.key, p.computed)].filter(
(k): k is string => k !== null,
),
),
),
];
}
unknownMembers(
value: SymbolicValue,
active = new Set<SymbolicValue>(),
): number {
if (active.has(value)) return 1;
active.add(value);
if (value.kind === "union")
return value.values.reduce(
(sum, v) => sum + this.unknownMembers(v, active),
0,
);
if (value.kind === "record") return 0;
if (value.kind === "namespace") {
if (this.#mutated.has(value.bindingId)) return 1;
const replacement = this.#replacements.get(value.bindingId);
return replacement
? this.unknownMembers(
this.evaluate(replacement, value.environment),
active,
)
: 0;
}
if (value.kind !== "object") return 1;
return value.node.properties.reduce(
(sum, p) =>
sum +
(t.isSpreadElement(p)
? this.unknownMembers(
this.evaluate(p.argument, value.environment),
new Set(active),
)
: Number(semanticStaticPropertyKey(p.key, p.computed) === null)),
0,
);
}
bind(
fn: SymbolicFunction,
args: readonly SymbolicValue[],
): SymbolicEnvironment {
const values = new Map<string, SymbolicValue>();
fn.node.params.forEach((param, index) => {
const target = t.isRestElement(param) ? param.argument : param;
if (!t.isIdentifier(target)) return;
const binding = resolveSemanticBindingState(
this.state,
target,
target.name,
);
if (binding)
values.set(
binding.bindingId,
t.isRestElement(param)
? { kind: "array", values: args.slice(index) }
: (args[index] ?? symbolicUnknown("runtime parameter")),
);
});
return { values, parent: fn.environment };
}
arguments(
node: t.CallExpression | t.OptionalCallExpression,
env: SymbolicEnvironment,
): readonly SymbolicValue[] {
return node.arguments.flatMap((a) => {
if (!t.isSpreadElement(a)) return [this.evaluate(a, env)];
const value = this.evaluate(a.argument, env);
return value.kind === "array"
? value.values
: [symbolicUnknown("dynamic spread arguments")];
});
}
#evaluate(node: t.Node, env: SymbolicEnvironment): SymbolicValue {
if (
t.isStringLiteral(node) ||
t.isNumericLiteral(node) ||
t.isBooleanLiteral(node)
)
return { kind: "literal", value: node.value };
if (t.isNullLiteral(node)) return { kind: "literal", value: null };
if (t.isFunction(node))
return { kind: "function", node, environment: env, origins: [] };
if (t.isObjectExpression(node))
return { kind: "object", node, environment: env };
if (t.isIdentifier(node)) return this.#identifier(node, env);
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const key = semanticStaticPropertyKey(node.property, node.computed);
return key === null
? symbolicUnknown("dynamic member")
: this.property(this.evaluate(node.object, env), key);
}
if (t.isSequenceExpression(node))
return this.evaluate(node.expressions.at(-1), env);
if (t.isAssignmentExpression(node)) return this.evaluate(node.right, env);
if (t.isAwaitExpression(node)) return this.evaluate(node.argument, env);
if (t.isUnaryExpression(node)) {
const value = this.evaluate(node.argument, env);
if (node.operator === "void")
return { kind: "literal", value: undefined };
const truth = symbolicTruth(value);
if (node.operator === "!" && truth !== undefined)
return { kind: "literal", value: !truth };
}
if (t.isConditionalExpression(node)) {
const truth = symbolicTruth(this.evaluate(node.test, env));
return truth === undefined
? symbolicUnion([
this.evaluate(node.consequent, env),
this.evaluate(node.alternate, env),
])
: this.evaluate(truth ? node.consequent : node.alternate, env);
}
if (t.isLogicalExpression(node)) {
const left = this.evaluate(node.left, env);
const right = symbolicLogicalRight(node.operator, left);
if (right !== undefined)
return right ? this.evaluate(node.right, env) : left;
return symbolicUnion([left, this.evaluate(node.right, env)]);
}
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
return this.#call(node, env);
return symbolicUnknown(`unsupported ${node.type}`);
}
#identifier(node: t.Identifier, env: SymbolicEnvironment): SymbolicValue {
const binding = resolveSemanticBindingState(this.state, node, node.name);
if (
!binding &&
node.name === "undefined" &&
!semanticResolutionBlocked(this.state, node, node.name)
)
return { kind: "literal", value: undefined };
if (!binding)
return !semanticResolutionBlocked(this.state, node, node.name) &&
["require", "navigator", "String", "Boolean"].includes(node.name)
? { kind: "external", path: [node.name] }
: symbolicUnknown("unbound identifier");
if (binding.definitions.some((d) => d.kind === "assignment"))
return symbolicUnknown("reassigned binding");
if (this.#mutated.has(binding.bindingId))
return symbolicUnknown("dynamic member writes");
for (let e: SymbolicEnvironment | undefined = env; e; e = e.parent) {
const value = e.values.get(binding.bindingId);
if (value) return value;
}
if (this.#writes.has(binding.bindingId))
return symbolicUnknown("overwritten object members");
const initializer =
binding.initializers.length === 1 ? binding.initializers[0] : undefined;
if (!initializer)
return symbolicUnknown("missing or ambiguous initializer");
if (this.state.conditionalInitializers.has(initializer.node))
return symbolicUnknown("conditional initializer");
let value = this.evaluate(initializer.node, env);
for (const key of initializer.projection) {
if (key === null) return symbolicUnknown("dynamic destructuring");
value = this.property(value, String(key));
}
return value;
}
#call(
node: t.CallExpression | t.OptionalCallExpression,
env: SymbolicEnvironment,
): SymbolicValue {
const callee = this.evaluate(node.callee, env);
const args = this.arguments(node, env);
return symbolicUnion(
symbolicVariants(callee).map((value) => {
if (value.kind === "loader") {
const key = args[0];
return key?.kind === "literal"
? (value.modules.get(String(key.value)) ??
symbolicUnknown("missing module"))
: symbolicUnknown("dynamic module");
}
if (value.kind === "external" && value.path.join(".") === "require") {
const spec = args[0];
return spec?.kind === "literal" && typeof spec.value === "string"
? { kind: "external", path: [spec.value] }
: symbolicUnknown("dynamic require");
}
if (value.kind !== "function" || this.#activeFunctions.has(value.node))
return symbolicUnknown("unresolved or recursive call");
this.#activeFunctions.add(value.node);
try {
const bound = this.bind(value, args);
const result = t.isBlockStatement(value.node.body)
? this.#returns(value.node.body.body, bound)
: this.evaluate(value.node.body, bound);
return symbolicUnion(
symbolicVariants(result).map((v) =>
v.kind === "function"
? { ...v, origins: [...value.origins, node, ...v.origins] }
: v,
),
);
} finally {
this.#activeFunctions.delete(value.node);
}
}),
);
}
#returns(
statements: readonly t.Statement[],
env: SymbolicEnvironment,
): SymbolicValue {
const flow = this.#returnFlow(statements, env);
return symbolicUnion([
...flow.values,
...(flow.fallsThrough
? [{ kind: "literal" as const, value: undefined }]
: []),
]);
}
#returnFlow(
statements: readonly t.Statement[],
env: SymbolicEnvironment,
depth = 0,
): SymbolicReturnFlow {
const possible: SymbolicValue[] = [];
for (const statement of statements) {
if (--this.#remainingEvaluations < 0 || depth >= 128) {
this.truncated = true;
return {
values: [...possible, symbolicUnknown("symbolic resource limit")],
fallsThrough: false,
};
}
if (t.isThrowStatement(statement))
return {
values: [...possible, symbolicUnknown("wrapper exits by throwing")],
fallsThrough: false,
};
if (t.isReturnStatement(statement))
return {
values: [...possible, this.evaluate(statement.argument, env)],
fallsThrough: false,
};
if (t.isBlockStatement(statement)) {
const flow = this.#returnFlow(statement.body, env, depth + 1);
possible.push(...flow.values);
if (!flow.fallsThrough)
return { values: possible, fallsThrough: false };
}
if (t.isIfStatement(statement)) {
const truth = symbolicTruth(this.evaluate(statement.test, env));
const branches =
truth === undefined
? [statement.consequent, statement.alternate]
: [truth ? statement.consequent : statement.alternate];
const flows = branches.map((branch) =>
this.#returnFlow(branch ? [branch] : [], env, depth + 1),
);
possible.push(...flows.flatMap((flow) => flow.values));
if (flows.every((flow) => !flow.fallsThrough))
return { values: possible, fallsThrough: false };
}
}
return { values: possible, fallsThrough: true };
}
#indexBootstrap(call: t.CallExpression): void {
const bootstrap = javascriptBootstrapAt(call);
if (!bootstrap) return;
const modules = new Map<string, SymbolicValue>();
for (const property of bootstrap.table.properties) {
const factory = moduleFactory(property);
if (!factory) continue;
const values = new Map<string, SymbolicValue>();
const environment = { values };
const first = factory.params[0];
const second = factory.params[1];
const third = factory.params[2];
const binding = (n: t.Node | undefined) =>
t.isIdentifier(n)
? resolveSemanticBindingState(this.state, n, n.name)?.bindingId
: undefined;
const moduleId = binding(first);
const exportsId = binding(second);
const loaderId = binding(third);
const namespaceId = `${String(factory.start)}:exports`;
this.#namespaceOwners.set(namespaceId, factory);
const namespace: SymbolicValue = {
kind: "namespace",
bindingId: namespaceId,
environment,
};
if (moduleId) {
values.set(moduleId, {
kind: "record",
values: new Map([["exports", namespace]]),
});
this.#exportAliases.set(moduleId, namespaceId);
this.#moduleBindings.add(moduleId);
}
if (exportsId) {
values.set(exportsId, namespace);
this.#exportAliases.set(exportsId, namespaceId);
}
if (loaderId) values.set(loaderId, { kind: "loader", modules });
this.#environments.set(factory, environment);
modules.set(modulePropertyName(property), namespace);
}
}
#indexWrite(target: t.Node, value: t.Node, site: t.Node): void {
const path: string[] = [];
let root = target;
let dynamic = false;
while (t.isMemberExpression(root)) {
const key = semanticStaticPropertyKey(root.property, root.computed);
if (key === null) dynamic = true;
else path.unshift(key);
root = root.object;
}
if (dynamic && t.isIdentifier(root)) {
const binding = resolveSemanticBindingState(this.state, root, root.name);
if (binding)
this.#mutated.add(
this.#exportAliases.get(binding.bindingId) ?? binding.bindingId,
);
return;
}
if (t.isIdentifier(root)) this.#addWrite(root, path, value, site);
}
#addWrite(
root: t.Identifier,
path: readonly string[],
value: t.Node,
site: t.Node,
): void {
const binding = resolveSemanticBindingState(this.state, root, root.name);
if (!binding) return;
const alias = this.#exportAliases.get(binding.bindingId);
if (this.#moduleBindings.has(binding.bindingId) && path[0] !== "exports")
return;
const key = alias ?? binding.bindingId;
const selected = this.#moduleBindings.has(binding.bindingId)
? path.slice(1)
: path;
if (alias) {
const owner = this.#namespaceOwners.get(alias);
for (
let parent = this.state.parentsByNode.get(site);
parent && parent !== owner;
parent = this.state.parentsByNode.get(parent)
) {
if (
t.isFunction(parent) ||
t.isIfStatement(parent) ||
t.isConditionalExpression(parent) ||
t.isLogicalExpression(parent) ||
t.isLoop(parent) ||
t.isSwitchCase(parent) ||
t.isTryStatement(parent)
) {
if (selected.length === 0) this.#mutated.add(key);
else this.#unsafeExports.add(`${key}:${selected[0] ?? ""}`);
return;
}
}
}
if (alias && selected.length === 0) {
this.#replacements.set(key, value);
return;
}
const writes = this.#writes.get(key) ?? [];
writes.push({ path: selected, value, site });
this.#writes.set(key, writes);
}
}