From b5d9f6027bb3228c92c3b7943ec7eb6affa0bd03 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Fri, 4 Dec 2026 05:55:49 +0100 Subject: [PATCH] Add an isolated function bind experiment --- .../experiments/function-bind/BindContract.ts | 52 +++++ .../ExperimentalFunctionBindTest.kt | 114 ++++++++++ .../function-bind/experiment.patch | 204 ++++++++++++++++++ usvm-ts/experiments/function-bind/run.py | 39 ++++ 4 files changed, 409 insertions(+) create mode 100644 usvm-ts/experiments/function-bind/BindContract.ts create mode 100644 usvm-ts/experiments/function-bind/ExperimentalFunctionBindTest.kt create mode 100644 usvm-ts/experiments/function-bind/experiment.patch create mode 100644 usvm-ts/experiments/function-bind/run.py diff --git a/usvm-ts/experiments/function-bind/BindContract.ts b/usvm-ts/experiments/function-bind/BindContract.ts new file mode 100644 index 0000000000..778eeca7e9 --- /dev/null +++ b/usvm-ts/experiments/function-bind/BindContract.ts @@ -0,0 +1,52 @@ +class Bias { + readonly offset: number; + + constructor(offset: number) { + this.offset = offset; + } + + lexicalArrow(receiver: Bias): number { + const arrow = (first: number, second: number): number => this.offset + first * 10 + second; + return arrow.bind(receiver, 2)(3); + } +} + +class OwnBind { + bind(offset: number): number { + return offset + 200; + } +} + +function ordinary(this: Bias, first: number, second: number): number { + return this.offset + first * 10 + second; +} + +function nullReceiver(this: Bias | null, first: number, second: number): number { + return (this === null ? 100 : this.offset) + first * 10 + second; +} + +export class BindContract { + static prefixAndThis(): number { + const bound = ordinary.bind(new Bias(7), 2); + return bound(3); + } + + static secondBindKeepsReceiver(): number { + return nullReceiver.bind(null, 2).bind(new Bias(7), 3)(); + } + + static lexicalThis(): number { + return new Bias(11).lexicalArrow(new Bias(7)); + } + + static distinctIdentity(): boolean { + const receiver = new Bias(7); + const first = ordinary.bind(receiver, 1); + const second = ordinary.bind(receiver, 1); + return first !== second; + } + + static userMethod(): number { + return new OwnBind().bind(1); + } +} diff --git a/usvm-ts/experiments/function-bind/ExperimentalFunctionBindTest.kt b/usvm-ts/experiments/function-bind/ExperimentalFunctionBindTest.kt new file mode 100644 index 0000000000..167073e602 --- /dev/null +++ b/usvm-ts/experiments/function-bind/ExperimentalFunctionBindTest.kt @@ -0,0 +1,114 @@ +package org.usvm.machine.call + +import org.jacodb.ets.utils.loadEtsProjectAutoConvert +import org.junit.jupiter.api.io.TempDir +import org.usvm.PathSelectionStrategy +import org.usvm.StateCollectionStrategy +import org.usvm.api.TsTestValue +import org.usvm.machine.TsInterpreterObserver +import org.usvm.machine.TsMachine +import org.usvm.machine.TsOptions +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.TsTestResolver +import org.usvm.util.assertNodeReplay +import org.usvm.util.getResourcePath +import java.nio.file.Path +import kotlin.io.path.readText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ExperimentalFunctionBindTest : TsMethodTestRunner() { + private val resource = getResourcePath("/models/function-bind-experiment") + override val scene = loadEtsProjectAutoConvert(resource, useArkAnalyzerTypeInference = null) + + @TempDir + lateinit var directory: Path + + init { + options = options.copy( + pathSelectionStrategies = listOf(PathSelectionStrategy.BFS), + stateCollectionStrategy = StateCollectionStrategy.ALL, + stopOnCoverage = 0, + throwExceptionOnStepFailure = true, + ) + } + + @Test + fun `enabled prototype returns the same five values as Node`() { + for ((method, expected) in expectedReturns) { + val run = analyze(method, enabled = true) + + assertEquals(setOf(expected), run.values, method) + assertEquals(method != "userMethod", run.applied, method) + } + + val assertions = expectedReturns.entries.joinToString(separator = "\n") { (method, expected) -> + "if (BindContract.$method() !== $expected) throw Error('$method');" + } + assertNodeReplay( + source = resource.resolve("BindContract.ts").readText() + "\n" + assertions, + directory = directory, + name = "function-bind-experiment", + timeoutMessage = "Native bind checks did not finish", + ) + } + + @Test + fun `disabled prototype leaves native bind to the configured fallback`() { + val nativeMethod = analyze("prefixAndThis", enabled = false) + val projectMethod = analyze("userMethod", enabled = false) + + assertTrue(nativeMethod.stopped) + assertFalse(nativeMethod.applied) + assertTrue(nativeMethod.values.isEmpty()) + assertFalse(projectMethod.applied) + assertEquals(setOf(201.0), projectMethod.values) + } + + private fun analyze(name: String, enabled: Boolean): BindingRun { + val method = getMethod(name, className = "BindContract") + val events = mutableListOf() + val observer = object : TsInterpreterObserver { + override fun onUnknownCall(event: TsUnknownCallEvent) { + events += event + } + } + val selected = if (enabled) setOf(modelId) else emptySet() + val tsOptions = TsOptions( + eraseTypeAssertions = true, + unknownCallModelSelection = TsUnknownCallModelSelection.Only(selected), + unknownCallFallback = TsResidualCallPolicy.STOP_PATH, + ) + + val run = TsMachine(scene = scene, options = options, tsOptions = tsOptions, observer = observer).use { machine -> + machine.analyzeWithMetadata(methods = listOf(method)) + } + + assertFalse(run.engineFailed, name) + val values = run.states.map { state -> + when (val result = TsTestResolver().resolve(method, state).returnValue) { + is TsTestValue.TsNumber -> result.number + is TsTestValue.TsBoolean -> result.value + else -> error("Unexpected $name result: $result") + } + }.toSet() + val applied = events.any { (it.decision as? TsUnknownCallDecision.ModelApplied)?.modelId == modelId } + val stopped = events.any { it.callee.name == "bind" && it.outcome == TsUnknownCallOutcome.PATH_STOPPED } + return BindingRun(values, applied, stopped) + } + + private data class BindingRun(val values: Set, val applied: Boolean, val stopped: Boolean) + + private companion object { + const val modelId = "ts.function.bind" + val expectedReturns = linkedMapOf( + "prefixAndThis" to 30.0, + "secondBindKeepsReceiver" to 123.0, + "lexicalThis" to 34.0, + "distinctIdentity" to true, + "userMethod" to 201.0, + ) + } +} diff --git a/usvm-ts/experiments/function-bind/experiment.patch b/usvm-ts/experiments/function-bind/experiment.patch new file mode 100644 index 0000000000..f83bb27c13 --- /dev/null +++ b/usvm-ts/experiments/function-bind/experiment.patch @@ -0,0 +1,204 @@ +--- a/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsFunction.kt ++++ b/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsFunction.kt +@@ -1,10 +1,23 @@ + package org.usvm.machine.interpreter + + import org.jacodb.ets.model.EtsMethod ++import org.usvm.UExpr + import org.usvm.UHeapRef + + class TsFunction( + val method: EtsMethod, + val thisInstance: UHeapRef?, + val closure: UHeapRef?, +-) ++) { ++ internal var boundArguments: List>? = null ++ private set ++ ++ internal constructor( ++ method: EtsMethod, ++ thisInstance: UHeapRef, ++ closure: UHeapRef?, ++ boundArguments: List>, ++ ) : this(method, thisInstance, closure) { ++ this.boundArguments = boundArguments.toList() ++ } ++} +--- a/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsInterpreter.kt ++++ b/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsInterpreter.kt +@@ -44,6 +44,7 @@ + import org.usvm.forkblacklists.UForkBlackList + import org.usvm.isAllocatedConcreteHeapRef + import org.usvm.machine.TsConcreteMethodCallStmt ++import org.usvm.machine.call.intrinsic.argumentsWithBoundPrefix + import org.usvm.machine.TsContext + import org.usvm.machine.TsEntryPointGuardResultStmt + import org.usvm.machine.TsGraph +@@ -466,7 +467,8 @@ + registerCallee(stmt.returnSite, callee.cfg) + + val args = mutableListOf>() +- val numActual = stmt.args.size ++ val actualArguments = argumentsWithBoundPrefix(stmt) ++ val numActual = actualArguments.size + val numFormal = callee.parameters.size + + args += stmt.instance +@@ -490,7 +492,7 @@ + + // first n-1 args are normal + val numNormal = numFormal - 1 +- args += stmt.args.take(numNormal) ++ args += actualArguments.take(numNormal) + + // fill missing normal args with undefined + repeat(numNormal - numActual) { +@@ -499,7 +501,7 @@ + + // wrap rest args in array + val content = mutableListOf() +- for (argument in stmt.args.drop(numNormal)) { ++ for (argument in actualArguments.drop(numNormal)) { + val value = with(ctx) { argument.toFakeObject(scope) } ?: return@doWithState + content += value + } +@@ -523,7 +525,7 @@ + // normal call + + // ignore extra args +- args += stmt.args.take(numFormal) ++ args += actualArguments.take(numFormal) + + // fill missing args with undefined + repeat(numFormal - numActual) { +--- a/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsBuiltInUnknownCallModels.kt ++++ b/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsBuiltInUnknownCallModels.kt +@@ -2,6 +2,7 @@ + + import org.usvm.machine.call.intrinsic.TsBuiltInUnknownCallModel + import org.usvm.machine.call.intrinsic.TsBuiltInUnknownCallModelFamily ++import org.usvm.machine.call.intrinsic.TsFunctionBindModel + + /** Discovers built-in model objects from the sealed hierarchy. */ + object TsBuiltInUnknownCallModels { +@@ -18,7 +19,7 @@ + family.models + } + +- individualModels + modelFamilies ++ individualModels + modelFamilies + TsFunctionBindModel + } + private val allModels by lazy { TsUnknownCallModelCatalog(models) } + +--- /dev/null ++++ b/usvm-ts/src/main/kotlin/org/usvm/machine/call/intrinsic/TsFunctionBindModel.kt +@@ -0,0 +1,108 @@ ++package org.usvm.machine.call.intrinsic ++ ++import io.ksmt.utils.asExpr ++import org.jacodb.ets.model.EtsArrayType ++import org.jacodb.ets.model.EtsClassType ++import org.jacodb.ets.model.EtsFileSignature ++import org.jacodb.ets.model.EtsFunctionType ++import org.jacodb.ets.model.EtsLexicalEnvType ++import org.usvm.UConcreteHeapRef ++import org.usvm.UExpr ++import org.usvm.api.typeStreamOf ++import org.usvm.machine.TsConcreteMethodCallStmt ++import org.usvm.machine.call.TsUnknownCall ++import org.usvm.machine.call.TsUnknownCallModel ++import org.usvm.machine.call.TsUnknownCallModelCompletion ++import org.usvm.machine.call.TsUnknownCallModelExecution ++import org.usvm.machine.call.TsUnknownCallModelSuccessor ++import org.usvm.machine.call.TsUnknownCallTarget ++import org.usvm.machine.interpreter.TsFunction ++import org.usvm.machine.runtimeFunctionType ++import org.usvm.machine.state.TsState ++import org.usvm.types.singleOrNull ++ ++internal object TsFunctionBindModel : TsUnknownCallModel { ++ override val id: String = "ts.function.bind" ++ override val target = TsUnknownCallTarget(methodName = "bind") ++ ++ override fun apply(state: TsState, call: TsUnknownCall): TsUnknownCallModelExecution? = with(state) { ++ val owner = call.callee.enclosingClass ++ if (java.lang.Boolean.getBoolean("usvm.bind.diagnostic")) { ++ val pointer = call.receiver?.resolved as? UConcreteHeapRef ++ val function = pointer?.let { associatedFunction[it] } ++ val typed = call.receiver?.source?.type as? EtsFunctionType ++ val first = call.arguments.firstOrNull()?.resolved as? UConcreteHeapRef ++ System.err.println("Bind diagnostic owner=$owner sdk=${ctx.scene.sdkClasses.any { it.signature == owner }} " + ++ "fn=${function?.method?.signature} sourceKind=${call.receiver?.source?.type?.javaClass?.simpleName} " + ++ "type=${typed?.signature} isArrow=${typed?.isArrow} isStrict=${function?.method?.isStrictMode} " + ++ "project=${function?.method?.enclosingClass in ctx.scene.projectClasses} " + ++ "firstKind=${first?.let { memory.typeStreamOf(it).singleOrNull() }} " + ++ "resolvedReceiver=${call.receiver?.resolved?.javaClass?.simpleName} argSorts=${call.arguments.map { it.resolved?.sort }}") ++ } ++ val functionOwner = owner.name in setOf("", "Function", "CallableFunction") ++ val nativeOwner = owner.file == EtsFileSignature.UNKNOWN || ctx.scene.sdkClasses.any { it.signature == owner } ++ if (!functionOwner || !nativeOwner) return null ++ ++ val receiver = call.receiver ?: return null ++ val pointer = receiver.resolved as? UConcreteHeapRef ?: return null ++ val function = associatedFunction[pointer] ?: return null ++ val projectOwner = function.method.enclosingClass in ctx.scene.projectClasses ++ val hasOwnBind = trackedObjectProperties.any { it.instance == pointer && it.name == "bind" } ++ if (!projectOwner || hasOwnBind) return null ++ ++ val arguments = mutableListOf>() ++ for (argument in call.arguments) { ++ val resolved = argument.resolved ?: return null ++ arguments += resolved ++ } ++ ++ val boundArguments = function.boundArguments ++ val thisInstance = if (boundArguments != null) { ++ requireNotNull(function.thisInstance) ++ } else { ++ val type = receiver.source.type as? EtsFunctionType ?: return null ++ val environment = function.method.parameters.firstOrNull()?.type as? EtsLexicalEnvType ++ val capturesThis = function.closure != null && environment?.closures?.any { it.name == "this" } == true ++ val namedOrdinaryTarget = !type.isArrow && type.signature.name.isNotBlank() && ++ type.signature.name == function.method.name ++ val explicitArrowTarget = type.isArrow && type.signature == function.method.signature ++ if (!capturesThis && !namedOrdinaryTarget && !explicitArrowTarget) return null ++ ++ if (capturesThis || explicitArrowTarget) { ++ function.thisInstance ?: ctx.mkUndefinedValue() ++ } else { ++ val passedReceiver = arguments.firstOrNull() ?: ctx.mkUndefinedValue() ++ if (passedReceiver.sort != ctx.addressSort) return null ++ val reference = passedReceiver.asExpr(ctx.addressSort) ++ val nullish = reference == ctx.mkUndefinedValue() || reference == ctx.mkTsNullValue() ++ if (nullish && function.method.isStrictMode != true) return null ++ if (!nullish) { ++ if (reference !is UConcreteHeapRef) return null ++ val valueType = memory.typeStreamOf(reference).singleOrNull() ++ if (valueType !is EtsClassType && valueType !is EtsArrayType) return null ++ } ++ reference ++ } ++ } ++ ++ val prefix = boundArguments.orEmpty() + arguments.drop(1) ++ val completion = TsUnknownCallModelCompletion.Normal { ++ val reference = memory.allocConcrete(ctx.scene.runtimeFunctionType()) ++ val bound = TsFunction(function.method, thisInstance, function.closure, prefix) ++ associatedFunction = associatedFunction.put(reference, bound, ownership) ++ reference ++ } ++ val successor = TsUnknownCallModelSuccessor(guard = ctx.trueExpr, completion = completion) ++ TsUnknownCallModelExecution(successors = listOf(successor)) ++ } ++} ++ ++internal fun TsState.argumentsWithBoundPrefix(call: TsConcreteMethodCallStmt): List> { ++ val pointer = call.resolvedReceiver as? UConcreteHeapRef ?: return call.args ++ val function = associatedFunction[pointer] ?: return call.args ++ if (function.method != call.callee) return call.args ++ ++ val prefix = function.boundArguments ?: return call.args ++ val prefixOffset = if (function.closure != null) 1 else 0 ++ return call.args.take(prefixOffset) + prefix + call.args.drop(prefixOffset) ++} diff --git a/usvm-ts/experiments/function-bind/run.py b/usvm-ts/experiments/function-bind/run.py new file mode 100644 index 0000000000..ec463eb958 --- /dev/null +++ b/usvm-ts/experiments/function-bind/run.py @@ -0,0 +1,39 @@ +"""Run a bind prototype against a temporary copy of the public Calls checkout.""" + +import argparse +from pathlib import Path +import shutil +import subprocess +from tempfile import TemporaryDirectory + + +HERE = Path(__file__).resolve().parent +BASE = "7e74b8061fd86d69b7bc22d8a5e2b535e6e2c6ad" +TEST = "org.usvm.machine.call.ExperimentalFunctionBindTest" + + +def main(gradle_arguments): + repository = Path(subprocess.check_output( + ["git", "rev-parse", "--show-toplevel"], cwd=HERE, text=True, + ).strip()) + patch = HERE / "experiment.patch" + with TemporaryDirectory(prefix="usvm-bind-experiment-") as temporary: + checkout = Path(temporary) / "usvm" + subprocess.run(["git", "clone", "--shared", "--no-checkout", repository, checkout], check=True) + subprocess.run(["git", "switch", "--detach", BASE], cwd=checkout, check=True) + subprocess.run(["git", "apply", "--check", patch], cwd=checkout, check=True) + subprocess.run(["git", "apply", patch], cwd=checkout, check=True) + + kotlin_tests = checkout / "usvm-ts/src/test/kotlin/org/usvm/machine/call" + resources = checkout / "usvm-ts/src/test/resources/models/function-bind-experiment" + resources.mkdir(parents=True) + shutil.copyfile(HERE / "ExperimentalFunctionBindTest.kt", kotlin_tests / "ExperimentalFunctionBindTest.kt") + shutil.copyfile(HERE / "BindContract.ts", resources / "BindContract.ts") + subprocess.run(["./gradlew", ":usvm-ts:test", "--tests", TEST, *gradle_arguments], cwd=checkout, check=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("gradle_arguments", nargs=argparse.REMAINDER, help="Gradle arguments after --") + arguments = parser.parse_args().gradle_arguments + main(arguments[1:] if arguments[:1] == ["--"] else arguments)