diff --git a/buildSrc/src/main/kotlin/Dependencies.kt b/buildSrc/src/main/kotlin/Dependencies.kt index 4e94f7b95a..c536d1e14f 100644 --- a/buildSrc/src/main/kotlin/Dependencies.kt +++ b/buildSrc/src/main/kotlin/Dependencies.kt @@ -6,7 +6,7 @@ object Versions { const val clikt = "5.0.0" const val detekt = "1.23.7" const val ini4j = "0.5.4" - const val jacodb = "0fac32c8c5" + const val jacodb = "1332879057" const val juliet = "1.3.2" const val junit = "5.9.3" const val kotlin = "2.1.0" diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/ArrayIterator.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/ArrayIterator.kt index 7eba4f05e6..558592db06 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/ArrayIterator.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/ArrayIterator.kt @@ -37,10 +37,21 @@ internal fun TsExprResolver.tryApproximateBuiltinIteratorCall( stmt: TsVirtualMethodCallStmt, ): TsExprApproximationResult = with(ctx) { if (stmt.call.wellKnownSymbol == EtsWellKnownSymbol.ITERATOR) { + val reference = stmt.instance as? UConcreteHeapRef + val nativeIterator = scope.calcOnState { + arrayIterators[reference] != null || stringIterators[reference] != null + } + if (nativeIterator) return TsExprApproximationResult.from(reference) + val string = tryCreateStringIterator(stmt) if (string !is TsExprApproximationResult.NoApproximation) return string - return TsExprApproximationResult.from(createArrayIterator(stmt)) + if (stmt.instance.sort != addressSort) return TsExprApproximationResult.NoApproximation + + val array = stmt.instance.asExpr(addressSort) + val arrayType = scope.calcOnState { arrayStorageType(array, stmt.call.instance.type) } as? EtsArrayType + ?: return TsExprApproximationResult.NoApproximation + return TsExprApproximationResult.from(createArrayIterator(array, arrayType)) } val reference = stmt.instance as? UConcreteHeapRef ?: return TsExprApproximationResult.NoApproximation @@ -54,19 +65,7 @@ internal fun TsExprResolver.tryApproximateBuiltinIteratorCall( TsExprApproximationResult.from(advanceArrayIterator(reference, arrayIterator)) } -private fun TsExprResolver.createArrayIterator(stmt: TsVirtualMethodCallStmt): UHeapRef? = with(ctx) { - if (stmt.instance.sort != addressSort) { - unsupportedArrayIterator("The intrinsic iterator requires a modeled runtime array") - return null - } - - val array = stmt.instance.asExpr(addressSort) - val arrayType = scope.calcOnState { arrayStorageType(array, stmt.call.instance.type) } as? EtsArrayType - if (arrayType == null) { - unsupportedArrayIterator("Custom and non-array iterators are not modeled") - return null - } - +private fun TsExprResolver.createArrayIterator(array: UHeapRef, arrayType: EtsArrayType): UHeapRef? = with(ctx) { val runtimeArray = scope.calcOnState { memory.types.evalIsSubtype(array, arrayType) } if (scope.checkSat(mkNot(runtimeArray)) != null) { reportRuntimeFeatureLimitation( diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/ProjectIteratorDispatch.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/ProjectIteratorDispatch.kt new file mode 100644 index 0000000000..b4f6173b2a --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/ProjectIteratorDispatch.kt @@ -0,0 +1,89 @@ +package org.usvm.machine.interpreter + +import io.ksmt.utils.asExpr +import org.jacodb.ets.model.EtsClassType +import org.jacodb.ets.model.EtsWellKnownSymbol +import org.usvm.api.typeStreamOf +import org.usvm.machine.TsContext +import org.usvm.machine.TsInterpreterObserver +import org.usvm.machine.TsRuntimeFeatureLimitationEvent +import org.usvm.machine.TsRuntimeFeatureLimitationReason +import org.usvm.machine.TsVirtualMethodCallStmt +import org.usvm.machine.expr.TsExprResolver +import org.usvm.machine.onRuntimeFeatureLimitationSafely +import org.usvm.machine.state.TsState +import org.usvm.machine.state.lastStmt +import org.usvm.machine.state.newStmt +import org.usvm.types.TypesResult +import org.usvm.util.EtsHierarchy +import org.usvm.util.isResolved + +internal fun TsContext.tryDispatchProjectIterator( + scope: TsStepScope, + stmt: TsVirtualMethodCallStmt, + hierarchy: EtsHierarchy, + observer: TsInterpreterObserver?, + resolver: TsExprResolver, +): Boolean { + if (stmt.call.wellKnownSymbol != EtsWellKnownSymbol.ITERATOR) return false + + val reason = TsRuntimeFeatureLimitationReason.ARRAY_ITERATOR_UNSUPPORTED + val instance = stmt.instance + if (instance.sort != addressSort) { + resolver.stopRuntimeFeatureLimitation(reason = reason, detail = "No modeled iterator for this receiver") + return true + } + + val receiver = instance.asExpr(addressSort) + val types = scope.calcOnState { memory.typeStreamOf(receiver).take(scene.projectAndSdkClasses.size + 1) } + val projectTypes = if (types is TypesResult.SuccessfulTypesResult) { + types.types.filterIsInstance().distinct() + } else { + emptyList() + } + + val declaredType = stmt.call.instance.type as? EtsClassType + val declaredOwners = if (declaredType?.isResolved() == true) { + hierarchy.classesForType(declaredType) + } else { + emptyList() + } + val exactRuntimeType = if (types is TypesResult.SuccessfulTypesResult) { + types.types.singleOrNull() as? EtsClassType + } else { + null + } + + val targets = projectTypes.mapNotNull { type -> + val owner = hierarchy.classesForType(type).singleOrNull() ?: return@mapNotNull null + val hasOwnerEvidence = type == exactRuntimeType || + declaredOwners.any { it in hierarchy.getAncestors(owner) } + if (!hasOwnerEvidence) return@mapNotNull null + + val method = hierarchy.instanceSymbolMethod(owner, EtsWellKnownSymbol.ITERATOR) + ?: return@mapNotNull null + if (method.enclosingClass !in scene.projectClasses) return@mapNotNull null + + val matchesType = scope.calcOnState { + mkAnd(memory.types.evalIsSubtype(receiver, type), memory.types.evalIsSupertype(receiver, type)) + } + val enter: (TsState) -> Unit = { state -> state.newStmt(stmt.toConcrete(method)) } + matchesType to enter + } + + val detail = "No modeled or declared Symbol.iterator method for this receiver" + if (targets.isEmpty()) { + resolver.stopRuntimeFeatureLimitation(reason = reason, detail = detail) + return true + } + + val unmatched = mkNot(mkOr(targets.map { it.first })) + val unsupported: (TsState) -> Unit = { state -> + observer?.onRuntimeFeatureLimitationSafely( + TsRuntimeFeatureLimitationEvent(statement = state.lastStmt, reason = reason, detail = detail), + ) + state.terminateAsUnsupported(reason = "$reason: $detail") + } + scope.forkMulti(targets + (unmatched to unsupported)) + return true +} diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsInterpreter.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsInterpreter.kt index 22865401ac..1427c66765 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsInterpreter.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/interpreter/TsInterpreter.kt @@ -259,6 +259,9 @@ class TsInterpreter( TsExprApproximationResult.NoApproximation -> {} } + val iteratorDispatched = tryDispatchProjectIterator(scope, stmt, graph.hierarchy, observer, resolver) + if (iteratorDispatched) return + if (stmt.call.wellKnownSymbol != null) { throw UnsupportedOperationException("Symbol-keyed method dispatch requires a supported intrinsic receiver") } diff --git a/usvm-ts/src/main/kotlin/org/usvm/util/EtsHierarchy.kt b/usvm-ts/src/main/kotlin/org/usvm/util/EtsHierarchy.kt index 2255d25c52..8566fe6466 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/util/EtsHierarchy.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/util/EtsHierarchy.kt @@ -12,6 +12,7 @@ import org.jacodb.ets.model.EtsMethodSignature import org.jacodb.ets.model.EtsRefType import org.jacodb.ets.model.EtsScene import org.jacodb.ets.model.EtsUnclearRefType +import org.jacodb.ets.model.EtsWellKnownSymbol import kotlin.system.measureTimeMillis private val logger = KotlinLogging.logger { } @@ -102,6 +103,23 @@ class EtsHierarchy(private val scene: EtsScene) { } } + internal fun instanceSymbolMethod(clazz: EtsClass, symbol: EtsWellKnownSymbol): EtsMethod? { + var current = clazz + val visited = mutableSetOf() + while (visited.add(current)) { + val shadowsWithField = current.fields.any { !it.isStatic && it.signature.wellKnownSymbol == symbol } + if (shadowsWithField) return null + + val method = current.methods.firstOrNull { !it.isStatic && it.signature.wellKnownSymbol == symbol } + if (method != null) return method.takeUnless { it.isAccessor } + + val parent = current.superClass ?: return null + current = resolveClassesBySignature(parent).singleOrNull() ?: return null + } + + return null + } + /** Finds the closest instance declaration, preferring the class chain over interface declarations. */ fun nearestInstanceMethod(clazz: EtsClass, methodName: String): EtsMethod? { val classes = ArrayDeque() diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/expr/ArrayIteratorSourceTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/expr/ArrayIteratorSourceTest.kt index 59d3b04517..cc16119e16 100644 --- a/usvm-ts/src/test/kotlin/org/usvm/machine/expr/ArrayIteratorSourceTest.kt +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/expr/ArrayIteratorSourceTest.kt @@ -3,6 +3,7 @@ package org.usvm.machine.expr import org.jacodb.ets.model.EtsScene import org.jacodb.ets.utils.EtsIrProvider import org.jacodb.ets.utils.loadEtsFileAutoConvert +import org.usvm.StateCollectionStrategy import org.usvm.api.TsTestValue import org.usvm.machine.TsAnalysisStopReason import org.usvm.machine.TsInterpreterObserver @@ -27,6 +28,61 @@ class ArrayIteratorSourceTest : TsMethodTestRunner() { ) override val tsOptions = TsOptions(maxArraySize = 6) + init { + options = options.copy(stateCollectionStrategy = StateCollectionStrategy.ALL, stopOnCoverage = 0) + } + + @Test + fun `class iteration uses symbol identity and the nearest prototype implementation`() { + discoverProperties( + method = getMethod(methodName = "classIterators", className = "ArrayIteratorSource"), + { result -> result.number == 719.0 }, + invariants = arrayOf({ result -> result.number == 719.0 }), + ) + } + + @Test + fun `symbolic class inputs retain inherited and overridden iterator bodies`() { + discoverProperties( + method = getMethod(methodName = "iterateInput", className = "ArrayIteratorSource"), + { _, result -> result.number == 7.0 }, + { _, result -> result.number == 19.0 }, + invariants = arrayOf({ _, result -> result.number == 7.0 || result.number == 19.0 }), + ) + } + + @Test + fun `a symbolic own iterator shadow reports its unmatched branch`() { + val method = getMethod(methodName = "iterateInput", className = "ArrayIteratorSource") + val reasons = mutableListOf() + val observer = object : TsInterpreterObserver { + override fun onRuntimeFeatureLimitation(event: TsRuntimeFeatureLimitationEvent) { + reasons += event.reason + } + } + val limitation = TsRuntimeFeatureLimitationReason.ARRAY_ITERATOR_UNSUPPORTED + + val outcome = TsMachine(scene = scene, options = options, tsOptions = tsOptions, observer = observer).use { + it.analyzeWithMetadata(methods = listOf(method)) + } + + assertTrue(outcome.states.isNotEmpty()) + assertTrue(outcome.unsupportedPaths.any { limitation.name in it }) + assertEquals(listOf(limitation), reasons) + } + + @Test + fun `explicit iterator calls use the runtime symbol only for the library binding`() { + val cases = mapOf("explicitIteratorKey" to 1.0, "explicitShadowedKey" to 17.0) + for ((name, expected) in cases) { + discoverProperties( + method = getMethod(methodName = name, className = "ArrayIteratorSource"), + { result -> result.number == expected }, + invariants = arrayOf({ result -> result.number == expected }), + ) + } + } + @Test fun `native array iteration preserves values evaluation order and live length`() { val methods = listOf( diff --git a/usvm-ts/src/test/kotlin/org/usvm/samples/types/ComputedClassMembersTest.kt b/usvm-ts/src/test/kotlin/org/usvm/samples/types/ComputedClassMembersTest.kt index 2a01f5d98c..92fe86cc95 100644 --- a/usvm-ts/src/test/kotlin/org/usvm/samples/types/ComputedClassMembersTest.kt +++ b/usvm-ts/src/test/kotlin/org/usvm/samples/types/ComputedClassMembersTest.kt @@ -66,8 +66,8 @@ class ComputedClassMembersTest : TsMethodTestRunner() { } @Test - fun `symbol access is explicit unsupported instead of returning the string method result`() { - assertUnsupported("symbolMethod", reason = null) + fun `explicit iterator call selects the symbol method`() { + discoverConstant("symbolMethod", expected = 17.0) } @Test @@ -84,7 +84,7 @@ class ComputedClassMembersTest : TsMethodTestRunner() { ) } - private fun assertUnsupported(methodName: String, reason: String?) { + private fun assertUnsupported(methodName: String, reason: String) { val method = getMethod(methodName, className = "ComputedClassMembers") val result = TsMachine( scene = scene, @@ -100,10 +100,7 @@ class ComputedClassMembersTest : TsMethodTestRunner() { assertTrue(result.stopReason == TsAnalysisStopReason.EXHAUSTED, "$methodName: ${result.stopReason}") assertTrue(result.states.isEmpty(), methodName) assertFalse(result.engineFailed, methodName) - assertTrue(result.unsupportedPaths.isNotEmpty(), "$methodName: $result") - if (reason != null) { - assertTrue(result.unsupportedPaths.any { reason in it }, "$methodName: ${result.unsupportedPaths}") - } + assertTrue(result.unsupportedPaths.any { reason in it }, "$methodName: ${result.unsupportedPaths}") } private fun replay(assertions: String) { diff --git a/usvm-ts/src/test/resources/models/ArrayIteratorSource.ts b/usvm-ts/src/test/resources/models/ArrayIteratorSource.ts index 281efd3329..3adc466585 100644 --- a/usvm-ts/src/test/resources/models/ArrayIteratorSource.ts +++ b/usvm-ts/src/test/resources/models/ArrayIteratorSource.ts @@ -1,4 +1,67 @@ +class SingleValueIterator { + private exhausted = false; + + constructor(private readonly item: number) {} + + next(): { done: boolean; value: number } { + if (this.exhausted) return { done: true, value: 0 }; + + this.exhausted = true; + return { done: false, value: this.item }; + } +} + +class ClassIterable { + ["Symbol.iterator"](): SingleValueIterator { + return new SingleValueIterator(99); + } + + [Symbol.iterator](): SingleValueIterator { + return new SingleValueIterator(7); + } +} + +class DerivedIterable extends ClassIterable {} + +class OverridingIterable extends ClassIterable { + [Symbol.iterator](): SingleValueIterator { + return new SingleValueIterator(19); + } +} + +class ShadowingIterable extends ClassIterable { + // @ts-expect-error A data property hides the inherited method at runtime. + [Symbol.iterator] = undefined; +} + export class ArrayIteratorSource { + static classIterators(): number { + const inherited = [...new DerivedIterable()]; + const overridden = [...new OverridingIterable()]; + return inherited[0] * 100 + overridden[0]; + } + + static iterateInput(iterable: ClassIterable): number { + let result = 0; + for (const value of iterable) { + result += value; + } + return result; + } + + static explicitIteratorKey(): number { + const target = [11, 13]; + const iterator = target[Symbol.iterator](); + const same = iterator[Symbol.iterator](); + return same === iterator && same.next().value === 11 && iterator.next().value === 13 ? 1 : 0; + } + + static explicitShadowedKey(): number { + const Symbol = { iterator: "lookup" }; + const target = { lookup: (): number => 17 }; + return target[Symbol.iterator](); + } + static literalSpread(): number { const values = [7, 11]; const copy = [3, ...values, 13];