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 @@ -45,6 +45,7 @@ internal data class CallsClassInputCandidate(
val environmentLimitations: List<String>,
val nativeReplayValidated: Boolean = false,
val returnedCallableScenario: CallsReturnedCallableScenario? = null,
val directEntryFreshResidualCalls: Int? = null,
val predictedReturn: CallsConcreteReturnedValue? = null,
val returnExtractionLimitation: String? = null,
val inputMethodCalls: List<CallsConcreteInputMethodCall> = emptyList(),
Expand Down Expand Up @@ -96,6 +97,7 @@ internal class CallsClassInputCandidates(
output: Path,
private val profile: CallsExperimentProfile,
private val returnedCallableScenarios: Map<EtsMethod, TsReturnedCallableScenario> = emptyMap(),
private val directEntriesToRecord: Set<EtsMethod> = emptySet(),
) {
private val candidates = InputJournal(path = output.resolve("input-candidates.jsonl"))
private val failures = InputJournal(path = output.resolve("input-extraction-failures.jsonl"))
Expand Down Expand Up @@ -183,15 +185,17 @@ 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"
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) {
val predictedReturn = if (outcome == "RETURNED" && observeBehavior) {
runCatching { resolveReturnedValue(state) }
} else {
null
Expand Down Expand Up @@ -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(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ internal class ClassRawAnalysisObserver(
private val retainRawStateDiagnostics: Boolean,
private val profile: CallsExperimentProfile,
returnedCallableScenarios: Map<EtsMethod, TsReturnedCallableScenario> = emptyMap(),
directEntriesToRecord: Set<EtsMethod> = emptySet(),
) : UMachineObserver<TsState> {
private val universe = universe.toList()
private val universePoints = this.universe.toSet()
Expand All @@ -148,6 +149,7 @@ internal class ClassRawAnalysisObserver(
output = output,
profile = profile,
returnedCallableScenarios = returnedCallableScenarios,
directEntriesToRecord = directEntriesToRecord,
)
private val snapshotFailures = mutableListOf<String>()
private val methodSteps = linkedMapOf<String, Long>()
Expand Down Expand Up @@ -424,6 +426,7 @@ internal class ClassRawAnalysisObserver(
retainRawStateDiagnostics: Boolean,
profile: CallsExperimentProfile,
returnedCallableScenarios: Map<EtsMethod, TsReturnedCallableScenario> = emptyMap(),
directEntriesToRecord: Set<EtsMethod> = emptySet(),
): ClassRawAnalysisObserver {
val target = methods.first().signature.enclosingClass
val universe = methods.flatMap { it.cfg.stmts }.filter {
Expand All @@ -436,6 +439,7 @@ internal class ClassRawAnalysisObserver(
retainRawStateDiagnostics = retainRawStateDiagnostics,
profile = profile,
returnedCallableScenarios = returnedCallableScenarios,
directEntriesToRecord = directEntriesToRecord,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -102,6 +104,7 @@ internal data class CallsClassStartManifest(
val classes: List<CallsClassStartCase>,
val retainRawStateDiagnostics: Boolean = false,
val automaticLifecycles: Boolean = false,
val recordDirectEntryCalls: Boolean = false,
val frozenModelIds: Set<String>? = null,
val maxInputCollectionSize: Int? = null,
) {
Expand Down Expand Up @@ -503,6 +506,13 @@ private fun runRawClassAnalysis(args: List<String>, 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) {
Expand All @@ -513,6 +523,7 @@ private fun runRawClassAnalysis(args: List<String>, exploratory: Boolean) {
output = output,
retainRawStateDiagnostics = manifest.retainRawStateDiagnostics,
returnedCallableScenarios = lifecycle?.returnedCallableScenarios.orEmpty(),
directEntriesToRecord = directEntriesToRecord,
profile = manifest.profile,
)
} else {
Expand Down Expand Up @@ -634,7 +645,8 @@ private fun runRawClassAnalysis(args: List<String>, 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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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<CallsClassInputCandidate> {
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<CallsClassStartResult>(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<CallsClassInputCandidate>(it) }.toList()
}
}
}
Loading