diff --git a/buildSrc/src/main/kotlin/Dependencies.kt b/buildSrc/src/main/kotlin/Dependencies.kt index fa3a6c9aca..d557245c22 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 = "4251d2023d" + const val jacodb = "a797c890" 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/TsInterpreterObserver.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/TsInterpreterObserver.kt index 4963a96d69..988a9fbbd9 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/TsInterpreterObserver.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/TsInterpreterObserver.kt @@ -163,4 +163,5 @@ enum class TsRuntimeFeatureLimitationReason { ARRAY_LENGTH_CAPACITY, ARRAY_LENGTH_GROWTH, STRING_ITERATOR_UNSUPPORTED, + OBJECT_METHOD_RECEIVER, } diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/TsExprResolver.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/TsExprResolver.kt index 05a2b4314c..d163fd1c4b 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/TsExprResolver.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/TsExprResolver.kt @@ -1302,6 +1302,11 @@ class TsExprResolver( ref: UConcreteHeapRef, operation: RuntimeConstructorOperation, ): Nothing? = with(ctx) { + val function = scope.calcOnState { associatedFunction[ref] } + val attemptsToConstructMethod = operation == RuntimeConstructorOperation.NEW && + function?.method?.isObjectLiteralMethod == true + if (attemptsToConstructMethod) return throwTypeError() + val objectType = if (isAllocatedConcreteHeapRef(ref)) { scope.calcOnState { memory.typeStreamOf(ref).singleOrNull() } } else { @@ -1320,10 +1325,8 @@ class TsExprResolver( ancestor.methods.any { it.name == "%computed" || it.name == "Symbol.hasInstance" } || ancestor.fields.any { it.name == "%computed" || it.name == "Symbol.hasInstance" } } - val isFunction = scope.calcOnState { associatedFunction[ref] != null } - val mayHandleInstanceof = operation == RuntimeConstructorOperation.INSTANCEOF && hasComputedMember - val isKnownNonConstructor = ordinaryObject && !mayHandleInstanceof && !isFunction + val isKnownNonConstructor = ordinaryObject && !mayHandleInstanceof && function == null if (isKnownNonConstructor) return throwTypeError() } @@ -1409,6 +1412,16 @@ class TsExprResolver( val explicitReceiver = expr.receiver val boundInstance = callee.thisInstance + val needsSloppyGlobalReceiver = callee.method.isObjectLiteralMethod && + callee.method.isStrictMode != true && explicitReceiver == null && boundInstance == null + if (needsSloppyGlobalReceiver) { + stopRuntimeFeatureLimitation( + reason = TsRuntimeFeatureLimitationReason.OBJECT_METHOD_RECEIVER, + detail = "A detached sloppy object method requires the JavaScript global receiver", + ) + return null + } + val instance = if (boundInstance != null) { boundInstance } else if (explicitReceiver != null) { diff --git a/usvm-ts/src/test/kotlin/org/usvm/samples/lang/ObjectLiteralMethodBoundariesTest.kt b/usvm-ts/src/test/kotlin/org/usvm/samples/lang/ObjectLiteralMethodBoundariesTest.kt new file mode 100644 index 0000000000..a65d414162 --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/samples/lang/ObjectLiteralMethodBoundariesTest.kt @@ -0,0 +1,59 @@ +package org.usvm.samples.lang + +import org.jacodb.ets.model.EtsScene +import org.jacodb.ets.utils.DEFAULT_ARK_CLASS_NAME +import org.junit.jupiter.api.Test +import org.usvm.api.TsTestValue +import org.usvm.machine.TsMachine +import org.usvm.machine.TsOptions +import org.usvm.machine.TsRuntimeFeatureLimitationReason +import org.usvm.machine.call.TsResidualCallPolicy +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.eq +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ObjectLiteralMethodBoundariesTest : TsMethodTestRunner() { + override val scene: EtsScene = loadScene("/samples/lang/ObjectLiteralMethodBoundaries.ts") + + @Test + fun `a sloppy method uses its actual object receiver and reports missing global receiver on extraction`() { + val memberCall = getMethod(methodName = "callSloppyMember", className = DEFAULT_ARK_CLASS_NAME) + + discoverProperties( + method = memberCall, + { result -> result eq 3 }, + invariants = arrayOf({ result -> result eq 3 }), + ) + assertUnsupported( + methodName = "callSloppyDetached", + reason = TsRuntimeFeatureLimitationReason.OBJECT_METHOD_RECEIVER.name, + ) + } + + @Test + fun `a method with super is created and stops only if invoked`() { + val create = getMethod(methodName = "createMethodWithSuper", className = DEFAULT_ARK_CLASS_NAME) + + discoverProperties( + method = create, + { result -> result.value }, + invariants = arrayOf({ result -> result.value }), + ) + assertUnsupported(methodName = "callMethodWithSuper", reason = "super.toString") + } + + private fun assertUnsupported(methodName: String, reason: String) { + val entry = getMethod(methodName = methodName, className = DEFAULT_ARK_CLASS_NAME) + val options = options.copy(throwExceptionOnStepFailure = false) + val tsOptions = TsOptions(unknownCallFallback = TsResidualCallPolicy.FRESH_SYMBOLIC_RETURN) + + val result = TsMachine(scene = scene, options = options, tsOptions = tsOptions).use { machine -> + machine.analyzeWithMetadata(methods = listOf(entry)) + } + + assertFalse(result.engineFailed) + assertTrue(result.states.isEmpty(), result.toString()) + assertTrue(result.unsupportedPaths.any { reason in it }, result.unsupportedPaths.toString()) + } +} diff --git a/usvm-ts/src/test/kotlin/org/usvm/samples/lang/ObjectLiteralMethodsTest.kt b/usvm-ts/src/test/kotlin/org/usvm/samples/lang/ObjectLiteralMethodsTest.kt new file mode 100644 index 0000000000..b40e5a69ff --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/samples/lang/ObjectLiteralMethodsTest.kt @@ -0,0 +1,179 @@ +package org.usvm.samples.lang + +import org.jacodb.ets.model.EtsMethod +import org.jacodb.ets.model.EtsScene +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.usvm.StateCollectionStrategy +import org.usvm.UMachineOptions +import org.usvm.api.TsTest +import org.usvm.api.TsTestValue +import org.usvm.machine.TS_TYPE_ERROR_TYPE +import org.usvm.machine.TsAnalysisStopReason +import org.usvm.machine.TsMachine +import org.usvm.machine.call.TsCompatibilityUnknownCallDispatcher +import org.usvm.machine.state.TsMethodResult +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.TsTestResolver +import org.usvm.util.assertNodeReplay +import org.usvm.util.eq +import org.usvm.util.getResourcePath +import java.nio.file.Path +import kotlin.io.path.readText +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +class ObjectLiteralMethodsTest : TsMethodTestRunner() { + @TempDir + lateinit var directory: Path + + override val scene: EtsScene = loadScene(sourcePath) + + init { + options = options.copy( + timeout = 33.seconds, + stateCollectionStrategy = StateCollectionStrategy.ALL, + stopOnCoverage = 0, + ) + } + + override val runner: (EtsMethod, UMachineOptions) -> List = { method, machineOptions -> + TsMachine(scene, machineOptions, tsOptions, unknownCallDispatcher = TsCompatibilityUnknownCallDispatcher) + .use { machine -> + val analysis = machine.analyzeWithMetadata(methods = listOf(method)) + assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason, method.name) + assertFalse(analysis.engineFailed, method.name) + assertFalse(analysis.unsupportedCall, method.name) + assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString()) + + analysis.states.map { TsTestResolver().resolve(method, it) } + } + } + + @Test + fun `stored methods are stable on one object and fresh on each evaluation`() { + assertTrueResult("identity") + } + + @Test + fun `member calls use the current receiver and extracted calls get undefined this`() { + assertNumberResult("receiver", expected = 389) + assertNumberResult("replacingAnOwnMethod", expected = 58) + } + + @Test + fun `method and arrow bodies share the enclosing mutable binding`() { + assertNumberResult("sharedCapture", expected = 777) + } + + @Test + fun `method allocation preserves neighboring property evaluation order`() { + assertNumberResult("propertyOrder", expected = 12345) + } + + @Test + fun `async bodies run only on invocation`() { + assertTrueResult("asyncDeclaration") + assertNumberResult("asyncInvocation", expected = 1) + } + + @Test + fun `object methods throw TypeError when used as constructors`() { + val method = getMethod("notConstructable", className = "ObjectLiteralMethods") + + val analysis = TsMachine(scene, options, tsOptions).use { machine -> + machine.analyzeWithMetadata(methods = listOf(method)) + } + + assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason) + assertFalse(analysis.engineFailed) + assertFalse(analysis.unsupportedCall) + assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString()) + val result = assertIs(analysis.states.single().methodResult) + assertEquals(TS_TYPE_ERROR_TYPE, result.type) + } + + @Test + fun `computed keys spread and accessor keep explicit unsupported outcomes`() { + val expectedDiagnostics = mapOf( + "computedKeyOrder" to "Data property requires a constant string key", + "spreadOrder" to "copyDataProperties", + "accessor" to "defineAccessor", + ) + + for ((name, expected) in expectedDiagnostics) { + val method = getMethod(name, className = "ObjectLiteralMethods") + val analysis = TsMachine(scene, options, tsOptions).use { machine -> + machine.analyzeWithMetadata(methods = listOf(method)) + } + + assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason, name) + assertFalse(analysis.engineFailed, name) + assertTrue(analysis.states.isEmpty(), name) + val hasUnsupportedStatement = analysis.unsupportedPaths.any { expected in it } + assertTrue(hasUnsupportedStatement, "$name: ${analysis.unsupportedPaths}") + } + } + + @Test + fun `native Node confirms method results and object evaluation order`() { + val assertions = """ + const fixture = new ObjectLiteralMethods(); + const expected = { + identity: true, + receiver: 389, + replacingAnOwnMethod: 58, + sharedCapture: 777, + propertyOrder: 12345, + computedKeyOrder: 123456, + spreadOrder: 1237, + accessor: 4, + asyncDeclaration: true, + asyncInvocation: 1, + }; + for (const [name, result] of Object.entries(expected)) { + if (fixture[name]() !== result) throw Error(name); + } + + let constructionError; + try { + fixture.notConstructable(); + } catch (error) { + constructionError = error; + } + if (!(constructionError instanceof TypeError)) throw Error("notConstructable"); + """.trimIndent() + + assertNodeReplay( + source = getResourcePath(sourcePath).readText() + "\n" + assertions, + directory = directory, + name = "object-literal-methods", + timeoutMessage = "Native object literal method checks timed out", + ) + } + + private fun assertTrueResult(name: String) { + val method = getMethod(name, className = "ObjectLiteralMethods") + discoverProperties( + method = method, + { result -> result.value }, + invariants = arrayOf({ result -> result.value }), + ) + } + + private fun assertNumberResult(name: String, expected: Int) { + val method = getMethod(name, className = "ObjectLiteralMethods") + discoverProperties( + method = method, + { result -> result eq expected }, + invariants = arrayOf({ result -> result eq expected }), + ) + } + + private companion object { + const val sourcePath = "/samples/lang/ObjectLiteralMethods.ts" + } +} diff --git a/usvm-ts/src/test/kotlin/org/usvm/samples/lang/SharedCaptureBindingsTest.kt b/usvm-ts/src/test/kotlin/org/usvm/samples/lang/SharedCaptureBindingsTest.kt new file mode 100644 index 0000000000..11321299f0 --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/samples/lang/SharedCaptureBindingsTest.kt @@ -0,0 +1,83 @@ +package org.usvm.samples.lang + +import org.jacodb.ets.model.EtsScene +import org.jacodb.ets.utils.EtsIrProvider +import org.jacodb.ets.utils.loadEtsFileAutoConvert +import org.junit.jupiter.api.Test +import org.usvm.api.TsTestValue +import org.usvm.machine.TsMachine +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.eq +import org.usvm.util.getResourcePath +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SharedCaptureBindingsTest : TsMethodTestRunner() { + override val scene = EtsScene( + listOf( + loadEtsFileAutoConvert( + path = getResourcePath(res = "/samples/lang/SharedCaptureBindings.ts"), + provider = EtsIrProvider.TS_FRONTEND, + ), + ), + ) + + @Test + fun `parameters uninitialized lets and deferred self captures share cells across calls`() { + for (name in listOf("parameterCell", "uninitializedCell", "deferredSelfCapture")) { + val method = getMethod(methodName = name, className = "SharedCaptureBindings") + + discoverProperties( + method = method, + { result -> result.number == 2.0 }, + invariants = arrayOf({ result -> result.number == 2.0 }), + ) + } + } + + @Test + fun `potential eager self-reference during lexical initialization stays unsupported`() { + val method = getMethod(methodName = "eagerSelfCapture", className = "SharedCaptureBindings") + + val outcome = TsMachine(scene = scene, options = options, tsOptions = tsOptions).use { machine -> + machine.analyzeWithMetadata(methods = listOf(method)) + } + + assertFalse(outcome.engineFailed) + assertTrue(outcome.states.isEmpty()) + assertTrue(outcome.unsupportedPaths.isNotEmpty()) + } + + @Test + fun `writes in the declaring method and in nested closures reach sibling closures`() { + val method = getMethod(methodName = "siblingsAndEnclosing", className = "SharedCaptureBindings") + + discoverProperties( + method = method, + { value -> value eq 466 }, + invariants = arrayOf({ value -> value eq 466 }), + ) + } + + @Test + fun `separate invocations initialize independent bindings`() { + val method = getMethod(methodName = "separateInvocations", className = "SharedCaptureBindings") + + discoverProperties( + method = method, + { value -> value eq 313 }, + invariants = arrayOf({ value -> value eq 313 }), + ) + } + + @Test + fun `each execution of a block creates a fresh binding for escaping closures`() { + val method = getMethod(methodName = "reenterBlock", className = "SharedCaptureBindings") + + discoverProperties( + method = method, + { value -> value eq 1011 }, + invariants = arrayOf({ value -> value eq 1011 }), + ) + } +} diff --git a/usvm-ts/src/test/resources/samples/lang/ObjectLiteralMethodBoundaries.ts b/usvm-ts/src/test/resources/samples/lang/ObjectLiteralMethodBoundaries.ts new file mode 100644 index 0000000000..5b10caa8fa --- /dev/null +++ b/usvm-ts/src/test/resources/samples/lang/ObjectLiteralMethodBoundaries.ts @@ -0,0 +1,36 @@ +function makeObject() { + return { + value: 3, + read() { + return this.value; + }, + }; +} + +function callSloppyMember() { + const object = makeObject(); + return object.read(); +} + +function callSloppyDetached() { + const read = makeObject().read; + return read(); +} + +function makeObjectWithSuper() { + return { + render() { + return super.toString(); + }, + }; +} + +function createMethodWithSuper() { + const object = makeObjectWithSuper(); + return typeof object.render === "function"; +} + +function callMethodWithSuper() { + const object = makeObjectWithSuper(); + return object.render(); +} diff --git a/usvm-ts/src/test/resources/samples/lang/ObjectLiteralMethods.ts b/usvm-ts/src/test/resources/samples/lang/ObjectLiteralMethods.ts new file mode 100644 index 0000000000..619add37ce --- /dev/null +++ b/usvm-ts/src/test/resources/samples/lang/ObjectLiteralMethods.ts @@ -0,0 +1,144 @@ +function createReader(value: number) { + return { + value, + read(): number { + if (this === undefined) return -1; + + return this.value; + }, + }; +} + +export class ObjectLiteralMethods { + identity(): boolean { + const first = createReader(3); + const second = createReader(3); + const read = first.read; + + return read === first.read && read !== second.read; + } + + receiver(): number { + const original = createReader(3); + const borrowed = { value: 9, read: original.read }; + const detached = original.read; + + return original.read() * 100 + borrowed.read() * 10 + detached(); + } + + replacingAnOwnMethod(): number { + const subject = { read() { return 5; } }; + const old = subject.read; + subject.read = () => 8; + + return old() * 10 + subject.read(); + } + + sharedCapture(): number { + let value = 1; + const subject = { + increase() { value += 2; }, + read() { return value; }, + }; + const arrow = () => value; + value = 5; + subject.increase(); + + return 100 * subject.read() + 10 * arrow() + value; + } + + propertyOrder(): number { + const effects = { trace: 1 }; + const subject = { + before: (effects.trace = effects.trace * 10 + 2), + read() { + effects.trace = effects.trace * 10 + 5; + return effects.trace; + }, + after: (effects.trace = effects.trace * 10 + 3), + }; + effects.trace = effects.trace * 10 + 4; + + return subject.read(); + } + + computedKeyOrder(): number { + const effects = { trace: 1 }; + const key = (): "read" => { + effects.trace = effects.trace * 10 + 3; + return "read"; + }; + const subject = { + before: (effects.trace = effects.trace * 10 + 2), + [key()]() { + effects.trace = effects.trace * 10 + 6; + return effects.trace; + }, + after: (effects.trace = effects.trace * 10 + 4), + }; + effects.trace = effects.trace * 10 + 5; + + return subject.read(); + } + + spreadOrder(): number { + const effects = { trace: 0 }; + const spread = () => { + effects.trace = effects.trace * 10 + 2; + return { read: () => 7 }; + }; + const subject = { + first: (effects.trace = effects.trace * 10 + 1), + read() { return 1; }, + ...spread(), + last: (effects.trace = effects.trace * 10 + 3), + }; + + return effects.trace * 10 + subject.read(); + } + + accessor(): number { + const subject = { + value() { return 4; }, + get read() { return this.value(); }, + }; + + return subject.read; + } + + asyncDeclaration(): boolean { + const effects = { calls: 0 }; + const subject = { + async read(): Promise { + effects.calls += 1; + throw 47; + }, + }; + const stored = subject.read; + + return effects.calls === 0 && stored === subject.read; + } + + asyncInvocation(): number { + const effects = { calls: 0 }; + const subject = { + async read(): Promise { + effects.calls += 1; + return 23; + }, + }; + const pending = subject.read(); + + return typeof pending === "object" ? effects.calls : -1; + } + + notConstructable(): never { + const subject = { + read() { throw 47; }, + }; + const ctor: any = subject.read; + + new ctor(); + throw 91; + } +} diff --git a/usvm-ts/src/test/resources/samples/lang/SharedCaptureBindings.ts b/usvm-ts/src/test/resources/samples/lang/SharedCaptureBindings.ts new file mode 100644 index 0000000000..1945f9dc95 --- /dev/null +++ b/usvm-ts/src/test/resources/samples/lang/SharedCaptureBindings.ts @@ -0,0 +1,71 @@ +class SharedCaptureBindings { + parameterCell(): number { + function make(count: number) { + return { increment() { ++count; }, read() { return count; } }; + } + const pair = make(1); + pair.increment(); + return pair.read(); + } + + uninitializedCell(): number { + let count: number | undefined; + const pair = { read() { return count; } }; + if (pair.read() !== undefined) return -1; + count = 1; + return pair.read() === 1 ? pair.read() + 1 : -2; + } + + deferredSelfCapture(): number { + let counter = { read() { return counter.value; }, value: 1 }; + const original = counter; + counter = { read() { return 2; }, value: 2 }; + return original.read(); + } + + eagerSelfCapture(): number { + const counter = { read() { return counter.value; }, value: (() => counter.read())() }; + return counter.read(); + } + + siblingsAndEnclosing(): number { + let value = 1; + const read = () => value; + const makeUpdate = () => () => { value += 2; }; + const update = makeUpdate(); + + value = 4; + const before = read(); + update(); + + return 100 * before + 10 * read() + value; + } + + separateInvocations(): number { + const first = this.makeCounter(1); + const second = this.makeCounter(10); + + return 100 * first() + 10 * second() + first(); + } + + private makeCounter(seed: number): () => number { + let value = seed; + return () => ++value; + } + + reenterBlock(): number { + const readers: (() => number)[] = []; + for (let i = 0; i < 2; ++i) { + let value = i; + const read = () => value; + const update = () => { value += 10; }; + + readers.push(read); + update(); + } + + const first = readers[0]; + const second = readers[1]; + return 100 * first() + second(); + } +}