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
2 changes: 1 addition & 1 deletion buildSrc/src/main/kotlin/Dependencies.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "d3625b1e34"
const val jacodb = "6127cd53"
const val juliet = "1.3.2"
const val junit = "5.9.3"
const val kotlin = "2.1.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.usvm.machine.call
import org.jacodb.ets.model.EtsAnyType
import org.jacodb.ets.model.EtsArrayType
import org.jacodb.ets.model.EtsClassSignature
import org.jacodb.ets.model.EtsFileSignature
import org.jacodb.ets.model.EtsFunctionType
import org.jacodb.ets.model.EtsLocal
import org.jacodb.ets.model.EtsMethodSignature
Expand All @@ -19,6 +20,12 @@ import org.usvm.UExpr
import org.usvm.machine.TsContext
import org.usvm.util.EtsHierarchy

/** Constructor binding emitted for a verified Set value from the bundled TypeScript library. */
internal val nativeSetConstructorSignature = EtsClassSignature(
name = "Set",
file = EtsFileSignature(projectName = "", fileName = "lib.es2015.collection.d.ts"),
)

internal fun hasBuiltinGlobalOwner(
owner: EtsValue,
callee: EtsMethodSignature,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import org.usvm.machine.call.TsUnknownCallModelSuccessor
import org.usvm.machine.call.TsUnknownCallTarget
import org.usvm.machine.call.hasBuiltinGlobalOwner
import org.usvm.machine.call.loadBundledEtsIrUnknownCallModelArtifact
import org.usvm.machine.call.nativeSetConstructorSignature
import org.usvm.machine.expr.TsCollectionKind
import org.usvm.machine.expr.newModeledCollection
import org.usvm.machine.state.TsState
Expand Down Expand Up @@ -84,16 +85,26 @@ internal object TsCollectionEtsIrModelFamily : TsBuiltInUnknownCallModelFamily {
private fun constructor(kind: TsCollectionKind, name: String): TsUnknownCallModel {
val entry = if (kind == TsCollectionKind.MAP) "mapConstructor" else "setConstructor"
val initialize = if (kind == TsCollectionKind.MAP) "initializeMap" else "initializeSet"
val signature = EtsClassSignature.UNKNOWN.copy(name = name)
val legacySignature = EtsClassSignature.UNKNOWN.copy(name = name)
return TsEtsIrUnknownCallModel(
id = "ts.${name.lowercase()}.constructor",
target = TsUnknownCallTarget(methodName = CONSTRUCTOR_NAME, enclosingClassName = name),
artifact = artifact(entry),
inputAdapter = TsEtsIrUnknownCallModelInputAdapter { state, call ->
val signature = call.callee.enclosingClass
val verifiedSet = kind == TsCollectionKind.SET && signature == nativeSetConstructorSignature
val legacy = signature == legacySignature
if (!verifiedSet && !legacy) return@TsEtsIrUnknownCallModelInputAdapter null

// An unresolved legacy owner cannot distinguish native storage from a project declaration.
val ambiguousLegacySet = kind == TsCollectionKind.SET && legacy &&
state.ctx.scene.projectClasses.any { it.name == name }
if (ambiguousLegacySet) return@TsEtsIrUnknownCallModelInputAdapter null

val receiver = call.receiver?.resolved as? UConcreteHeapRef
?: return@TsEtsIrUnknownCallModelInputAdapter null
val runtimeType = state.memory.typeStreamOf(receiver).singleOrNull()
if (call.callee.enclosingClass != signature || runtimeType != EtsClassType(signature)) {
if (runtimeType != EtsClassType(signature)) {
return@TsEtsIrUnknownCallModelInputAdapter null
}
val arguments = call.arguments.map { it.resolved ?: return@TsEtsIrUnknownCallModelInputAdapter null }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1569,9 +1569,9 @@ class TsExprResolver(
return@with allocateRegExpLiteral(checkNotNull(classType))
}

// Try to resolve the concrete type if possible.
// Otherwise, create an object with UnclearRefType
val resolvedType = if (expr.type.isResolved()) {
// Standard-library and project Set allocations can have the same name but different owners.
val isSetAllocation = classType?.signature?.name == "Set"
val resolvedType = if (!isSetAllocation && expr.type.isResolved()) {
scene.projectAndSdkClasses
.singleOrNull { it.name == expr.type.typeName }?.type
?: expr.type
Expand Down
6 changes: 4 additions & 2 deletions usvm-ts/src/main/kotlin/org/usvm/util/EtsHierarchy.kt
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,10 @@ class EtsHierarchy(private val scene: EtsScene) {
val typeName = etsClassType.typeName.removeTrashFromTheName()
val suitableClasses = resolveMap[typeName] ?: return emptySet()

if (etsClassType.isResolved()) {
val signature = (etsClassType as EtsClassType).signature.copy(name = typeName)
val classType = etsClassType as? EtsClassType
val requiresExactOwner = classType?.signature?.name == "Set"
if (etsClassType.isResolved() || requiresExactOwner) {
val signature = requireNotNull(classType).signature.copy(name = typeName)
return suitableClasses[signature]?.let { setOf(it) } ?: emptySet()
}

Expand Down
10 changes: 8 additions & 2 deletions usvm-ts/src/main/kotlin/org/usvm/util/MethodResolver.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.usvm.util

import org.jacodb.ets.model.EtsClass
import org.jacodb.ets.model.EtsClassSignature
import org.jacodb.ets.model.EtsClassType
import org.jacodb.ets.model.EtsMethod
import org.jacodb.ets.model.EtsMethodSignature
Expand All @@ -19,7 +21,7 @@ fun TsContext.resolveEtsMethods(

if (method.enclosingClass.name != UNKNOWN_CLASS_NAME) {
val classes = resolutionClasses.filter {
it.name == method.enclosingClass.name
it.matchesMethodOwner(method.enclosingClass)
}
val methods = classes.flatMap {
it.methods
Expand All @@ -31,7 +33,7 @@ fun TsContext.resolveEtsMethods(

val classes = if (instanceType is EtsClassType) {
resolutionClasses.filter {
it.name == instanceType.signature.name
it.matchesMethodOwner(instanceType.signature)
}
} else {
resolutionClasses
Expand All @@ -43,3 +45,7 @@ fun TsContext.resolveEtsMethods(
}
return methods
}

/** Set dispatch must preserve the constructor owner, including unresolved legacy owners. */
private fun EtsClass.matchesMethodOwner(owner: EtsClassSignature): Boolean =
if (owner.name == "Set") signature == owner else name == owner.name
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package org.usvm.machine.expr

import org.jacodb.ets.model.EtsMethod
import org.jacodb.ets.utils.EtsIrProvider
import org.jacodb.ets.utils.loadEtsProjectAutoConvert
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.TsAnalysisStopReason
import org.usvm.machine.TsMachine
import org.usvm.util.TsMethodTestRunner
import org.usvm.util.TsTestResolver
import org.usvm.util.assertNodeReplay
import org.usvm.util.getResourcePath
import org.usvm.util.jsString
import java.nio.file.Path
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds

class SetConstructorBindingIdentityTest : TsMethodTestRunner() {
@TempDir
lateinit var directory: Path

private val project = getResourcePath("/models/set-constructor-binding")

override val scene = loadEtsProjectAutoConvert(
projectPath = project,
provider = EtsIrProvider.TS_FRONTEND,
)

init {
options = options.copy(
timeout = 33.seconds,
stateCollectionStrategy = StateCollectionStrategy.ALL,
stopOnCoverage = 0,
)
}

override val runner: (EtsMethod, UMachineOptions) -> List<TsTest> = { method, machineOptions ->
TsMachine(scene = scene, options = machineOptions, tsOptions = tsOptions).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 `native Set keeps native behavior with one project namesake in the scene`() {
val projectSet = scene.projectClasses.single { it.name == "Set" }
assertEquals("LocalSetBinding.ts", projectSet.signature.file.fileName)

assertResult("NativeSetBinding", methodName = "sizeAndMembership", expected = 219.0)
}

@Test
fun `local and imported Set bind to the project declaration`() {
assertResult("LocalSetBinding", methodName = "localSize", expected = 31.0)
assertResult("ImportedSetBinding", methodName = "importedSize", expected = 47.0)
}

@Test
fun `replacing the global Set stops before native modeling`() {
val replacements = mapOf(
"replacedGlobal" to "Set = function replacement",
"replacedViaGlobalAlias" to "scope.Set = function replacement",
"replacedViaReflection" to "Reflect.set(globalThis",
)

val analysis = TsMachine(
scene = scene,
options = options.copy(throwExceptionOnStepFailure = true),
tsOptions = tsOptions.copy(eraseTypeAssertions = true),
).use { machine ->
replacements.keys.associateWith { methodName ->
val method = getMethod(methodName = methodName, className = "NativeSetBinding")
machine.analyzeWithMetadata(methods = listOf(method))
}
}

analysis.forEach { (methodName, result) ->
assertFalse(result.engineFailed, methodName)
assertTrue(result.states.isEmpty(), methodName)
val mutation = replacements.getValue(methodName)
val stoppedAtMutation = result.unsupportedPaths.any { it.contains(mutation) }
assertTrue(stoppedAtMutation, "$methodName: ${result.unsupportedPaths}")
}
}

@Test
fun `Node agrees with all constructor results in the original fixture modules`() {
val script = """
import { NativeSetBinding } from ${moduleUrl("NativeSetBinding.ts")};
import { LocalSetBinding } from ${moduleUrl("LocalSetBinding.ts")};
import { ImportedSetBinding } from ${moduleUrl("ImportedSetBinding.ts")};

if (NativeSetBinding.sizeAndMembership() !== 219) throw Error("native Set");
if (LocalSetBinding.localSize() !== 31) throw Error("local Set");
if (ImportedSetBinding.importedSize() !== 47) throw Error("imported Set");

const nativeSet = globalThis.Set;
for (const [method, expected] of [
[NativeSetBinding.replacedGlobal, 23],
[NativeSetBinding.replacedViaGlobalAlias, 103],
[NativeSetBinding.replacedViaReflection, 107],
]) {
try {
if (method() !== expected) throw Error(method.name);
} finally {
globalThis.Set = nativeSet;
}
}
""".trimIndent()

assertNodeReplay(
source = script,
directory = directory,
name = "set-constructor-binding",
timeoutMessage = "Native Set binding regression timed out",
)
}

private fun assertResult(clazz: String, methodName: String, expected: Double) {
val method = getMethod(methodName = methodName, className = clazz)
discoverProperties<TsTestValue.TsNumber>(
method = method,
{ result -> result.number == expected },
invariants = arrayOf({ result -> result.number == expected }),
)
}

private fun moduleUrl(filename: String): String =
jsString(project.resolve(filename).toUri().toString())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Set } from "./LocalSetBinding.ts";

export class ImportedSetBinding {
static importedSize(): number {
return new Set().size;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class Set {
readonly size: number;

constructor(size: number = 47) {
this.size = size;
}
}

export class LocalSetBinding {
static localSize(): number {
return new Set(31).size;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export class NativeSetBinding {
static sizeAndMembership(): number {
const values = new Set();
values.add(5);
values.add(5);
values.add(19);

return values.size * 100 + (values.has(19) ? 19 : 0);
}

static replacedGlobal(): number {
Set = function replacement() { return { marker: 23 }; } as unknown as SetConstructor;
const result = new Set() as unknown as { marker: number };
return result.marker;
}

static replacedViaGlobalAlias(): number {
const scope = globalThis;
scope.Set = function replacement() { return { marker: 103 }; } as unknown as SetConstructor;
const result = new Set() as unknown as { marker: number };
return result.marker;
}

static replacedViaReflection(): number {
Reflect.set(globalThis, "Set", function replacement() { return { marker: 107 }; });
const result = new Set() as unknown as { marker: number };
return result.marker;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true
},
"files": ["NativeSetBinding.ts", "LocalSetBinding.ts", "ImportedSetBinding.ts"]
}
Loading