From 97a4be7593fbfc7200dacf779110a5bf3537265c Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 20:14:17 +0100 Subject: [PATCH 1/2] Record complete fresh input method transcripts per path --- .../usvm/machine/call/TsFreshResidualCall.kt | 11 ++ .../call/TsUnknownCallModelDispatcher.kt | 27 +++- .../kotlin/org/usvm/machine/state/TsState.kt | 31 +++++ .../org/usvm/util/TsResolvedResidualInputs.kt | 17 +++ .../kotlin/org/usvm/util/TsTestResolver.kt | 124 +++++++++++++----- .../call/TsFreshInputCallTranscriptTest.kt | 82 ++++++++++++ .../models/TsFreshInputCallTranscript.ts | 9 ++ 7 files changed, 265 insertions(+), 36 deletions(-) create mode 100644 usvm-ts/src/main/kotlin/org/usvm/machine/call/TsFreshResidualCall.kt create mode 100644 usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt create mode 100644 usvm-ts/src/test/kotlin/org/usvm/machine/call/TsFreshInputCallTranscriptTest.kt create mode 100644 usvm-ts/src/test/resources/models/TsFreshInputCallTranscript.ts diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsFreshResidualCall.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsFreshResidualCall.kt new file mode 100644 index 0000000000..34352e096d --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsFreshResidualCall.kt @@ -0,0 +1,11 @@ +package org.usvm.machine.call + +import org.usvm.UExpr + +/** Symbolic values for a missing input method, to be concretized together at a terminal path. */ +internal data class TsFreshResidualCall( + val name: String, + val receiver: UExpr<*>, + val arguments: List>, + val result: UExpr<*>, +) diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsUnknownCallModelDispatcher.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsUnknownCallModelDispatcher.kt index 1dce219a9e..6888b195a4 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsUnknownCallModelDispatcher.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/call/TsUnknownCallModelDispatcher.kt @@ -1,9 +1,14 @@ package org.usvm.machine.call import mu.KotlinLogging +import org.jacodb.ets.model.EtsClassSignature +import org.jacodb.ets.model.EtsInstanceCallExpr +import org.jacodb.ets.utils.callExpr import org.usvm.UExpr import org.usvm.api.makeFreshUnknownCallResult import org.usvm.api.setMockMethodCallResult +import org.usvm.isAllocatedConcreteHeapRef +import org.usvm.isStaticHeapRef import org.usvm.machine.TsInterpreterObserver import org.usvm.machine.call.intrinsic.TsDateEtsIrModelFamily import org.usvm.machine.expr.invalidateCollectionAfterResidual @@ -12,6 +17,7 @@ import org.usvm.machine.state.TsMethodResult import org.usvm.machine.state.TsState import org.usvm.machine.state.newStmt import org.usvm.machine.types.mkFakeValue +import org.usvm.uctx private val logger = KotlinLogging.logger {} @@ -79,6 +85,7 @@ class TsModelUnknownCallDispatcher( scope.doWithState { invalidateCollectionAfterResidual(call) setMockMethodCallResult(call.callee, result) + recordFreshResidualCall { call.inputMethodWitness(result) } newStmt(call.callSite) } } @@ -136,8 +143,10 @@ class TsModelUnknownCallDispatcher( if (residualGuard != null && residualPolicy == TsResidualCallPolicy.FRESH_SYMBOLIC_RETURN) { guardedStateChanges += residualGuard to { + val result = requireNotNull(freshResidualResult) invalidateCollectionAfterResidual(call) - setMockMethodCallResult(call.callee, requireNotNull(freshResidualResult)) + setMockMethodCallResult(call.callee, result) + recordFreshResidualCall { call.inputMethodWitness(result) } newStmt(call.callSite) freshResidualApplied = true } @@ -236,6 +245,22 @@ class TsModelUnknownCallDispatcher( ) } +/** A replay double can supply a missing input method with a string key. */ +private fun TsUnknownCall.inputMethodWitness(result: UExpr<*>): TsFreshResidualCall? { + val call = callSite.callExpr as? EtsInstanceCallExpr + val isUnboundMethod = failureReason == TsUnknownCallFailureReason.VIRTUAL_METHOD_NOT_FOUND && + callee.enclosingClass == EtsClassSignature.UNKNOWN && call?.wellKnownSymbol == null && callee.name.isNotBlank() + if (!isUnboundMethod) return null + + val receiver = receiver?.resolved ?: return null + val canReferToInput = receiver.sort == receiver.uctx.addressSort && + !isAllocatedConcreteHeapRef(receiver) && !isStaticHeapRef(receiver) + if (!canReferToInput) return null + + val inputs = arguments.map { argument -> argument.resolved ?: return null } + return TsFreshResidualCall(name = callee.name, receiver = receiver, arguments = inputs, result = result) +} + private fun TsInterpreterObserver.onPathStoppedSafely(state: TsState, reason: String) { runCatching { onPathStopped(state = state, reason = reason) } .onFailure { error -> logger.warn(error) { "Unknown-call observer failed while recording a stopped path" } } diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/state/TsState.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/state/TsState.kt index 72fd52a611..069005da68 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/state/TsState.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/state/TsState.kt @@ -29,6 +29,7 @@ import org.usvm.constraints.UPathConstraints import org.usvm.machine.TsContext import org.usvm.machine.TsInputPropertyPresence import org.usvm.machine.TsSizeSort +import org.usvm.machine.call.TsFreshResidualCall import org.usvm.machine.expr.TrackedObjectProperty import org.usvm.machine.expr.TsArrayIterator import org.usvm.machine.expr.TsCapturedInstanceCall @@ -157,10 +158,35 @@ class TsState( internal var collectionOriginalReceivers: Map = emptyMap() internal var modeledCollections: Map = emptyMap() + + internal var recordsFreshInputMethods = false + private set + + /** Number of opaque returns used by this path while recording is enabled. */ + var freshResidualCallCount: Int = 0 + private set + + internal var freshResidualCalls: List = emptyList() + private set + internal var initialEnvironmentFailure: String? = null internal var initialEnvironmentHeaps: Map = emptyMap() internal var initialEnvironmentSlots: Map, TsInitialEnvironmentSlot> = emptyMap() + /** Enables per-path recording for clients that replay missing input methods as test doubles. */ + fun recordFreshInputMethodsForReplay() { + recordsFreshInputMethods = true + } + + internal fun recordFreshResidualCall(witness: () -> TsFreshResidualCall?) { + if (!recordsFreshInputMethods) return + + freshResidualCallCount++ + if (freshResidualCalls.size >= MAX_RECORDED_FRESH_CALLS) return + + witness()?.let { freshResidualCalls += it } + } + internal fun captureInitialEnvironmentMemory(): UReadOnlyMemory { val liveOwnership = MutabilityOwnership() val snapshotOwnership = MutabilityOwnership() @@ -432,6 +458,9 @@ class TsState( cloned.inputCollectionReferences = inputCollectionReferences cloned.collectionOriginalReceivers = collectionOriginalReceivers cloned.promiseExecutorFunctions = promiseExecutorFunctions + cloned.recordsFreshInputMethods = recordsFreshInputMethods + cloned.freshResidualCallCount = freshResidualCallCount + cloned.freshResidualCalls = freshResidualCalls cloned.initialEnvironmentFailure = initialEnvironmentFailure cloned.initialEnvironmentHeaps = initialEnvironmentHeaps cloned.initialEnvironmentSlots = initialEnvironmentSlots @@ -442,6 +471,8 @@ class TsState( get() = methodResult is TsMethodResult.TsException } +private const val MAX_RECORDED_FRESH_CALLS = 16 + /** Snapshot of the regions that establish dense Calls input-array contents. */ data class TsDenseInputArray( val type: EtsArrayType, diff --git a/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt b/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt new file mode 100644 index 0000000000..be8c61efd6 --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt @@ -0,0 +1,17 @@ +package org.usvm.util + +import org.usvm.api.TsParametersState +import org.usvm.api.TsTestValue + +/** Resolved input values share identities with objects referenced by residual calls. */ +data class TsResolvedResidualInputs( + val inputs: TsParametersState, + val calls: Result>, +) + +data class TsResolvedInputMethodCall( + val methodName: String, + val receiver: TsTestValue.TsClass, + val arguments: List, + val returnedValue: TsTestValue, +) diff --git a/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt b/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt index 77a918f42c..c11074122e 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt @@ -88,16 +88,9 @@ class TsTestResolver( resolveEnvironment: Boolean = true, ): TsParametersState { prepareForResolve(state) - val scope = MemoryScope( - ctx = state.ctx, - model = state.models.first(), - finalStateMemory = state.memory, + val scope = memoryScope( method = method, - resolvedLValuesToFakeObjects = resolvedLValuesToFakeObjects, - maxStringLength = state.maxStringLength, - stringLengthBounds = state.boundedStringBackingRefs, - propertyState = state, - onClassResolved = onClassResolved, + state = state, inputValues = inputValues, receiverValue = receiverValue, ) @@ -108,37 +101,65 @@ class TsTestResolver( } } + /** Resolves a complete residual trace with the same model and identity cache as the original inputs. */ + fun resolveInputsWithResidualCalls( + state: TsState, + inputValues: List>, + receiverValue: UExpr<*>, + resolveEnvironment: Boolean = true, + ): TsResolvedResidualInputs { + prepareForResolve(state) + val method = state.entrypoint + val scope = memoryScope(method = method, state = state, inputValues = inputValues, receiverValue = receiverValue) + val hasReceiver = !method.isStatic && method.name != "constructor" + val inputs = scope.withMode(ResolveMode.MODEL) { + resolveState(includeReceiver = hasReceiver, resolveEnvironment = resolveEnvironment) + } + val calls = runCatching { + check(state.recordsFreshInputMethods) { "Input method recording was not enabled for the entry" } + check(state.freshResidualCallCount == state.freshResidualCalls.size) { + "Only ${state.freshResidualCalls.size} of ${state.freshResidualCallCount} fresh calls can supply input methods" + } + scope.withMode(ResolveMode.CURRENT) { + state.freshResidualCalls.map { call -> + val receiver = resolveInputMethodReceiver(call.receiver, call.name) + TsResolvedInputMethodCall( + methodName = call.name, + receiver = receiver, + arguments = call.arguments.map(::resolveExpr), + returnedValue = resolveExpr(call.result), + ) + } + } + } + return TsResolvedResidualInputs(inputs = inputs, calls = calls) + } + private val resolvedLValuesToFakeObjects: MutableList, UConcreteHeapRef>> = mutableListOf() - /** [resolveEnvironment] opts into complete touched source data bindings and explicit unsupported failures. */ - fun resolve(method: EtsMethod, state: TsState, resolveEnvironment: Boolean = false): TsTest = with(state.ctx) { - val model = state.models.first() - val memory = state.memory + /** Resolves only a normally completed entry's return value, without resolving or snapshotting its input heap. */ + fun resolveReturnedValue(state: TsState): TsTestValue { + val result = checkNotNull(state.methodResult as? TsMethodResult.Success.RegularCall) { + "A predicted value requires a completed original entry return" + } + val completedEntry = state.callStack.isEmpty() && result.method === state.entrypoint && + state.unsupportedReason == null && state.engineFailureReason == null + check(completedEntry) { + "A predicted value requires a completed original entry return" + } prepareForResolve(state) + return memoryScope(method = state.entrypoint, state = state).withMode(ResolveMode.CURRENT) { + resolveExpr(result.value) + } + } - val beforeMemoryScope = MemoryScope( - this, - model, - memory, - method, - resolvedLValuesToFakeObjects, - state.maxStringLength, - stringLengthBounds = state.boundedStringBackingRefs, - propertyState = state, - onClassResolved = onClassResolved, - ) - val afterMemoryScope = MemoryScope( - this, - model, - memory, - method, - resolvedLValuesToFakeObjects, - state.maxStringLength, - stringLengthBounds = state.boundedStringBackingRefs, - propertyState = state, - onClassResolved = onClassResolved, - ) + /** [resolveEnvironment] opts into complete touched source data bindings and explicit unsupported failures. */ + fun resolve(method: EtsMethod, state: TsState, resolveEnvironment: Boolean = false): TsTest { + prepareForResolve(state) + + val beforeMemoryScope = memoryScope(method = method, state = state) + val afterMemoryScope = memoryScope(method = method, state = state) val result = when (val res = state.methodResult) { is TsMethodResult.NoCall -> { @@ -166,6 +187,25 @@ class TsTestResolver( return TsTest(method, before, after, result, trace = emptyList()) } + private fun memoryScope( + method: EtsMethod, + state: TsState, + inputValues: List>? = null, + receiverValue: UExpr<*>? = null, + ): MemoryScope = MemoryScope( + ctx = state.ctx, + model = state.models.first(), + finalStateMemory = state.memory, + method = method, + resolvedLValuesToFakeObjects = resolvedLValuesToFakeObjects, + maxStringLength = state.maxStringLength, + stringLengthBounds = state.boundedStringBackingRefs, + propertyState = state, + onClassResolved = onClassResolved, + inputValues = inputValues, + receiverValue = receiverValue, + ) + private fun prepareForResolve(state: TsState) { resolvedLValuesToFakeObjects.clear() state.lValuesToAllocatedFakeObjects.forEach { (lValue, fakeObject) -> @@ -297,6 +337,20 @@ open class TsTestStateResolver( private val resolvedClasses = hashMapOf() private val resolvedArrays = hashMapOf>() + internal fun resolveInputMethodReceiver(receiver: UExpr<*>, name: String): TsTestValue.TsClass = with(ctx) { + check(receiver.sort == addressSort) { "A recorded input method receiver is not an object" } + val ref = receiver.asExpr(addressSort) + val concreteRef = checkNotNull(evaluateInModel(ref) as? UConcreteHeapRef) + val original = checkNotNull(resolvedClasses[concreteRef]) { + "A recorded input method receiver is outside the original input heap" + } + + val written = model.eval(finalStateMemory.read(writtenPropertyLValue(ref, name))).isTrue + val deleted = model.eval(finalStateMemory.read(deletedFieldLValue(ref, name))).isTrue + check(!written && !deleted) { "Recorded input method '$name' was mutated in the symbolic path" } + original + } + fun resolveLValue( lValue: ULValue<*, *>, ): TsTestValue { diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/call/TsFreshInputCallTranscriptTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/call/TsFreshInputCallTranscriptTest.kt new file mode 100644 index 0000000000..225351defc --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/call/TsFreshInputCallTranscriptTest.kt @@ -0,0 +1,82 @@ +package org.usvm.machine.call + +import org.usvm.StateCollectionStrategy +import org.usvm.UExpr +import org.usvm.api.TsTestValue +import org.usvm.machine.TsMachine +import org.usvm.machine.TsOptions +import org.usvm.machine.state.TsMethodResult +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.TsResolvedResidualInputs +import org.usvm.util.TsTestResolver +import org.usvm.util.mkRegisterStackLValue +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertSame +import kotlin.test.assertTrue + +class TsFreshInputCallTranscriptTest : TsMethodTestRunner() { + override val scene = loadScene(resourcePath = "/models/TsFreshInputCallTranscript.ts") + override val tsOptions = TsOptions( + unknownCallModelSelection = TsUnknownCallModelSelection.Only(emptySet()), + unknownCallFallback = TsResidualCallPolicy.FRESH_SYMBOLIC_RETURN, + ) + + @Test + fun `forked paths record only their own calls in order with a shared receiver`() { + val entries = analyze(recordTranscript = true) + + val shortPath = entries.getValue(-1.0).first { it.calls.isSuccess } + assertEquals(expected = 1, actual = shortPath.calls.getOrThrow().size) + + val completePath = entries.getValue(23.0).first { it.calls.isSuccess } + val calls = completePath.calls.getOrThrow() + assertEquals(listOf("choose", "choose"), calls.map { it.methodName }) + val arguments = calls.map { assertIs(it.arguments.single()).number } + val returnedValues = calls.map { assertIs(it.returnedValue).number } + assertEquals(listOf(11.0, 7.0), arguments) + assertEquals(listOf(7.0, 5.0), returnedValues) + calls.forEach { assertSame(completePath.inputs.parameters.single(), it.receiver) } + } + + @Test + fun `disabled recording still resolves original inputs and does not present an empty transcript`() { + val entries = analyze(recordTranscript = false) + + val returned = entries.getValue(23.0) + assertTrue(returned.all { it.inputs.parameters.size == 1 && it.calls.isFailure }) + } + + private fun analyze(recordTranscript: Boolean): Map> { + val method = getMethod(methodName = "chooseTwice", className = "TsFreshInputCallTranscript") + val analysisOptions = options.copy(stateCollectionStrategy = StateCollectionStrategy.ALL, stopOnCoverage = 0) + lateinit var receiver: UExpr<*> + lateinit var adapter: UExpr<*> + + return TsMachine(scene = scene, options = analysisOptions, tsOptions = tsOptions).use { machine -> + val analysis = machine.analyzeWithMetadata(methods = listOf(method), configureInitialState = { _, state -> + receiver = state.memory.read(mkRegisterStackLValue(state.ctx.addressSort, idx = 0)) + val inputSort = checkNotNull(state.getSortForLocal(idx = 1)) + adapter = state.memory.read(mkRegisterStackLValue(inputSort, idx = 1)) + if (recordTranscript) state.recordFreshInputMethodsForReplay() + }) + assertFalse(analysis.engineFailed) + val resolver = TsTestResolver() + + val returns = analysis.states.filter { it.methodResult is TsMethodResult.Success.RegularCall } + val resolved = returns.map { state -> + val result = assertIs(resolver.resolveReturnedValue(state)) + val inputs = resolver.resolveInputsWithResidualCalls( + state = state, + inputValues = listOf(adapter), + receiverValue = receiver, + resolveEnvironment = false, + ) + result.number to inputs + } + resolved.groupBy(keySelector = { it.first }, valueTransform = { it.second }) + } + } +} diff --git a/usvm-ts/src/test/resources/models/TsFreshInputCallTranscript.ts b/usvm-ts/src/test/resources/models/TsFreshInputCallTranscript.ts new file mode 100644 index 0000000000..60c9bd0991 --- /dev/null +++ b/usvm-ts/src/test/resources/models/TsFreshInputCallTranscript.ts @@ -0,0 +1,9 @@ +export class TsFreshInputCallTranscript { + static chooseTwice(adapter: any): number { + const first = adapter.choose(11); + if (first !== 7) return -1; + + const second = adapter.choose(first); + return second === 5 ? 23 : -2; + } +} From 9bc150123fe9d65cf4e83a20d92ceb8155c48873 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 20:58:42 +0100 Subject: [PATCH 2/2] Document and format the input transcript API --- .../org/usvm/util/TsResolvedResidualInputs.kt | 1 + .../src/main/kotlin/org/usvm/util/TsTestResolver.kt | 13 ++++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt b/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt index be8c61efd6..62d03425f1 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt @@ -9,6 +9,7 @@ data class TsResolvedResidualInputs( val calls: Result>, ) +/** A missing method call on an original input object, resolved in the path's satisfying model. */ data class TsResolvedInputMethodCall( val methodName: String, val receiver: TsTestValue.TsClass, diff --git a/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt b/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt index c11074122e..21a3e027d8 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt @@ -110,15 +110,22 @@ class TsTestResolver( ): TsResolvedResidualInputs { prepareForResolve(state) val method = state.entrypoint - val scope = memoryScope(method = method, state = state, inputValues = inputValues, receiverValue = receiverValue) + val scope = memoryScope( + method = method, + state = state, + inputValues = inputValues, + receiverValue = receiverValue, + ) val hasReceiver = !method.isStatic && method.name != "constructor" val inputs = scope.withMode(ResolveMode.MODEL) { resolveState(includeReceiver = hasReceiver, resolveEnvironment = resolveEnvironment) } val calls = runCatching { check(state.recordsFreshInputMethods) { "Input method recording was not enabled for the entry" } - check(state.freshResidualCallCount == state.freshResidualCalls.size) { - "Only ${state.freshResidualCalls.size} of ${state.freshResidualCallCount} fresh calls can supply input methods" + val totalCount = state.freshResidualCallCount + val recordedCount = state.freshResidualCalls.size + check(totalCount == recordedCount) { + "Only $recordedCount of $totalCount fresh calls can supply input methods" } scope.withMode(ResolveMode.CURRENT) { state.freshResidualCalls.map { call ->