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 95800a3bd7..02f9fc3c77 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 @@ -45,6 +45,7 @@ internal data class CallsClassInputCandidate( val environmentLimitations: List, val nativeReplayValidated: Boolean = false, val returnedCallableScenario: CallsReturnedCallableScenario? = null, + val directEntryFreshResidualCalls: Int? = null, val predictedReturn: CallsConcreteReturnedValue? = null, val returnExtractionLimitation: String? = null, val inputMethodCalls: List = emptyList(), @@ -96,6 +97,7 @@ internal class CallsClassInputCandidates( output: Path, private val profile: CallsExperimentProfile, private val returnedCallableScenarios: Map = emptyMap(), + private val directEntriesToRecord: Set = emptySet(), ) { private val candidates = InputJournal(path = output.resolve("input-candidates.jsonl")) private val failures = InputJournal(path = output.resolve("input-extraction-failures.jsonl")) @@ -183,7 +185,9 @@ internal class CallsClassInputCandidates( val method = state.entrypoint val returnedCallablePlan = returnedCallableScenarios[method] val enteredCallable = returnedCallablePlan?.enteredCallable(state) - val resolveMethodCalls = enteredCallable != null && state.freshResidualCallCount > 0 + val directEntry = method in directEntriesToRecord + val observeBehavior = directEntry || enteredCallable != null + val resolveMethodCalls = observeBehavior && state.freshResidualCallCount > 0 val environment = resolveOriginalEnvironment(state = state, resolveMethodCalls = resolveMethodCalls) val inputs = environment.inputs val suspended = outcome != "RETURNED" && outcome != "THREW" @@ -191,7 +195,7 @@ internal class CallsClassInputCandidates( val returnedCallable = returnedCallablePlan?.let { scenario -> describeReturnedCallable(scenario, enteredCallable, state, inputHeap = inputs.heap) } - val predictedReturn = if (outcome == "RETURNED" && enteredCallable != null) { + val predictedReturn = if (outcome == "RETURNED" && observeBehavior) { runCatching { resolveReturnedValue(state) } } else { null @@ -229,6 +233,7 @@ internal class CallsClassInputCandidates( environmentComplete = environment.limitation == null, environmentLimitations = listOfNotNull(environment.limitation), returnedCallableScenario = returnedCallable, + directEntryFreshResidualCalls = if (directEntry) state.freshResidualCallCount else null, predictedReturn = predictedReturn?.getOrNull(), returnExtractionLimitation = resultFailure?.let { "${it::class.java.name}: ${it.message}" }, inputMethodCalls = inputs.methodCalls?.getOrNull().orEmpty(), 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 04ca3c468a..3faaf6e858 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 @@ -133,6 +133,7 @@ internal class ClassRawAnalysisObserver( private val retainRawStateDiagnostics: Boolean, private val profile: CallsExperimentProfile, returnedCallableScenarios: Map = emptyMap(), + directEntriesToRecord: Set = emptySet(), ) : UMachineObserver { private val universe = universe.toList() private val universePoints = this.universe.toSet() @@ -148,6 +149,7 @@ internal class ClassRawAnalysisObserver( output = output, profile = profile, returnedCallableScenarios = returnedCallableScenarios, + directEntriesToRecord = directEntriesToRecord, ) private val snapshotFailures = mutableListOf() private val methodSteps = linkedMapOf() @@ -424,6 +426,7 @@ internal class ClassRawAnalysisObserver( retainRawStateDiagnostics: Boolean, profile: CallsExperimentProfile, returnedCallableScenarios: Map = emptyMap(), + directEntriesToRecord: Set = emptySet(), ): ClassRawAnalysisObserver { val target = methods.first().signature.enclosingClass val universe = methods.flatMap { it.cfg.stmts }.filter { @@ -436,6 +439,7 @@ internal class ClassRawAnalysisObserver( retainRawStateDiagnostics = retainRawStateDiagnostics, profile = profile, returnedCallableScenarios = returnedCallableScenarios, + directEntriesToRecord = directEntriesToRecord, ) } } 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 f44fadf9a2..d7ea6ceddf 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 @@ -14,6 +14,8 @@ import org.jacodb.ets.model.EtsReturnStmt import org.jacodb.ets.model.EtsStmt import org.jacodb.ets.model.EtsThrowStmt import org.jacodb.ets.utils.ANONYMOUS_METHOD_PREFIX +import org.jacodb.ets.utils.INSTANCE_INIT_METHOD_NAME +import org.jacodb.ets.utils.STATIC_INIT_METHOD_NAME import org.jacodb.ets.utils.loadEtsProjectFromIR import org.usvm.CoverageZone import org.usvm.PathSelectionStrategy @@ -102,6 +104,7 @@ internal data class CallsClassStartManifest( val classes: List, val retainRawStateDiagnostics: Boolean = false, val automaticLifecycles: Boolean = false, + val recordDirectEntryCalls: Boolean = false, val frozenModelIds: Set? = null, val maxInputCollectionSize: Int? = null, ) { @@ -503,6 +506,13 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { } val automaticMethods = lifecycle?.methods.orEmpty() automaticEntryPoints = automaticMethods.map { it.signature.toString() } + val directEntriesToRecord = if (exploratory && manifest.recordDirectEntryCalls) { + independentMethods.filterTo(mutableSetOf()) { method -> + method.name != INSTANCE_INIT_METHOD_NAME && method.name != STATIC_INIT_METHOD_NAME + } + } else { + emptySet() + } val analysisMethods = independentMethods + automaticMethods require(analysisMethods.isNotEmpty()) { "Target class has no independently bindable entry points" } val raw = if (exploratory) { @@ -513,6 +523,7 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { output = output, retainRawStateDiagnostics = manifest.retainRawStateDiagnostics, returnedCallableScenarios = lifecycle?.returnedCallableScenarios.orEmpty(), + directEntriesToRecord = directEntriesToRecord, profile = manifest.profile, ) } else { @@ -634,7 +645,8 @@ private fun runRawClassAnalysis(args: List, exploratory: Boolean) { outcome = machine.analyzeWithMetadata( methods = analysisMethods, configureInitialState = { method, state -> - if (lifecycle?.returnedCallableScenarios?.containsKey(method) == true) { + val returnedCallable = lifecycle?.returnedCallableScenarios?.containsKey(method) == true + if (returnedCallable || method in directEntriesToRecord) { state.recordFreshInputMethodsForReplay() } machineObserver.registerInitialState(method = method, state = state) diff --git a/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsDirectEntryJournalTest.kt b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsDirectEntryJournalTest.kt new file mode 100644 index 0000000000..9e71f24cba --- /dev/null +++ b/usvm-ts-calls/src/test/kotlin/org/usvm/ts/calls/CallsDirectEntryJournalTest.kt @@ -0,0 +1,128 @@ +package org.usvm.ts.calls + +import org.jacodb.ets.utils.INSTANCE_INIT_METHOD_NAME +import org.jacodb.ets.utils.STATIC_INIT_METHOD_NAME +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 CallsDirectEntryJournalTest { + @TempDir + lateinit var directory: Path + + @Test + fun `direct entries record original input calls and successful return only when enabled`() { + val inputs = Files.createDirectory(directory.resolve("inputs")) + val source = """ + export class DirectEntry { + value = 7; + + static chooseTwice(adapter: any): number { + const first = adapter.choose(11); + if (first !== 7) throw first; + + const second = adapter.choose(first); + if (second !== 5) throw second; + return 23; + } + + static localReceiver(): number { + const local: any = {}; + return local.choose(11); + } + } + """.trimIndent() + Files.writeString(inputs.resolve("DirectEntry.ts"), source) + val case = CallsClassStartCase( + classId = "direct-entry", + identity = "fixture@DirectEntry", + projectRevision = "a".repeat(40), + sourceRoot = inputs.toString(), + sourceFile = "DirectEntry.ts", + className = "DirectEntry", + 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), + ) + + val ordinary = probe(manifest) + val recorded = probe(manifest.copy(recordDirectEntryCalls = true)) + + val defaultReturns = ordinary.filter { it.methodName == "chooseTwice" } + assertTrue(defaultReturns.any { it.completion == CallsCoverageCompletion.RETURNED }) + val recordingDisabled = ordinary.all { + it.directEntryFreshResidualCalls == null && it.predictedReturn == null && it.inputMethodCalls.isEmpty() + } + assertTrue(recordingDisabled) + + val initializerNames = setOf(INSTANCE_INIT_METHOD_NAME, STATIC_INIT_METHOD_NAME) + val initializers = recorded.filter { it.methodName in initializerNames } + assertTrue(initializers.isNotEmpty()) + assertTrue(initializers.all { it.directEntryFreshResidualCalls == null && it.predictedReturn == null }) + + val choices = recorded.filter { it.methodName == "chooseTwice" } + val completed = choices.filter { + it.completion == CallsCoverageCompletion.RETURNED && it.inputMethodExtractionLimitation == null + } + assertTrue(completed.isNotEmpty()) + for (success in completed) { + val receiver = assertNotNull(success.inputs.arguments.single().objectId) + assertEquals(expected = 2, actual = success.directEntryFreshResidualCalls) + assertEquals(listOf(receiver, receiver), success.inputMethodCalls.map { it.receiverObjectId }) + assertEquals(listOf("choose", "choose"), success.inputMethodCalls.map { it.methodName }) + val arguments = success.inputMethodCalls.map { it.arguments.single().primitive } + val returns = success.inputMethodCalls.map { it.returnedValue.primitive } + assertEquals(listOf(11.0, 7.0).map(JsConcreteValue::number), arguments) + assertEquals(listOf(7.0, 5.0).map(JsConcreteValue::number), returns) + assertEquals(JsConcreteValue.number(23.0), success.predictedReturn?.value?.primitive) + assertNull(success.inputMethodExtractionLimitation) + assertFalse(success.nativeReplayValidated) + } + + val throws = choices.filter { it.completion == CallsCoverageCompletion.THREW } + assertTrue(throws.isNotEmpty()) + assertTrue(throws.all { it.predictedReturn == null }) + + val localReturns = recorded.filter { + it.methodName == "localReceiver" && it.completion == CallsCoverageCompletion.RETURNED + } + assertTrue(localReturns.isNotEmpty()) + for (local in localReturns) { + assertEquals(expected = 1, actual = local.directEntryFreshResidualCalls) + assertTrue(local.inputMethodCalls.isEmpty()) + assertNotNull(local.inputMethodExtractionLimitation) + } + } + + private fun probe(manifest: CallsClassStartManifest): List { + val root = Files.createTempDirectory(directory, "probe-") + val manifestPath = root.resolve("manifest.json") + val output = root.resolve("output") + Files.writeString(manifestPath, encodeClassStartManifest(manifest)) + + runClassSymbolicProbe(listOf(manifestPath.toString(), manifest.classes.single().classId, output.toString())) + + val json = CallsExperimentJson.json + val result = json.decodeFromString(Files.readString(output.resolve("result.json"))) + assertFalse(result.engineFailed) + val journal = assertNotNull(result.rawAnalysis?.inputCandidates) + return Files.newBufferedReader(output.resolve(journal.path)).useLines { lines -> + lines.map { json.decodeFromString(it) }.toList() + } + } +}