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
Expand Up @@ -6,6 +6,7 @@ import org.jacodb.ets.model.EtsFileSignature
import org.jacodb.ets.model.EtsMethod
import org.usvm.UExpr
import org.usvm.api.TsTestValue
import org.usvm.machine.TsReturnedCallableScenario
import org.usvm.machine.state.TsState
import org.usvm.machine.state.lastStmt
import org.usvm.util.TsTestResolver
Expand Down Expand Up @@ -43,6 +44,27 @@ internal data class CallsClassInputCandidate(
val environmentComplete: Boolean,
val environmentLimitations: List<String>,
val nativeReplayValidated: Boolean = false,
val returnedCallableScenario: CallsReturnedCallableScenario? = null,
val predictedReturn: CallsConcreteReturnedValue? = null,
val returnExtractionLimitation: String? = null,
val inputMethodCalls: List<CallsConcreteInputMethodCall> = emptyList(),
val inputMethodExtractionLimitation: String? = null,
)

/** Replays the factory and its detached result using three consecutive slices of the input heap roots. */
@Serializable
internal data class CallsReturnedCallableScenario(
val sourceFile: String,
val className: String,
val factoryMethod: String,
val factorySignature: String,
val factoryIsStatic: Boolean,
val constructorArgumentCount: Int,
val factoryArgumentCount: Int,
val callableArgumentCount: Int,
val invocationReached: Boolean,
val callableTargetMethod: String? = null,
val freshResidualCallCount: Int,
)

@Serializable
Expand Down Expand Up @@ -70,7 +92,11 @@ internal data class CallsClassInputJournalMetadata(
)

