Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<UExpr<*>>,
val result: UExpr<*>,
)
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 {}

Expand Down Expand Up @@ -79,6 +85,7 @@ class TsModelUnknownCallDispatcher(
scope.doWithState {
invalidateCollectionAfterResidual(call)
setMockMethodCallResult(call.callee, result)
recordFreshResidualCall { call.inputMethodWitness(result) }
newStmt(call.callSite)
}
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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" } }
Expand Down
31 changes: 31 additions & 0 deletions usvm-ts/src/main/kotlin/org/usvm/machine/state/TsState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -157,10 +158,35 @@ class TsState(
internal var collectionOriginalReceivers: Map<UConcreteHeapRef, UHeapRef> = emptyMap()

internal var modeledCollections: Map<UConcreteHeapRef, TsModeledCollection> = 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<TsFreshResidualCall> = emptyList()
private set

internal var initialEnvironmentFailure: String? = null
internal var initialEnvironmentHeaps: Map<EtsClass, TsInitialEnvironmentHeap> = emptyMap()
internal var initialEnvironmentSlots: Map<Pair<EtsClass, String>, 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<EtsType> {
val liveOwnership = MutabilityOwnership()
val snapshotOwnership = MutabilityOwnership()
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
18 changes: 18 additions & 0 deletions usvm-ts/src/main/kotlin/org/usvm/util/TsResolvedResidualInputs.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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<List<TsResolvedInputMethodCall>>,
)

/** A missing method call on an original input object, resolved in the path's satisfying model. */
data class TsResolvedInputMethodCall(
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
val methodName: String,
val receiver: TsTestValue.TsClass,
val arguments: List<TsTestValue>,
val returnedValue: TsTestValue,
)
131 changes: 96 additions & 35 deletions usvm-ts/src/main/kotlin/org/usvm/util/TsTestResolver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -108,37 +101,72 @@ class TsTestResolver(
}
}

/** Resolves a complete residual trace with the same model and identity cache as the original inputs. */
fun resolveInputsWithResidualCalls(
state: TsState,
inputValues: List<UExpr<*>>,
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" }
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 ->
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<Pair<ULValue<*, *>, 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 -> {
Expand Down Expand Up @@ -166,6 +194,25 @@ class TsTestResolver(
return TsTest(method, before, after, result, trace = emptyList())
}

private fun memoryScope(
method: EtsMethod,
state: TsState,
inputValues: List<UExpr<*>>? = 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) ->
Expand Down Expand Up @@ -297,6 +344,20 @@ open class TsTestStateResolver(
private val resolvedClasses = hashMapOf<UConcreteHeapRef, TsTestValue.TsClass>()
private val resolvedArrays = hashMapOf<UConcreteHeapRef, TsTestValue.TsArray<TsTestValue>>()

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 {
Expand Down
Loading
Loading