diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassInputCandidates.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassInputCandidates.kt index 897f9eb57f..95800a3bd7 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassInputCandidates.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassInputCandidates.kt @@ -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 @@ -43,6 +44,27 @@ internal data class CallsClassInputCandidate( val environmentComplete: Boolean, val environmentLimitations: List, val nativeReplayValidated: Boolean = false, + val returnedCallableScenario: CallsReturnedCallableScenario? = null, + val predictedReturn: CallsConcreteReturnedValue? = null, + val returnExtractionLimitation: String? = null, + val inputMethodCalls: List = 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 @@ -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 = 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>() @@ -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 @@ -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() + 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() - 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): 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() @@ -229,7 +335,7 @@ internal class CallsClassInputCandidates(output: Path, private val profile: Call private data class EntryBindings(val receiver: UExpr<*>, val parameters: List>) - 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) { @@ -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, @@ -266,5 +370,3 @@ private class InputJournal(private val path: Path) { ) } } - -private const val UNSIGNED_BYTE_MASK = 0xff diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassOracle.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassOracle.kt index 8e6d75d58e..6620985605 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassOracle.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassOracle.kt @@ -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 @@ -265,16 +266,18 @@ private class ClassObservationValueResolver( internal class OriginalTypeScriptClassReplayer( sourceRoot: Path, private val function: CallsFunctionCase, - private val observationFields: Map, + observationFields: Map, 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 { @@ -282,17 +285,45 @@ internal class OriginalTypeScriptClassReplayer( 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( @@ -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) @@ -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" } diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassRawAnalysis.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassRawAnalysis.kt index 7f31983563..04ca3c468a 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassRawAnalysis.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassRawAnalysis.kt @@ -6,6 +6,7 @@ import org.jacodb.ets.model.EtsStmt import org.usvm.PathSelectionStrategy import org.usvm.UPathSelector import org.usvm.machine.TsEntryPointTimeQuantumEvent +import org.usvm.machine.TsReturnedCallableScenario import org.usvm.machine.TsSolverQueryEvent import org.usvm.machine.state.TsMethodResult import org.usvm.machine.state.TsState @@ -131,6 +132,7 @@ internal class ClassRawAnalysisObserver( private val output: Path, private val retainRawStateDiagnostics: Boolean, private val profile: CallsExperimentProfile, + returnedCallableScenarios: Map = emptyMap(), ) : UMachineObserver { private val universe = universe.toList() private val universePoints = this.universe.toSet() @@ -142,7 +144,11 @@ internal class ClassRawAnalysisObserver( private val entered = linkedSetOf() private val snapshots = if (retainRawStateDiagnostics) CallsClassRawSnapshotStore(output = output) else null - private val candidates = CallsClassInputCandidates(output = output, profile = profile) + private val candidates = CallsClassInputCandidates( + output = output, + profile = profile, + returnedCallableScenarios = returnedCallableScenarios, + ) private val snapshotFailures = mutableListOf() private val methodSteps = linkedMapOf() private val sourceKinds = linkedMapOf() @@ -417,6 +423,7 @@ internal class ClassRawAnalysisObserver( output: Path, retainRawStateDiagnostics: Boolean, profile: CallsExperimentProfile, + returnedCallableScenarios: Map = emptyMap(), ): ClassRawAnalysisObserver { val target = methods.first().signature.enclosingClass val universe = methods.flatMap { it.cfg.stmts }.filter { @@ -428,6 +435,7 @@ internal class ClassRawAnalysisObserver( output = output, retainRawStateDiagnostics = retainRawStateDiagnostics, profile = profile, + returnedCallableScenarios = returnedCallableScenarios, ) } } diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt new file mode 100644 index 0000000000..c1feed0887 --- /dev/null +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplay.kt @@ -0,0 +1,504 @@ +package org.usvm.ts.calls + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.usvm.ts.pbt.fastcheck.FastCheckRuntime +import org.usvm.ts.pbt.model.ConstantDomain +import org.usvm.ts.pbt.model.JsConcreteValue +import org.usvm.ts.pbt.model.PropertyInput +import org.usvm.ts.pbt.model.TypeScriptEntryPoint +import org.usvm.ts.pbt.model.encodeToUtf8SafeString +import java.nio.file.Files +import java.nio.file.Path +import java.security.DigestInputStream +import java.security.MessageDigest + +@Serializable +internal enum class CallsReturnedCallableReplayPhase { CONSTRUCTOR, FACTORY, CALLABLE } + +@Serializable +internal data class CallsReturnedCallableReplayResult( + val classId: String, + val stateId: String, + val entryMethod: String, + val scenario: CallsReturnedCallableScenario, + val phase: CallsReturnedCallableReplayPhase, + val completion: CallsCoverageCompletion, + val symbolicCompletion: CallsCoverageCompletion?, + val completionMatches: Boolean?, + val returnedValue: JsConcreteValue?, + val predictedValue: JsConcreteValue?, + val returnValueMatches: Boolean?, + /** A returned callable ran under Node and its representable result matched the symbolic prediction. */ + val nativeReplayValidated: Boolean, + val generatedInputDouble: Boolean, + val generatedInputDoubleValidated: Boolean, + val recordedInputMethodCalls: Int, + val consumedInputMethodCalls: Int, + val inputTranscriptMatched: Boolean?, + val inputTranscriptDiagnostic: String?, + val inputMethodExtractionLimitation: String?, + val returnExtractionLimitation: String?, + val diagnostic: String?, + val replayElapsedMillis: Long, +) + +internal data class CallsClassGeneratedReplayEntry( + val originalSourceFile: String, + val source: String, + val frozenInputs: Map, + val prototypeFiles: Set, + val observationFields: Set, +) + +@Serializable +private data class CallsReturnedCallableReplayInput( + val heap: CallsConcreteHeap, + val methodCalls: List, +) + +internal fun replayClassLifecycle(args: List) { + val usesDouble = args.size == REQUIRED_REPLAY_ARGUMENTS + 1 && args.last() == "--generated-input-double" + require(args.size == REQUIRED_REPLAY_ARGUMENTS || usesDouble) { + "class-replay-lifecycle requires " + + "[--generated-input-double]" + } + val result = replayReturnedCallableCandidate( + manifestPath = Path.of(args[0]).toRealPath(), + classId = args[1], + probeDirectory = Path.of(args[2]).toRealPath(), + stateId = args[3], + generatedInputDouble = usesDouble, + ) + System.out.appendLine(CallsExperimentJson.json.encodeToUtf8SafeString(result)) +} + +internal fun replayReturnedCallableCandidate( + manifestPath: Path, + classId: String, + probeDirectory: Path, + stateId: String, + generatedInputDouble: Boolean = false, +): CallsReturnedCallableReplayResult { + val json = CallsExperimentJson.json + val manifestBytes = Files.readAllBytes(manifestPath) + val manifest = json.decodeFromString(manifestBytes.toString(Charsets.UTF_8)) + val case = manifest.classes.single { it.classId == classId } + val probe = json.decodeFromString(Files.readString(probeDirectory.resolve("result.json"))) + val matchesProbe = probe.classId == classId && probe.identity == case.identity && + probe.manifestSha256 == callsArtifactSha256(manifestBytes) + require(matchesProbe) { "Lifecycle probe identity differs from the frozen manifest" } + val raw = requireNotNull(probe.rawAnalysis) { "Missing lifecycle probe analysis" } + require(raw.profile == manifest.profile && raw.seed == manifest.seed) { + "Lifecycle probe profile or seed differs from the frozen manifest" + } + val journal = requireNotNull(raw.inputCandidates) { "Missing lifecycle input journal" } + val candidate = readLifecycleCandidate(directory = probeDirectory, journal = journal, stateId = stateId) + require(candidate.entryMethod in probe.automaticEntryPoints && candidate.profile == manifest.profile) { + "Selected candidate is outside the frozen automatic entries or profile" + } + case.verifyStartupAcquisition(manifestDirectory = manifestPath.toAbsolutePath().parent) + val root = case.verifyInputs() + + return replayReturnedCallable( + case = case, + sourceRoot = root, + candidate = candidate, + timeoutMillis = manifest.budgetMillis, + generatedInputDouble = generatedInputDouble, + ) +} + +private fun readLifecycleCandidate( + directory: Path, + journal: CallsClassInputJournalMetadata, + stateId: String, +): CallsClassInputCandidate { + val supportedJournal = journal.complete && journal.path == "input-candidates.jsonl" && + journal.schemaVersion == 1 && journal.format == "JSONL" + require(supportedJournal) { "Replay requires a complete input-candidates JSONL journal" } + val path = directory.resolve(journal.path).toRealPath() + require(path.parent == directory.toRealPath() && Files.size(path) == journal.bytes) { + "Input journal path or size differs from its receipt" + } + val digest = MessageDigest.getInstance("SHA-256") + val json = CallsExperimentJson.json + var selected: CallsClassInputCandidate? = null + var records = 0L + DigestInputStream(Files.newInputStream(path), digest).bufferedReader().useLines { lines -> + for (line in lines) { + records++ + val row = json.parseToJsonElement(line).jsonObject + if (row["stateId"]?.jsonPrimitive?.content != stateId) continue + + require(selected == null) { "More than one candidate for state $stateId" } + selected = json.decodeFromString(line) + } + } + val sha256 = formatCallsDigest(digest.digest()) + require(records == journal.records && sha256 == journal.sha256) { + "Input journal content differs from its receipt" + } + return requireNotNull(selected) { "No input candidate for state $stateId" } +} + +internal fun replayReturnedCallable( + case: CallsClassStartCase, + sourceRoot: Path, + candidate: CallsClassInputCandidate, + timeoutMillis: Long, + generatedInputDouble: Boolean = false, +): CallsReturnedCallableReplayResult { + val scenario = requireNotNull(candidate.returnedCallableScenario) { + "Candidate has no returned-callable scenario identity" + } + require(scenario.invocationReached) { "Symbolic scenario did not enter the returned callable" } + require(scenario.sourceFile == case.sourceFile && scenario.className == case.className) { + "Factory owner differs from the frozen target class" + } + val replayInput = prepareReplayInput(candidate, scenario, generatedInputDouble) + val replay = runReturnedCallableReplay( + case = case, + sourceRoot = sourceRoot, + scenario = scenario, + replayInput = replayInput, + timeoutMillis = timeoutMillis, + ) + return observeReturnedCallableReplay( + classId = case.classId, + candidate = candidate, + scenario = scenario, + replay = replay, + generatedInputDouble = generatedInputDouble, + methodCallCount = replayInput.methodCalls.size, + ) +} + +private fun prepareReplayInput( + candidate: CallsClassInputCandidate, + scenario: CallsReturnedCallableScenario, + generatedInputDouble: Boolean, +): CallsReturnedCallableReplayInput { + val heap = candidate.inputs + val hasUnrestoredBindings = !candidate.environmentComplete || heap.environmentFields.isNotEmpty() + require(!hasUnrestoredBindings) { "Lifecycle replay cannot restore recorded static or module bindings" } + val constructorCount = scenario.constructorArgumentCount + val factoryCount = scenario.factoryArgumentCount + val callableCount = scenario.callableArgumentCount + val matchesPartitions = heap.receiver == null && constructorCount >= 0 && factoryCount >= 0 && + callableCount >= 0 && (!scenario.factoryIsStatic || constructorCount == 0) && + constructorCount.toLong() + factoryCount + callableCount == heap.arguments.size.toLong() + require(matchesPartitions) { "Lifecycle argument partitions differ from the recorded caller heap" } + val methodCalls = if (generatedInputDouble) { + val nonemptyTrace = candidate.inputMethodCalls.isNotEmpty() + val completeTrace = candidate.inputMethodExtractionLimitation == null && nonemptyTrace && + candidate.inputMethodCalls.size == scenario.freshResidualCallCount + require(completeTrace) { + candidate.inputMethodExtractionLimitation ?: "Generated input double needs a complete method transcript" + } + verifyInputMethodCalls(heap, candidate.inputMethodCalls) + candidate.inputMethodCalls + } else { + emptyList() + } + + return CallsReturnedCallableReplayInput(heap = heap, methodCalls = methodCalls) +} + +private fun runReturnedCallableReplay( + case: CallsClassStartCase, + sourceRoot: Path, + scenario: CallsReturnedCallableScenario, + replayInput: CallsReturnedCallableReplayInput, + timeoutMillis: Long, +): CallsClassReplayObservation { + val modules = mutableMapOf(scenario.sourceFile to "targetModule") + val prototypes = linkedMapOf() + for (node in replayInput.heap.objects) { + val signature = node.classSignature + if (signature == null) { + require(node.classSourceFile == null && node.className == null) { "Incomplete prototype identity" } + continue + } + + val sourceFile = requireNotNull(node.classSourceFile) { "Concrete prototype has no source file" } + val className = requireNotNull(node.className) { "Concrete prototype has no class name" } + require(sourceFile in case.inputSha256) { "Concrete prototype source is not frozen: $sourceFile" } + val module = modules.getOrPut(sourceFile) { "prototypeModule${modules.size}" } + val reference = "requireClass($module, ${replayLiteral(className)}).prototype" + val previous = prototypes.putIfAbsent(signature, reference) + require(previous == null || previous == reference) { "Conflicting prototype for $signature" } + } + val encodedInput = JsConcreteValue.String(value = encodeCallsArtifact(replayInput)) + val input = PropertyInput(name = "encodedInput", domain = ConstantDomain(encodedInput)) + val function = CallsFunctionCase( + functionId = "returned-callable-replay", + sourceFile = RETURNED_CALLABLE_REPLAY_FILE, + entryPoint = TypeScriptEntryPoint( + module = RETURNED_CALLABLE_REPLAY_FILE, + exportName = "replayReturnedCallable", + ), + inputs = listOf(input), + targets = emptyList(), + ) + val driver = CallsClassGeneratedReplayEntry( + originalSourceFile = scenario.sourceFile, + source = returnedCallableDriver(scenario = scenario, modules = modules, prototypes = prototypes), + frozenInputs = case.inputSha256, + prototypeFiles = modules.keys - scenario.sourceFile, + observationFields = setOf( + "phase", + "completion", + "returnPayload", + "diagnostic", + "consumedInputMethodCalls", + "inputTranscriptMatched", + "inputTranscriptDiagnostic", + ), + ) + + return OriginalTypeScriptClassReplayer( + sourceRoot = sourceRoot, + function = function, + observationFields = emptyMap(), + generatedEntry = driver, + ).use { it.replay(inputs = listOf(encodedInput), timeoutMillis = timeoutMillis) } +} + +private fun observeReturnedCallableReplay( + classId: String, + candidate: CallsClassInputCandidate, + scenario: CallsReturnedCallableScenario, + replay: CallsClassReplayObservation, + generatedInputDouble: Boolean, + methodCallCount: Int, +): CallsReturnedCallableReplayResult { + val predictedValue = candidate.predictedReturn?.asReplayPrediction() + val observation = replay.observation + check(observation.representable && observation.completion == CallsCoverageCompletion.RETURNED) { + observation.diagnostic ?: "Native lifecycle replay produced no phase evidence" + } + val phase = CallsReturnedCallableReplayPhase.valueOf(observation.requiredText("phase")) + val completion = CallsCoverageCompletion.valueOf(observation.requiredText("completion")) + val returnPayload = observation.optionalText("returnPayload") + val returnedValue = returnPayload?.let { CallsExperimentJson.json.decodeFromString(it) } + val consumedCalls = observation.requiredText("consumedInputMethodCalls").toInt() + val transcriptMatched = observation.optionalText("inputTranscriptMatched")?.toBooleanStrict() + val transcriptDiagnostic = observation.optionalText("inputTranscriptDiagnostic") + val symbolicCompletion = candidate.completion + val replayedAllResiduals = if (generatedInputDouble) { + transcriptMatched == true && consumedCalls == methodCallCount + } else { + scenario.freshResidualCallCount == 0 + } + val completionMatches = symbolicCompletion?.let { + phase == CallsReturnedCallableReplayPhase.CALLABLE && it == completion + } + val comparesReturnValue = replayedAllResiduals && completionMatches == true && + completion == CallsCoverageCompletion.RETURNED + val returnValueMatches = when { + !comparesReturnValue -> null + returnedValue != null && predictedValue != null -> returnedValue == predictedValue + else -> null + } + return CallsReturnedCallableReplayResult( + classId = classId, + stateId = candidate.stateId, + entryMethod = candidate.entryMethod, + scenario = scenario, + phase = phase, + completion = completion, + symbolicCompletion = symbolicCompletion, + completionMatches = completionMatches, + returnedValue = returnedValue, + predictedValue = predictedValue, + returnValueMatches = returnValueMatches, + nativeReplayValidated = !generatedInputDouble && returnValueMatches == true, + generatedInputDouble = generatedInputDouble, + generatedInputDoubleValidated = generatedInputDouble && returnValueMatches == true, + recordedInputMethodCalls = candidate.inputMethodCalls.size, + consumedInputMethodCalls = consumedCalls, + inputTranscriptMatched = transcriptMatched, + inputTranscriptDiagnostic = transcriptDiagnostic, + inputMethodExtractionLimitation = candidate.inputMethodExtractionLimitation, + returnExtractionLimitation = candidate.returnExtractionLimitation, + diagnostic = observation.optionalText("diagnostic"), + replayElapsedMillis = replay.replayElapsedMillis, + ) +} + +private fun verifyInputMethodCalls(heap: CallsConcreteHeap, calls: List) { + val nodes = heap.objects.associateBy { it.id } + require(nodes.size == heap.objects.size) { "Duplicate input heap object ID" } + val reachable = mutableSetOf() + val pending = ArrayDeque(heap.arguments.mapNotNull { it.objectId }) + while (pending.isNotEmpty()) { + val id = pending.removeFirst() + if (!reachable.add(id)) continue + + val node = requireNotNull(nodes[id]) { "Missing input heap object $id" } + val values = node.elements ?: node.fields.orEmpty().values + values.mapNotNullTo(pending) { it.objectId } + } + for (call in calls) { + val receiver = nodes[call.receiverObjectId] + val isReachablePlainObject = receiver?.fields != null && receiver.classSignature == null && + call.receiverObjectId in reachable + require(isReachablePlainObject) { "Generated input double receiver is not a reachable plain input object" } + val name = call.methodName + require(name.isNotBlank() && name !in setOf("__proto__", "constructor", "prototype")) { + "Generated input double cannot install an unsafe method name" + } + require(name !in requireNotNull(receiver?.fields)) { + "Generated input double cannot replace an own input member: $name" + } + val references = (call.arguments + call.returnedValue).mapNotNull { it.objectId } + require(references.all { it in reachable }) { "Input method transcript refers outside the original heap" } + } +} + +private fun CallsClassObservation.requiredText(name: String): String = + requireNotNull(optionalText(name)) { "Missing native replay value $name" } + +private fun CallsClassObservation.optionalText(name: String): String? = when (val field = values.getValue(name)) { + JsConcreteValue.Undefined -> null + is JsConcreteValue.String -> field.value + else -> error("Invalid native replay value $name") +} + +private fun CallsConcreteReturnedValue.asReplayPrediction(): JsConcreteValue? { + val nodes = objects.associateBy { it.id } + if (nodes.size != objects.size) return null + + val seen = mutableSetOf() + fun resolve(slot: CallsConcreteHeapValue): JsConcreteValue? { + val primitive = slot.primitive + if (primitive != null) return primitive + + val id = slot.objectId ?: return null + val node = nodes[id] ?: return null + if (!seen.add(node.id) || node.classSignature != null) return null + + val elements = node.elements + if (elements != null) { + val values = elements.map { resolve(it) ?: return null } + return JsConcreteValue.Array(values) + } + val fields = linkedMapOf() + for ((name, field) in node.fields.orEmpty()) { + if (name in setOf("__proto__", "constructor", "prototype")) return null + + fields[name] = resolve(field) ?: return null + } + return JsConcreteValue.Object(fields) + } + + val result = resolve(value) ?: return null + return result.takeIf { seen.size == nodes.size } +} + +private fun returnedCallableDriver( + scenario: CallsReturnedCallableScenario, + modules: Map, + prototypes: Map, +): String { + val imports = modules.entries.joinToString("\n") { (path, name) -> + "import * as $name from ${replayLiteral("./$path")};" + } + val valueCodec = replayLiteral(FastCheckRuntime.concreteValueModule().toUri().toString()) + val protocolJson = replayLiteral(FastCheckRuntime.protocolJsonModule().toUri().toString()) + val classKey = replayLiteral(scenario.className) + val factoryKey = replayLiteral(scenario.factoryMethod) + val factoryStart = scenario.constructorArgumentCount + val callableStart = factoryStart + scenario.factoryArgumentCount + val prototypeEntries = prototypes.entries.joinToString { (key, expression) -> + "[${replayLiteral(key)}, $expression]" + } + val ownerPreparation = if (scenario.factoryIsStatic) { + "const owner = target;" + } else { + """ + let owner: any; + try { + owner = Reflect.construct(target, args.slice(0, $factoryStart)); + } catch (error) { + return observed(threw('CONSTRUCTOR', error)); + } + """.trimIndent() + } + + return """ + $imports + import { decodeJsValue, encodeJsValue } from $valueCodec; + import { stringifyProtocolJson } from $protocolJson; + + ${callsConcreteHeapRestoreSource()} + ${callsInputMethodDoubleSource()} + + function requireClass(module: any, name: string): any { + const value = module[name]; + const prototype = typeof value === 'function' && Object.getOwnPropertyDescriptor(value, 'prototype'); + if (!prototype || typeof prototype.value !== 'object' || prototype.value === null || value.name !== name) { + throw new Error('Original class export is unavailable: ' + name); + } + return value; + } + + function threw(phase: string, error: unknown) { + const diagnostic = error instanceof Error ? error.name + ': ' + error.message : 'Thrown ' + typeof error; + return { phase, completion: 'THREW', returnPayload: undefined, diagnostic }; + } + + export function replayReturnedCallable(encodedInput: string) { + const target = requireClass(targetModule, $classKey); + const prototypes = new Map([$prototypeEntries]); + const input = JSON.parse(encodedInput); + const restored = restoreCallsConcreteHeap(input.heap, prototypes, decodeJsValue); + const args = restored.arguments; + const transcript = input.methodCalls.length === 0 ? undefined : + installCallsInputMethodDouble(input.methodCalls, restored); + function observed(result: object) { + const evidence = transcript?.(); + return { ...result, + consumedInputMethodCalls: String(evidence?.consumedInputMethodCalls ?? 0), + inputTranscriptMatched: evidence === undefined ? undefined : String(evidence.inputTranscriptMatched), + inputTranscriptDiagnostic: evidence?.inputTranscriptDiagnostic }; + } + $ownerPreparation + + let callback: unknown; + try { + callback = Reflect.apply(owner[$factoryKey], owner, args.slice($factoryStart, $callableStart)); + } catch (error) { + return observed(threw('FACTORY', error)); + } + if (typeof callback !== 'function') { + return observed({ phase: 'FACTORY', completion: 'RETURNED', returnPayload: undefined, + diagnostic: 'Factory did not return a callable' }); + } + + let value: unknown; + try { + value = Reflect.apply(callback, undefined, args.slice($callableStart)); + } catch (error) { + return observed(threw('CALLABLE', error)); + } + + let returnPayload: string | undefined; + try { + returnPayload = stringifyProtocolJson(encodeJsValue(value)); + } catch { + // The observation protocol cannot encode every JavaScript value. + } + const diagnostic = returnPayload !== undefined ? undefined : 'Unrepresentable return value'; + return observed({ phase: 'CALLABLE', completion: 'RETURNED', returnPayload, diagnostic }); + } + """.trimIndent() + "\n" +} + +private fun replayLiteral(value: String): String = CallsExperimentJson.json.encodeToUtf8SafeString(value) + +private const val RETURNED_CALLABLE_REPLAY_FILE = ".usvm-returned-callable-replay.ts" + +private const val REQUIRED_REPLAY_ARGUMENTS = 4 diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassStartSmoke.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassStartSmoke.kt index 11e509dc90..f44fadf9a2 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassStartSmoke.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsClassStartSmoke.kt @@ -26,6 +26,7 @@ import org.usvm.machine.TsInterpreterObserver import org.usvm.machine.TsMachine import org.usvm.machine.TsOptions import org.usvm.machine.TsSolverQueryEvent +import org.usvm.machine.buildTsLifecycleScenarios import org.usvm.machine.call.TsUnknownCallEvent import org.usvm.machine.call.TsUnknownCallModelSelection import org.usvm.machine.expr.TsSimpleValueResolver @@ -100,6 +101,7 @@ internal data class CallsClassStartManifest( val profile: CallsExperimentProfile = CallsExperimentProfile.FROZEN_STOP, val classes: List, val retainRawStateDiagnostics: Boolean = false, + val automaticLifecycles: Boolean = false, val frozenModelIds: Set? = null, val maxInputCollectionSize: Int? = null, ) { @@ -160,6 +162,7 @@ internal data class CallsClassStartResult( val rawAnalysis: CallsClassRawAnalysis? = null, val targetDeclarationCandidates: List = emptyList(), val entryPointEligibility: List = emptyList(), + val automaticEntryPoints: List = emptyList(), ) @Serializable @@ -434,6 +437,7 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { var targetDeclarations = emptyList() var methods = emptyList() var entryPoints = emptyList() + var automaticEntryPoints = emptyList() var observer: ClassStartObserver? = null var rawObserver: ClassRawAnalysisObserver? = null var remainingSelector: UPathSelector? = null @@ -492,7 +496,15 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { require(methods.isNotEmpty()) { "Target class has no executable IR bodies" } entryPoints = classStartupEntryPoints(methods) val independentMethods = methods.filter { !it.name.startsWith(ANONYMOUS_METHOD_PREFIX) } - require(independentMethods.isNotEmpty()) { "Target class has no independently bindable entry points" } + val lifecycle = if (exploratory && manifest.automaticLifecycles) { + buildTsLifecycleScenarios(scene = scene, target = target) + } else { + null + } + val automaticMethods = lifecycle?.methods.orEmpty() + automaticEntryPoints = automaticMethods.map { it.signature.toString() } + val analysisMethods = independentMethods + automaticMethods + require(analysisMethods.isNotEmpty()) { "Target class has no independently bindable entry points" } val raw = if (exploratory) { ClassRawAnalysisObserver.forTarget( methods = methods, @@ -500,6 +512,7 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { sourceText = sourceText, output = output, retainRawStateDiagnostics = manifest.retainRawStateDiagnostics, + returnedCallableScenarios = lifecycle?.returnedCallableScenarios.orEmpty(), profile = manifest.profile, ) } else { @@ -540,6 +553,7 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { methodSignatures = methods.map { it.signature.toString() }, firstOriginalStep = current.firstOriginalStep, entryPointEligibility = entryPoints, + automaticEntryPoints = automaticEntryPoints, ) writeCallsArtifactAtomically(output.resolve("progress.json"), encodeCallsArtifact(progress)) }, @@ -582,7 +596,7 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { val factory = if (raw == null) null else ::rawMachineObserver val timeQuantum = if (exploratory) manifest.timeQuantumMillis.milliseconds else Duration.INFINITE TsMachine( - scene = scene, + scene = lifecycle?.scene ?: scene, options = UMachineOptions( pathSelectionStrategies = listOf(manifest.pathSelectionStrategy), stateCollectionStrategy = StateCollectionStrategy.ALL, @@ -618,8 +632,11 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { val analysisStarted = TimeSource.Monotonic.markNow() try { outcome = machine.analyzeWithMetadata( - methods = independentMethods, + methods = analysisMethods, configureInitialState = { method, state -> + if (lifecycle?.returnedCallableScenarios?.containsKey(method) == true) { + state.recordFreshInputMethodsForReplay() + } machineObserver.registerInitialState(method = method, state = state) raw?.registerInitialState(method = method, state = state) }, @@ -698,6 +715,7 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { rawAnalysis = rawObserver?.result(manifest = manifest, analysisElapsedMillis = analysisElapsedMillis), targetDeclarationCandidates = targetDeclarations, entryPointEligibility = entryPoints, + automaticEntryPoints = automaticEntryPoints, ) writeCallsArtifactAtomically(output.resolve("result.json"), encodeCallsArtifact(result)) System.out.appendLine(encodeCallsArtifact(result)) diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsConcreteHeap.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsConcreteHeap.kt index a64394ba5e..12c649c7d7 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsConcreteHeap.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsConcreteHeap.kt @@ -6,6 +6,7 @@ import org.jacodb.ets.utils.DEFAULT_ARK_CLASS_NAME import org.usvm.api.TsParametersState import org.usvm.api.TsTestValue import org.usvm.ts.pbt.model.JsConcreteValue +import org.usvm.util.TsResolvedInputMethodCall import java.util.IdentityHashMap /** A primitive transport value or a reference into one concrete test's object table. */ @@ -56,15 +57,55 @@ internal data class CallsConcreteHeap( val environmentFields: List = emptyList(), ) +/** Value and object identities of a normally returned result, independent of the before-input heap. */ +@Serializable +internal data class CallsConcreteReturnedValue( + val value: CallsConcreteHeapValue, + val objects: List, +) + +@Serializable +internal data class CallsConcreteInputMethodCall( + val receiverObjectId: Int, + val methodName: String, + val arguments: List, + val returnedValue: CallsConcreteHeapValue, +) + +internal data class CallsConcreteInputs( + val heap: CallsConcreteHeap, + val methodCalls: Result>?, +) + internal data class CallsConcretePrototype(val signature: EtsClassSignature, val ordinaryObject: Boolean) +internal fun concreteCallsReturnedValue( + value: TsTestValue, + prototypes: Map, +): CallsConcreteReturnedValue { + val encoder = ConcreteHeapEncoder(prototypes = prototypes) + val result = encoder.value(value) + val objects = encoder.objects() + val ordinaryPrototypes = objects.all { it.classSignature == null } + require(ordinaryPrototypes) { "Returned values with non-ordinary prototypes do not have a replay value comparison" } + return CallsConcreteReturnedValue(value = result, objects = objects) +} + internal fun concreteCallsInputHeap( inputs: TsParametersState, prototypes: Map, -): CallsConcreteHeap { +): CallsConcreteHeap = concreteCallsInputs(inputs, prototypes).heap + +internal fun concreteCallsInputs( + inputs: TsParametersState, + prototypes: Map, + methodCalls: Result>? = null, +): CallsConcreteInputs { val encoder = ConcreteHeapEncoder(prototypes = prototypes) val receiver = inputs.thisInstance?.let { encoder.value(it) } val arguments = inputs.parameters.map { encoder.value(it) } + // A trace may refer to an existing input object, but may not introduce new object identities. + val concreteMethods = methodCalls?.mapCatching { calls -> calls.map(encoder::inputMethodCall) } val fields = inputs.globals.flatMap { (owner, fields) -> fields.map { field -> CallsConcreteEnvironmentField( @@ -81,12 +122,13 @@ internal fun concreteCallsInputHeap( ) } } - return CallsConcreteHeap( + val heap = CallsConcreteHeap( receiver = receiver, arguments = arguments, objects = encoder.objects(), environmentFields = fields, ) + return CallsConcreteInputs(heap = heap, methodCalls = concreteMethods) } private class ConcreteHeapEncoder(private val prototypes: Map) { @@ -95,6 +137,34 @@ private class ConcreteHeapEncoder(private val prototypes: Map = objects.map { checkNotNull(it) } + fun inputMethodCall(call: TsResolvedInputMethodCall): CallsConcreteInputMethodCall { + val receiver = checkNotNull(identities[call.receiver]) { + "An input method receiver is not reachable from the input arguments" + } + val node = checkNotNull(objects[receiver]) + val fields = checkNotNull(node.fields) { "An input method receiver is not a plain object" } + val name = call.methodName + check(node.classSignature == null && !fields.containsKey(name) && name !in inheritedObjectNames) { + "Input method '$name' could replace an existing property or project prototype method" + } + + return CallsConcreteInputMethodCall( + receiverObjectId = receiver, + methodName = name, + arguments = call.arguments.map(::existingInputValue), + returnedValue = existingInputValue(call.returnedValue), + ) + } + + private fun existingInputValue(value: TsTestValue): CallsConcreteHeapValue { + if (value !is TsTestValue.TsClass && value !is TsTestValue.TsArray<*>) return value(value) + + val id = checkNotNull(identities[value]) { + "An input method call requires an object outside the original input heap" + } + return CallsConcreteHeapValue(objectId = id) + } + fun value(value: TsTestValue): CallsConcreteHeapValue { val primitive = when (value) { TsTestValue.TsNull -> JsConcreteValue.Null @@ -139,3 +209,8 @@ private class ConcreteHeapEncoder(private val prototypes: Map Object.is(arg, restored.resolve(next.arguments[index]))); + if (!matches) { + mismatch ??= 'Unexpected generated input method call ' + name + ' at index ' + consumed; + throw new Error(mismatch); + } + + consumed++; + return restored.resolve(next.returnedValue); + } + + const installed = new Map>(); + for (const call of calls) { + const receiver = restored.objects.get(call.receiverObjectId); + const name = call.methodName; + let names = installed.get(receiver); + if (names?.has(name)) continue; + if (receiver == null || Object.getPrototypeOf(receiver) !== Object.prototype || Reflect.has(receiver, name)) { + throw new Error('Cannot install generated input method ' + name + ' on an existing member or prototype'); + } + if (names === undefined) { + names = new Set(); + installed.set(receiver, names); + } + names.add(name); + Object.defineProperty(receiver, name, { + value: function (this: object, ...args: unknown[]) { return invoke(receiver, this, name, args); }, + writable: true, + configurable: true, + }); + } + return () => { + const inputTranscriptDiagnostic = mismatch ?? (consumed === calls.length ? undefined : + 'Generated input method transcript stopped at index ' + consumed + ' of ' + calls.length); + return { consumedInputMethodCalls: consumed, inputTranscriptDiagnostic, + inputTranscriptMatched: inputTranscriptDiagnostic === undefined }; + }; } """.trimIndent() diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsCoverageCell.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsCoverageCell.kt index 7150445f27..d27d8482e0 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsCoverageCell.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsCoverageCell.kt @@ -422,7 +422,10 @@ private val COVERAGE_CHECKPOINT_MILLIS = listOf( THIRD_CHECKPOINT_MILLIS, ) -internal fun callsArtifactSha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes) +internal fun callsArtifactSha256(bytes: ByteArray): String = + formatCallsDigest(MessageDigest.getInstance("SHA-256").digest(bytes)) + +internal fun formatCallsDigest(digest: ByteArray): String = digest .joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and UNSIGNED_BYTE_MASK) } private const val COVERAGE_UNIVERSE_ARGUMENT_COUNT = 4 diff --git a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsExperimentCli.kt b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsExperimentCli.kt index 004c03d6d6..558f20fb3e 100644 --- a/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsExperimentCli.kt +++ b/usvm-ts-calls/src/main/kotlin/org/usvm/ts/calls/CallsExperimentCli.kt @@ -12,6 +12,7 @@ fun main(args: Array) { "class-catalog" -> runClassCatalog(args.drop(1)) "class-start-smoke" -> runClassStartSmoke(args.drop(1)) "class-symbolic-probe" -> runClassSymbolicProbe(args.drop(1)) + "class-replay-lifecycle" -> replayClassLifecycle(args.drop(1)) "class-prepare" -> runClassPrepare(args.drop(1)) "class-preflight" -> runClassPreflight(args.drop(1)) "class-cell" -> runClassCell(args.drop(1)) @@ -108,6 +109,7 @@ private fun usage(): String = """ calls class-catalog calls class-start-smoke calls class-symbolic-probe + calls class-replay-lifecycle [--generated-input-double] calls class-prepare calls class-preflight calls class-cell diff --git a/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt new file mode 100644 index 0000000000..0a895c5d74 --- /dev/null +++ b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsClassReturnedCallableReplayTest.kt @@ -0,0 +1,245 @@ +package org.usvm.ts.calls + +import org.junit.jupiter.api.io.TempDir +import org.usvm.ts.pbt.model.JsConcreteValue +import java.nio.file.Files +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class CallsClassReturnedCallableReplayTest { + @TempDir + lateinit var directory: Path + + @Test + fun `native caller preserves aliases and the exact exported argument prototype`() { + val case = sourceCase( + """ + export class Input { + constructor(public score: number) {} + get adjusted() { return this.score + 2; } + } + + export class Target { + constructor(private readonly bias: number) {} + + make(input: Input) { + input.score++; + const bias = this.bias; + return function(this: undefined, other: Input) { + if (this !== undefined || other !== input || !(other instanceof Input)) { + throw new Error('Receiver or caller heap identity changed'); + } + return bias + other.adjusted; + }; + } + } + """.trimIndent(), + ) + val handle = CallsConcreteHeapValue(objectId = 0) + val heap = CallsConcreteHeap( + receiver = null, + arguments = listOf(number(7.0), handle, handle), + objects = listOf( + CallsConcreteHeapObject( + id = 0, + classSignature = "@fixture/Target.ts: Input", + classSourceFile = "Target.ts", + className = "Input", + fields = mapOf("score" to number(11.0)), + ), + ), + ) + val candidate = candidate( + heap, + isStatic = false, + predicted = number(21.0), + ) + + val replay = replayReturnedCallable(case, directory, candidate, timeoutMillis = 10_000) + + assertEquals(CallsReturnedCallableReplayPhase.CALLABLE, replay.phase) + assertEquals(CallsCoverageCompletion.RETURNED, replay.completion) + assertEquals(JsConcreteValue.number(21.0), replay.returnedValue) + assertEquals(true, replay.returnValueMatches) + assertTrue(replay.nativeReplayValidated) + } + + @Test + fun `native closure exception is retained as a callable mismatch`() { + val case = sourceCase( + """ + export class Target { + static make(base: number) { + return (arg: number): number => { + throw new TypeError('missing adapter ' + (base + arg)); + }; + } + } + """.trimIndent(), + ) + val heap = CallsConcreteHeap( + receiver = null, + arguments = listOf(number(1.0), number(2.0)), + objects = emptyList(), + ) + val candidate = candidate(heap, isStatic = true, predicted = number(3.0)) + + val replay = replayReturnedCallable(case, directory, candidate, timeoutMillis = 10_000) + + assertEquals(CallsReturnedCallableReplayPhase.CALLABLE, replay.phase) + assertEquals(CallsCoverageCompletion.THREW, replay.completion) + assertEquals(expected = false, actual = replay.completionMatches) + assertEquals("TypeError: missing adapter 3", replay.diagnostic) + assertNull(replay.returnedValue) + assertFalse(replay.nativeReplayValidated) + } + + @Test + fun `generated methods preserve aliases and require the whole ordered transcript`() { + val case = sourceCase( + """ + export class Target { + static make(adapter: { deserialize(input: object): object; serialize(input: object): number }) { + return (input: object): number => { + const result = adapter.deserialize(input); + if (result !== input) throw new Error('Restored argument alias changed'); + return adapter.serialize(result); + }; + } + } + """.trimIndent(), + ) + val input = CallsConcreteHeapValue(objectId = 1) + val heap = CallsConcreteHeap( + receiver = null, + arguments = listOf(CallsConcreteHeapValue(objectId = 0), input), + objects = listOf( + CallsConcreteHeapObject(id = 0, fields = emptyMap()), + CallsConcreteHeapObject(id = 1, fields = emptyMap()), + ), + ) + val calls = listOf( + CallsConcreteInputMethodCall( + receiverObjectId = 0, + methodName = "deserialize", + arguments = listOf(input), + returnedValue = input, + ), + CallsConcreteInputMethodCall( + receiverObjectId = 0, + methodName = "serialize", + arguments = listOf(input), + returnedValue = number(17.0), + ), + ) + val base = candidate(heap, isStatic = true, predicted = number(17.0)) + val scenario = requireNotNull(base.returnedCallableScenario).copy(freshResidualCallCount = calls.size) + val candidate = base.copy(returnedCallableScenario = scenario, inputMethodCalls = calls) + + val plain = replayReturnedCallable(case, directory, candidate, timeoutMillis = 10_000) + val replay = replayReturnedCallable( + case = case, + sourceRoot = directory, + candidate = candidate, + timeoutMillis = 10_000, + generatedInputDouble = true, + ) + val reordered = replayReturnedCallable( + case = case, + sourceRoot = directory, + candidate = candidate.copy(inputMethodCalls = calls.reversed()), + timeoutMillis = 10_000, + generatedInputDouble = true, + ) + val extended = candidate.copy( + returnedCallableScenario = scenario.copy(freshResidualCallCount = calls.size + 1), + inputMethodCalls = calls + calls.last(), + ) + val unconsumed = replayReturnedCallable( + case = case, + sourceRoot = directory, + candidate = extended, + timeoutMillis = 10_000, + generatedInputDouble = true, + ) + + assertEquals(CallsCoverageCompletion.THREW, plain.completion) + assertFalse(plain.nativeReplayValidated) + assertEquals(JsConcreteValue.number(17.0), replay.returnedValue) + assertEquals(calls.size, replay.consumedInputMethodCalls) + assertEquals(true, replay.inputTranscriptMatched) + assertTrue(replay.generatedInputDoubleValidated) + assertFalse(replay.nativeReplayValidated) + assertEquals(false, reordered.inputTranscriptMatched) + assertFalse(reordered.generatedInputDoubleValidated) + assertEquals(JsConcreteValue.number(17.0), unconsumed.returnedValue) + assertEquals(false, unconsumed.inputTranscriptMatched) + assertFalse(unconsumed.generatedInputDoubleValidated) + + val receiverWithMethod = heap.objects.first().copy(fields = mapOf("deserialize" to number(0.0))) + val hasOwnMethod = candidate.copy(inputs = heap.copy(objects = listOf(receiverWithMethod, heap.objects.last()))) + + val rejection = assertFailsWith { + replayReturnedCallable(case, directory, hasOwnMethod, timeoutMillis = 10_000, generatedInputDouble = true) + } + assertTrue(requireNotNull(rejection.message).contains("cannot replace an own input member")) + } + + private fun sourceCase(contents: String): CallsClassStartCase { + Files.writeString(directory.resolve("Target.ts"), contents) + return CallsClassStartCase( + classId = "target", + identity = "fixture@Target", + projectRevision = "a".repeat(40), + sourceRoot = directory.toString(), + sourceFile = "Target.ts", + className = "Target", + inputSha256 = startupIrFiles(directory), + ) + } + + private fun candidate( + inputs: CallsConcreteHeap, + isStatic: Boolean, + predicted: CallsConcreteHeapValue, + ): CallsClassInputCandidate = CallsClassInputCandidate( + stateId = "1", + entryMethod = "%Lifecycle\$Target::return.make", + currentMethod = "%Lifecycle\$Target::return.make", + statementIndex = 0, + className = "%Lifecycle\$Target", + methodName = "return.make", + invocationKind = CallsClassInvocationKind.STATIC_METHOD, + outcome = "RETURNED", + profile = CallsExperimentProfile.EMPTY_STOP, + origin = CallsCoverageCandidateOrigin.TERMINATED, + completion = CallsCoverageCompletion.RETURNED, + suspensionReason = null, + suspendedAtMachineStop = false, + emittedAtMillis = 0, + inputs = inputs, + environmentComplete = true, + environmentLimitations = emptyList(), + returnedCallableScenario = CallsReturnedCallableScenario( + sourceFile = "Target.ts", + className = "Target", + factoryMethod = "make", + factorySignature = "Target::make", + factoryIsStatic = isStatic, + constructorArgumentCount = if (isStatic) 0 else 1, + factoryArgumentCount = 1, + callableArgumentCount = 1, + invocationReached = true, + callableTargetMethod = "Target::callback", + freshResidualCallCount = 0, + ), + predictedReturn = CallsConcreteReturnedValue(value = predicted, objects = emptyList()), + ) + + private fun number(value: Double) = CallsConcreteHeapValue(primitive = JsConcreteValue.number(value)) +} diff --git a/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsReturnedCallableJournalTest.kt b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsReturnedCallableJournalTest.kt new file mode 100644 index 0000000000..3e81be4c88 --- /dev/null +++ b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsReturnedCallableJournalTest.kt @@ -0,0 +1,184 @@ +package org.usvm.ts.calls + +import org.junit.jupiter.api.io.TempDir +import org.usvm.ts.pbt.model.JsConcreteValue +import java.nio.file.Files +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class CallsReturnedCallableJournalTest { + @TempDir + lateinit var directory: Path + + @Test + fun `generated input partitions replay the factory capture and detached call exactly`() { + val source = """ + export class JournalFactory { + constructor(private readonly seed: number) {} + + create(delta: number) { + if (this.seed !== 7 || delta !== 5) return undefined; + return (input: number) => { + if (input !== 11) throw input; + return { answer: this.seed + delta + input }; + }; + } + } + """.trimIndent() + val probe = probe(source, factoryMethod = "create") + + val candidates = probe.candidates + val beforeCall = candidates.filter { it.returnedCallableScenario?.invocationReached == false } + assertTrue(beforeCall.isNotEmpty()) + val beforeCallHasNoEvidence = beforeCall.all { + it.predictedReturn == null && it.returnedCallableScenario?.callableTargetMethod == null + } + assertTrue(beforeCallHasNoEvidence) + + val candidate = candidates.single { + it.completion == CallsCoverageCompletion.RETURNED && it.returnedCallableScenario?.invocationReached == true + } + val scenario = assertNotNull(candidate.returnedCallableScenario) + assertEquals("JournalFactory.ts", scenario.sourceFile) + assertEquals("JournalFactory", scenario.className) + assertFalse(scenario.factoryIsStatic) + assertEquals(expected = 1, actual = scenario.constructorArgumentCount) + assertEquals(expected = 1, actual = scenario.factoryArgumentCount) + assertEquals(expected = 1, actual = scenario.callableArgumentCount) + assertNotNull(scenario.callableTargetMethod) + assertEquals(expected = 0, actual = scenario.freshResidualCallCount) + val arguments = candidate.inputs.arguments.map { it.primitive } + val expectedArguments = listOf(7.0, 5.0, 11.0).map { JsConcreteValue.number(it) } + assertEquals(expectedArguments, arguments) + assertNull(candidate.returnExtractionLimitation) + + val replay = probe.replay(candidate) + + assertEquals(CallsReturnedCallableReplayPhase.CALLABLE, replay.phase) + assertEquals(CallsCoverageCompletion.RETURNED, replay.completion) + val expected = JsConcreteValue.Object(mapOf("answer" to JsConcreteValue.number(23.0))) + assertEquals(expected, replay.predictedValue) + assertEquals(expected, replay.returnedValue) + assertEquals(expected = true, actual = replay.returnValueMatches) + } + + @Test + fun `generated input method transcript drives the original detached callable`() { + val source = """ + export class JournalFactory { + static create(adapter: any): (input: number) => { answer: number } { + return (input: number) => { + if (input !== 11) throw input; + const first = adapter.choose(input); + if (first !== 7) throw first; + const second = adapter.choose(first); + if (second !== 5) throw second; + return { answer: input + first + second }; + }; + } + } + """.trimIndent() + val probe = probe(source, factoryMethod = "create") + + val completed = probe.candidates.filter { + it.completion == CallsCoverageCompletion.RETURNED && it.returnedCallableScenario?.invocationReached == true + } + val candidate = assertNotNull( + completed.firstOrNull { it.inputMethodCalls.size == 2 }, + message = "No complete two-call transcript: ${completed.map { it.inputMethodExtractionLimitation }}", + ) + val scenario = assertNotNull(candidate.returnedCallableScenario) + assertEquals(expected = 2, actual = scenario.freshResidualCallCount) + assertNull(candidate.inputMethodExtractionLimitation) + val adapter = candidate.inputs.arguments.first() + val receiver = assertNotNull(adapter.objectId) + assertEquals(listOf(receiver, receiver), candidate.inputMethodCalls.map { it.receiverObjectId }) + assertEquals(listOf("choose", "choose"), candidate.inputMethodCalls.map { it.methodName }) + val expectedArguments = listOf(11.0, 7.0).map { JsConcreteValue.number(it) } + assertEquals(expectedArguments, candidate.inputMethodCalls.map { it.arguments.single().primitive }) + val expectedReturns = listOf(7.0, 5.0).map { JsConcreteValue.number(it) } + assertEquals(expectedReturns, candidate.inputMethodCalls.map { it.returnedValue.primitive }) + + val plain = probe.replay(candidate) + val withDouble = probe.replay(candidate, generatedInputDouble = true) + + assertEquals(CallsReturnedCallableReplayPhase.CALLABLE, plain.phase) + assertEquals(CallsCoverageCompletion.THREW, plain.completion) + assertFalse(plain.nativeReplayValidated) + assertEquals(CallsReturnedCallableReplayPhase.CALLABLE, withDouble.phase) + assertEquals(CallsCoverageCompletion.RETURNED, withDouble.completion) + val expected = JsConcreteValue.Object(mapOf("answer" to JsConcreteValue.number(23.0))) + assertEquals(expected, withDouble.predictedValue) + assertEquals(expected, withDouble.returnedValue) + assertEquals(expected = 2, actual = withDouble.consumedInputMethodCalls) + assertEquals(expected = true, actual = withDouble.inputTranscriptMatched) + assertTrue(withDouble.generatedInputDoubleValidated) + assertFalse(withDouble.nativeReplayValidated) + } + + private fun probe(source: String, factoryMethod: String): LifecycleProbe { + val inputs = Files.createDirectory(directory.resolve("inputs")) + Files.writeString(inputs.resolve("JournalFactory.ts"), source) + val case = CallsClassStartCase( + classId = "journal-factory", + identity = "fixture@JournalFactory", + projectRevision = "a".repeat(40), + sourceRoot = inputs.toString(), + sourceFile = "JournalFactory.ts", + className = "JournalFactory", + inputSha256 = startupIrFiles(inputs), + ) + val manifest = CallsClassStartManifest( + toolRevision = CallsBuildIdentity.toolRevision, + nativeFrontendRevision = CallsBuildIdentity.nativeFrontendRevision, + ledgerSha256 = "b".repeat(64), + expectedClassCount = 1, + budgetMillis = 30_000L, + collectedStatesLimit = null, + profile = CallsExperimentProfile.EMPTY_FRESH, + classes = listOf(case), + automaticLifecycles = true, + ) + val manifestPath = directory.resolve("manifest.json") + Files.writeString(manifestPath, encodeClassStartManifest(manifest)) + val probeDirectory = directory.resolve("probe") + + runClassSymbolicProbe(listOf(manifestPath.toString(), case.classId, probeDirectory.toString())) + + val json = CallsExperimentJson.json + val resultPath = probeDirectory.resolve("result.json") + val result = json.decodeFromString(Files.readString(resultPath)) + assertFalse(result.engineFailed) + val journal = assertNotNull(result.rawAnalysis?.inputCandidates) + val candidates = Files.newBufferedReader(probeDirectory.resolve(journal.path)).useLines { lines -> + lines.map { json.decodeFromString(it) } + .filter { it.returnedCallableScenario?.factoryMethod == factoryMethod } + .toList() + } + return LifecycleProbe(manifestPath, case.classId, probeDirectory, candidates) + } + + private data class LifecycleProbe( + val manifestPath: Path, + val classId: String, + val probeDirectory: Path, + val candidates: List, + ) { + fun replay( + candidate: CallsClassInputCandidate, + generatedInputDouble: Boolean = false, + ): CallsReturnedCallableReplayResult = + replayReturnedCallableCandidate( + manifestPath = manifestPath, + classId = classId, + probeDirectory = probeDirectory, + stateId = candidate.stateId, + generatedInputDouble = generatedInputDouble, + ) + } +} diff --git a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckRuntime.kt b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckRuntime.kt index 51d4514aa0..3f336cb553 100644 --- a/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckRuntime.kt +++ b/usvm-ts-fast-check/src/main/kotlin/org/usvm/ts/pbt/fastcheck/FastCheckRuntime.kt @@ -9,6 +9,9 @@ object FastCheckRuntime { /** Passive JSON serializer shared by generated replay wrappers and the adapter protocol. */ fun protocolJsonModule(): Path = locateEntryPoint("protocol-json.js") + /** Lossless tagged JavaScript value codec used by replay wrappers. */ + fun concreteValueModule(): Path = locateEntryPoint("js-value.js") + internal fun executionEntryPoint(): Path = locateEntryPoint(EXECUTION_CLI) internal fun projectionEntryPoint(): Path = locateEntryPoint(PROJECTION_CLI)