/** Reuses the normal before-test resolver; materialization failures remain explicit journal records. */
internal class CallsClassInputCandidates(output: Path, private val profile: CallsExperimentProfile) {
internal class CallsClassInputCandidates(
output: Path,
private val profile: CallsExperimentProfile,
private val returnedCallableScenarios: Map<EtsMethod, TsReturnedCallableScenario> = emptyMap(),
) {
private val candidates = InputJournal(path = output.resolve("input-candidates.jsonl"))
private val failures = InputJournal(path = output.resolve("input-extraction-failures.jsonl"))
private val bindings = IdentityHashMap<EtsMethod, Result<EntryBindings>>()
Expand Down Expand Up @@ -100,41 +126,7 @@ internal class CallsClassInputCandidates(output: Path, private val profile: Call
val currentMethod = location.method.signature
val currentSourceFile = currentMethod.enclosingClass.file.toString()
val extracted = runCatching {
val method = state.entrypoint
val environment = resolveOriginalEnvironment(state = state)
val suspended = outcome != "RETURNED" && outcome != "THREW"
val reason = if (suspended) state.engineFailureReason ?: state.unsupportedReason ?: outcome else null
CallsClassInputCandidate(
stateId = state.id.toString(),
entryMethod = method.signature.toString(),
currentMethod = currentMethod.toString(),
statementIndex = location.index,
className = method.signature.enclosingClass.name,
methodName = method.name,
invocationKind = when {
method.name == "constructor" -> CallsClassInvocationKind.CONSTRUCTOR
method.isStatic -> CallsClassInvocationKind.STATIC_METHOD
else -> CallsClassInvocationKind.INSTANCE_METHOD
},
outcome = outcome,
profile = profile,
origin = if (suspended) {
CallsCoverageCandidateOrigin.SUSPENDED
} else {
CallsCoverageCandidateOrigin.TERMINATED
},
completion = when (outcome) {
"RETURNED" -> CallsCoverageCompletion.RETURNED
"THREW" -> CallsCoverageCompletion.THREW
else -> null
},
suspensionReason = reason,
suspendedAtMachineStop = suspended && stopped,
emittedAtMillis = emittedAtMillis,
inputs = environment.heap,
environmentComplete = environment.limitation == null,
environmentLimitations = listOfNotNull(environment.limitation),
)
resolveCandidate(state = state, outcome = outcome, emittedAtMillis = emittedAtMillis, stopped = stopped)
}
extractionElapsedNanos += started.elapsedNow().inWholeNanoseconds

Expand Down Expand Up @@ -180,42 +172,156 @@ internal class CallsClassInputCandidates(output: Path, private val profile: Call
}
}

private fun resolveOriginalEnvironment(state: TsState): ResolvedEnvironment {
private fun resolveCandidate(
state: TsState,
outcome: String,
emittedAtMillis: Long,
stopped: Boolean,
): CallsClassInputCandidate {
val location = state.lastStmt.location
val currentMethod = location.method.signature
val method = state.entrypoint
val returnedCallablePlan = returnedCallableScenarios[method]
val enteredCallable = returnedCallablePlan?.enteredCallable(state)
val resolveMethodCalls = enteredCallable != null && state.freshResidualCallCount > 0
val environment = resolveOriginalEnvironment(state = state, resolveMethodCalls = resolveMethodCalls)
val inputs = environment.inputs
val suspended = outcome != "RETURNED" && outcome != "THREW"
val reason = if (suspended) state.engineFailureReason ?: state.unsupportedReason ?: outcome else null
val returnedCallable = returnedCallablePlan?.let { scenario ->
describeReturnedCallable(scenario, enteredCallable, state, inputHeap = inputs.heap)
}
val predictedReturn = if (outcome == "RETURNED" && enteredCallable != null) {
runCatching { resolveReturnedValue(state) }
} else {
null
}
val resultFailure = predictedReturn?.exceptionOrNull()
val methodCallFailure = inputs.methodCalls?.exceptionOrNull()
return CallsClassInputCandidate(
stateId = state.id.toString(),
entryMethod = method.signature.toString(),
currentMethod = currentMethod.toString(),
statementIndex = location.index,
className = method.signature.enclosingClass.name,
methodName = method.name,
invocationKind = when {
method.name == "constructor" -> CallsClassInvocationKind.CONSTRUCTOR
method.isStatic -> CallsClassInvocationKind.STATIC_METHOD
else -> CallsClassInvocationKind.INSTANCE_METHOD
},
outcome = outcome,
profile = profile,
origin = if (suspended) {
CallsCoverageCandidateOrigin.SUSPENDED
} else {
CallsCoverageCandidateOrigin.TERMINATED
},
completion = when (outcome) {
"RETURNED" -> CallsCoverageCompletion.RETURNED
"THREW" -> CallsCoverageCompletion.THREW
else -> null
},
suspensionReason = reason,
suspendedAtMachineStop = suspended && stopped,
emittedAtMillis = emittedAtMillis,
inputs = inputs.heap,
environmentComplete = environment.limitation == null,
environmentLimitations = listOfNotNull(environment.limitation),
returnedCallableScenario = returnedCallable,
predictedReturn = predictedReturn?.getOrNull(),
returnExtractionLimitation = resultFailure?.let { "${it::class.java.name}: ${it.message}" },
inputMethodCalls = inputs.methodCalls?.getOrNull().orEmpty(),
inputMethodExtractionLimitation = methodCallFailure?.let { "${it::class.java.name}: ${it.message}" },
)
}

private fun describeReturnedCallable(
scenario: TsReturnedCallableScenario,
enteredCallable: EtsMethod?,
state: TsState,
inputHeap: CallsConcreteHeap,
): CallsReturnedCallableScenario {
val argumentCount = scenario.constructorArgumentCount + scenario.factoryArgumentCount +
scenario.callableArgumentCount
check(inputHeap.receiver == null && inputHeap.arguments.size == argumentCount) {
"The returned-callable inputs do not match the generated wrapper's argument groups"
}

val factory = scenario.factory
val owner = factory.signature.enclosingClass
return CallsReturnedCallableScenario(
sourceFile = owner.file.fileName,
className = owner.name,
factoryMethod = factory.name,
factorySignature = factory.signature.toString(),
factoryIsStatic = factory.isStatic,
constructorArgumentCount = scenario.constructorArgumentCount,
factoryArgumentCount = scenario.factoryArgumentCount,
callableArgumentCount = scenario.callableArgumentCount,
invocationReached = enteredCallable != null,
callableTargetMethod = enteredCallable?.signature?.toString(),
freshResidualCallCount = state.freshResidualCallCount,
)
}

private fun resolveReturnedValue(state: TsState): CallsConcreteReturnedValue {
val prototypes = IdentityHashMap<TsTestValue.TsClass, CallsConcretePrototype>()
val result = createResolver(prototypes).resolveReturnedValue(state)
return concreteCallsReturnedValue(value = result, prototypes = prototypes)
}

private fun resolveOriginalEnvironment(state: TsState, resolveMethodCalls: Boolean): ResolvedEnvironment {
val method = state.entrypoint
val binding = checkNotNull(bindings[method]) { "Missing original entry bindings" }
val initial = binding.getOrThrow()
val prototypes = IdentityHashMap<TsTestValue.TsClass, CallsConcretePrototype>()
val resolver = TsTestResolver(onClassResolved = { value, owner ->
val builtinObject = owner.name == "Object" && owner.signature.file == EtsFileSignature.UNKNOWN
prototypes[value] = CallsConcretePrototype(
signature = owner.signature,
ordinaryObject = owner.category == EtsClassCategory.OBJECT || builtinObject,
)
})
val resolver = createResolver(prototypes)

var environmentFailure: String? = null
val inputs = try {
resolver.resolveInputs(
fun resolve(includeEnvironment: Boolean): CallsConcreteInputs {
if (resolveMethodCalls) {
val resolved = resolver.resolveInputsWithResidualCalls(
state = state,
inputValues = initial.parameters,
receiverValue = initial.receiver,
resolveEnvironment = includeEnvironment,
)
return concreteCallsInputs(
inputs = resolved.inputs,
prototypes = prototypes,
methodCalls = resolved.calls,
)
}

val inputs = resolver.resolveInputs(
method = method,
state = state,
inputValues = initial.parameters,
receiverValue = initial.receiver,
resolveEnvironment = includeEnvironment,
)
return concreteCallsInputs(inputs, prototypes)
}

return try {
ResolvedEnvironment(inputs = resolve(includeEnvironment = true), limitation = null)
} catch (failure: TsUnsupportedEnvironmentWitnessException) {
environmentFailure = "${failure::class.java.name}: ${failure.message}"
resolver.resolveInputs(
method = method,
state = state,
inputValues = initial.parameters,
receiverValue = initial.receiver,
resolveEnvironment = false,
ResolvedEnvironment(
inputs = resolve(includeEnvironment = false),
limitation = "${failure::class.java.name}: ${failure.message}",
)
}

val heap = concreteCallsInputHeap(inputs = inputs, prototypes = prototypes)
return ResolvedEnvironment(heap = heap, limitation = environmentFailure)
}

private fun createResolver(prototypes: MutableMap<TsTestValue.TsClass, CallsConcretePrototype>): TsTestResolver =
TsTestResolver(onClassResolved = { value, owner ->
val builtinObject = owner.name == "Object" && owner.signature.file == EtsFileSignature.UNKNOWN
prototypes[value] = CallsConcretePrototype(
signature = owner.signature,
ordinaryObject = owner.category == EtsClassCategory.OBJECT || builtinObject,
)
})

fun checkpoint() {
candidates.flush()
failures.flush()
Expand All @@ -229,7 +335,7 @@ internal class CallsClassInputCandidates(output: Path, private val profile: Call

private data class EntryBindings(val receiver: UExpr<*>, val parameters: List<UExpr<*>>)

private data class ResolvedEnvironment(val heap: CallsConcreteHeap, val limitation: String?)
private data class ResolvedEnvironment(val inputs: CallsConcreteInputs, val limitation: String?)
}

private class InputJournal(private val path: Path) {
Expand All @@ -254,9 +360,7 @@ private class InputJournal(private val path: Path) {
digest.update(buffer, 0, count)
}
}
val sha256 = digest.digest().joinToString(separator = "") { byte ->
"%02x".format(byte.toInt() and UNSIGNED_BYTE_MASK)
}
val sha256 = formatCallsDigest(digest.digest())
return CallsClassInputJournalMetadata(
path = path.fileName.toString(),
records = records,
Expand All @@ -266,5 +370,3 @@ private class InputJournal(private val path: Path) {
)
}
}

private const val UNSIGNED_BYTE_MASK = 0xff
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import org.usvm.util.mkFieldLValue
import org.usvm.util.resolveStringValue
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.UUID
import kotlin.time.TimeSource

Expand Down Expand Up @@ -265,34 +266,64 @@ private class ClassObservationValueResolver(
internal class OriginalTypeScriptClassReplayer(
sourceRoot: Path,
private val function: CallsFunctionCase,
private val observationFields: Map<String, PropertyDomain>,
observationFields: Map<String, PropertyDomain>,
sourceOverride: String? = null,
overrideSourceFile: String? = null,
private val counterGlobalName: String? = null,
generatedEntry: CallsClassGeneratedReplayEntry? = null,
) : AutoCloseable {
private val root = sourceRoot.toRealPath()
private val workspace = Files.createTempDirectory("usvm-calls-class-replay-")
private val overlay = workspace.resolve("overlay")
private val observationPath = workspace.resolve("observation.json")
private val wrapperName = ".usvm-class-replay-${UUID.randomUUID()}.mts"
private val expectedFields = generatedEntry?.observationFields ?: observationFields.keys
private val backend: FastCheckBackend

init {
val setup = runCatching {
require(
(sourceOverride == null) == (overrideSourceFile == null)
) { "Source override needs a relative target file" }
val closure = checkedCallsSourceClosure(root = root, entry = root.resolve(function.sourceFile))
require(generatedEntry == null || sourceOverride == null) {
"Generated lifecycle replay requires original source"
}
val originalSourceFile = generatedEntry?.originalSourceFile ?: function.sourceFile
val closure = checkedCallsSourceClosure(root = root, entry = root.resolve(originalSourceFile))
if (generatedEntry != null) {
val inputs = closure.resolution?.inputSha256.orEmpty()
require((inputs.keys + closure.files).all { it in generatedEntry.frozenInputs }) {
"Lifecycle replay requires a complete frozen runtime source closure"
}
require(inputs.all { (file, hash) -> generatedEntry.frozenInputs[file] == hash }) {
"Lifecycle replay source closure has drifted"
}
require(generatedEntry.prototypeFiles.all { it in closure.files }) {
"Concrete input prototype source is outside the frozen runtime closure"
}
}
copyCallsSourceClosure(root = root, destination = overlay, closure = closure)
if (generatedEntry != null) {
for (file in closure.files) {
val copiedHash = callsClassSourceSha256(Files.readAllBytes(overlay.resolve(file)))
require(copiedHash == generatedEntry.frozenInputs.getValue(file)) {
"Lifecycle replay source changed: $file"
}
}
}
if (overrideSourceFile != null) {
require(overrideSourceFile in closure.files) { "Replay override is outside the frozen runtime closure" }
Files.writeString(overlay.resolve(overrideSourceFile), requireNotNull(sourceOverride))
}
val tsconfig = writeCallsFrozenTsconfig(root = overlay, resolution = closure.resolution)
val replayEntry = overlay.resolve(function.sourceFile)
Files.deleteIfExists(replayEntry)
val harnessSource = Files.readString(root.resolve(function.sourceFile))
Files.writeString(replayEntry, nativeCheckedClassHarness(harnessSource))
if (generatedEntry == null) {
Files.deleteIfExists(replayEntry)
val harnessSource = Files.readString(root.resolve(function.sourceFile))
Files.writeString(replayEntry, nativeCheckedClassHarness(harnessSource))
} else {
Files.writeString(replayEntry, generatedEntry.source, StandardOpenOption.CREATE_NEW)
}
Files.writeString(
overlay.resolve(wrapperName),
classReplayWrapper(
Expand All @@ -301,7 +332,7 @@ internal class OriginalTypeScriptClassReplayer(
observationPath = observationPath,
dropSentinel = function.inputs.isEmpty(),
counterGlobalName = counterGlobalName,
fields = observationFields.keys,
fields = expectedFields,
)
)
FastCheckBackend(sourceRoots = listOf(overlay), tsconfig = tsconfig)
Expand Down Expand Up @@ -371,7 +402,6 @@ internal class OriginalTypeScriptClassReplayer(
val inputsInsideDomains = observation.inputs.size == function.inputs.size &&
observation.inputs.zip(function.inputs).all { (value, input) -> value in input.domain }
require(inputsInsideDomains) { "Native sample is outside the frozen constructor input domains" }
val expectedFields = observationFields.keys
val hasExactFields = !observation.observation.representable ||
observation.observation.values.keys == expectedFields
require(hasExactFields) { "Class replay omitted or added observation fields" }
Expand Down
Loading
Loading