Skip to content
Open
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 @@ -20,6 +20,7 @@
import org.swift.swiftkit.core.util.PlatformUtils;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.swift.swiftkit.ffm.SwiftRuntime.*;

public class SwiftArenaTest {
Expand All @@ -33,8 +34,9 @@ static boolean isAmd64() {
@Test
@DisabledIf("isAmd64")
public void arena_releaseClassOnClose_class_ok() {
MySwiftClass obj;
try (var arena = AllocatingSwiftArena.ofConfined()) {
var obj = MySwiftClass.init(1, 2, arena);
obj = MySwiftClass.init(1, 2, arena);

retain(obj);
assertEquals(2, retainCount(obj));
Expand All @@ -43,6 +45,7 @@ public void arena_releaseClassOnClose_class_ok() {
assertEquals(1, retainCount(obj));
}

// TODO: should we zero out the $memorySegment perhaps?
assertThrows(IllegalStateException.class, obj::$memorySegment);
assertThrows(IllegalStateException.class, obj::$memoryAddress);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,38 +51,34 @@ public void arena_releaseClassOnClose_class_ok() {
// See: https://github.com/swiftlang/swift-java/issues/97
@Test
public void arena_markAsDestroyed_preventUseAfterFree_class() {
MySwiftClass unsafelyEscapedOutsideArenaScope = null;
final MySwiftClass unsafelyEscapedOutsideArenaScope;

try (var arena = AllocatingSwiftArena.ofConfined()) {
var obj = MySwiftClass.init(1, 2, arena);
unsafelyEscapedOutsideArenaScope = obj;
unsafelyEscapedOutsideArenaScope = MySwiftClass.init(1, 2, arena);
}

try {
unsafelyEscapedOutsideArenaScope.echoIntMethod(1);
fail("Expected exception to be thrown! Object was supposed to be dead.");
} catch (IllegalStateException ex) {
return;
}
IllegalStateException methodEx = assertThrows(IllegalStateException.class,
() -> unsafelyEscapedOutsideArenaScope.echoIntMethod(1));
assertTrue(methodEx.getMessage().contains("already destroyed"));
assertThrows(IllegalStateException.class, unsafelyEscapedOutsideArenaScope::$memorySegment);
assertThrows(IllegalStateException.class, unsafelyEscapedOutsideArenaScope::$memoryAddress);
}

// FIXME: The destroy witness table call hangs on x86_64 platforms during the destroy witness table call
// See: https://github.com/swiftlang/swift-java/issues/97
@Test
public void arena_markAsDestroyed_preventUseAfterFree_struct() {
MySwiftStruct unsafelyEscapedOutsideArenaScope = null;
final MySwiftStruct unsafelyEscapedOutsideArenaScope;

try (var arena = AllocatingSwiftArena.ofConfined()) {
var s = MySwiftStruct.init(1, 2, arena);
unsafelyEscapedOutsideArenaScope = s;
unsafelyEscapedOutsideArenaScope = MySwiftStruct.init(1, 2, arena);
}

try {
unsafelyEscapedOutsideArenaScope.echoIntMethod(1);
fail("Expected exception to be thrown! Object was supposed to be dead.");
} catch (IllegalStateException ex) {
return;
}
IllegalStateException methodEx = assertThrows(IllegalStateException.class,
() -> unsafelyEscapedOutsideArenaScope.echoIntMethod(1));
assertTrue(methodEx.getMessage().contains("already destroyed"));
assertThrows(IllegalStateException.class, unsafelyEscapedOutsideArenaScope::$memorySegment);
assertThrows(IllegalStateException.class, unsafelyEscapedOutsideArenaScope::$memoryAddress);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ extension JNISwift2JavaGenerator {
printer.print(
"""
/** Pointer to the "self". */
private final long selfPointer;
private final SwiftInstancePointer selfPointer;

/** Pointer to the metatype of the concrete dynamic value boxed here. */
private final long selfTypePointer;
Expand All @@ -266,7 +266,8 @@ extension JNISwift2JavaGenerator {
private final SwiftInstanceCleanup $cleanup;

public long $memoryAddress() {
return this.selfPointer;
$ensureAlive();
return this.selfPointer.get();
}

@Override
Expand Down Expand Up @@ -378,13 +379,14 @@ extension JNISwift2JavaGenerator {
printer.print(
"""
/** Pointer to the "self". */
private final long selfPointer;
private final SwiftInstancePointer selfPointer;

/** Tracks whether this instance has been destroyed; doubles as the destroyed-state holder. */
private final SwiftInstanceCleanup $cleanup;

public long $memoryAddress() {
return this.selfPointer;
$ensureAlive();
return this.selfPointer.get();
}

@Override
Expand Down Expand Up @@ -458,16 +460,25 @@ extension JNISwift2JavaGenerator {
let pointerArg = pointerParams.map { "long \($0)" }.joined(separator: ", ")
printer.printBraceBlock("private \(javaName)(\(pointerArg), SwiftArena swiftArena)") { printer in
for param in pointerParams {
printer.print(
"""
SwiftObjects.requireNonZero(\(param), "\(param)");
this.\(param) = \(param);
"""
)
if param == "selfPointer" {
printer.print(
"""
SwiftObjects.requireNonZero(selfPointer, "selfPointer");
this.selfPointer = new SwiftInstancePointer(selfPointer);
"""
)
} else {
printer.print(
"""
SwiftObjects.requireNonZero(\(param), "\(param)");
this.\(param) = \(param);
"""
)
}
}
printer.print(
"""
this.$cleanup = $createCleanup();
this.$cleanup = $createCleanup(this.selfPointer);

// Only register once we have fully initialized the object since this will need the object pointer.
swiftArena.register(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,17 @@ public interface JNISwiftInstance extends SwiftInstance {
* and cache the result in a field exposed via {@link #$cleanup()}.
*/
default SwiftInstanceCleanup $createCleanup() {
return new JNISwiftInstanceCleanup($createDestroyFunction());
return $createCleanup(null);
}

/**
* Build a fresh {@link SwiftInstanceCleanup} that also clears {@code memoryAddress}
* after the underlying Swift value has been destroyed.
* <p>
* The cleanup stores the pointer holder rather than {@code this}, so it remains safe
* for use with a {@link java.lang.ref.Cleaner}.
*/
default SwiftInstanceCleanup $createCleanup(SwiftInstancePointer memoryAddress) {
return new JNISwiftInstanceCleanup($createDestroyFunction(), memoryAddress);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ class JNISwiftInstanceCleanup implements SwiftInstanceCleanup {
AtomicIntegerFieldUpdater.newUpdater(JNISwiftInstanceCleanup.class, "destroyed");

private final Runnable destroyFunction;
private final SwiftInstancePointer memoryAddress;

@SuppressWarnings("unused") // accessed via DESTROYED field updater
private volatile int destroyed;

public JNISwiftInstanceCleanup(Runnable destroyFunction) {
this(destroyFunction, null);
}

JNISwiftInstanceCleanup(Runnable destroyFunction, SwiftInstancePointer memoryAddress) {
this.destroyFunction = destroyFunction;
this.memoryAddress = memoryAddress;
}

@Override
Expand All @@ -38,6 +44,9 @@ public boolean isDestroyed() {
public void run() {
if (DESTROYED.compareAndSet(this, 0, 1)) {
destroyFunction.run();
if (memoryAddress != null) {
memoryAddress.clear();
}
} else {
throw new IllegalStateException("Double destruction attempt detected!");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
public final class SwiftErrorException extends SwiftError {

/** Pointer to the boxed {@code any Error}. */
private final long selfPointer;
private final SwiftInstancePointer selfPointer;

/** The metadata address of {@code (any Error).self}. */
private final long typeMetadataAddress;
Expand All @@ -47,9 +47,9 @@ public final class SwiftErrorException extends SwiftError {
private SwiftErrorException(long selfPointer, long typeMetadataAddress, SwiftArena swiftArena) {
SwiftObjects.requireNonZero(selfPointer, "selfPointer");
SwiftObjects.requireNonZero(typeMetadataAddress, "typeMetadataAddress");
this.selfPointer = selfPointer;
this.selfPointer = new SwiftInstancePointer(selfPointer);
this.typeMetadataAddress = typeMetadataAddress;
this.$cleanup = $createCleanup();
this.$cleanup = $createCleanup(this.selfPointer);

// Only register once we have fully initialized the object since this will need the object pointer.
swiftArena.register(this);
Expand All @@ -70,7 +70,8 @@ public static SwiftErrorException wrapMemoryAddressUnsafe(long selfPointer, long

@Override
public long $memoryAddress() {
return this.selfPointer;
$ensureAlive();
return this.selfPointer.get();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ public interface SwiftInstance {
/**
* Pointer to the {@code self} of the underlying Swift object or value.
*
* <b>API Note:</b> When using this pointer one must ensure that the underlying object
* is kept alive using some means (e.g. a class remains retained), as
* this function does not ensure safety of the address in any way.
* <p>Throws {@link IllegalStateException} if this instance has already been destroyed,
* for example after its {@link SwiftArena} was closed.
*
* <b>API Note:</b> When using this pointer one must still ensure that the underlying object
* is kept alive using some means (e.g. a class remains retained). This method prevents
* reaching freed Swift memory after an explicit destroy, but does not otherwise guarantee
* that the address remains valid.
*/
long $memoryAddress();

Expand All @@ -43,7 +47,8 @@ public interface SwiftInstance {
* use-after-free errors.
*/
default void $ensureAlive() {
if (this.$cleanup().isDestroyed()) {
SwiftInstanceCleanup cleanup = this.$cleanup();
if (cleanup != null && cleanup.isDestroyed()) {
throw new IllegalStateException("Attempted to call method on already destroyed instance of " + getClass().getSimpleName() + "!");
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

package org.swift.swiftkit.core;

/**
* A mutable holder for a Swift instance's memory address.
* <p>
* A {@link SwiftInstance} and its {@link SwiftInstanceCleanup} share the same holder so the
* cleanup can zero the address after destroy without capturing the Java wrapper itself.
* That keeps the cleanup safe to register with a {@link java.lang.ref.Cleaner}.
*/
public final class SwiftInstancePointer {
private volatile long address;

public SwiftInstancePointer(long address) {
this.address = address;
}

/**
* The current memory address, or {@code 0} if this pointer has been cleared.
*/
public long get() {
return address;
}

/**
* Zero the stored address so it can no longer be used to reach Swift memory.
*/
public void clear() {
this.address = 0L;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@
*/
public class SwiftDictionaryMap<K, V> extends AbstractMap<K, V> implements JNISwiftInstance {

private final long selfPointer;
private final SwiftInstancePointer selfPointer;
private final SwiftInstanceCleanup cleanup;

private SwiftDictionaryMap(long selfPointer) {
this.selfPointer = selfPointer;
this.cleanup = $createCleanup();
this.selfPointer = new SwiftInstancePointer(selfPointer);
this.cleanup = $createCleanup(this.selfPointer);
}

public static <K, V> SwiftDictionaryMap<K, V> wrapMemoryAddressUnsafe(long selfPointer, SwiftArena arena) {
Expand All @@ -48,13 +48,13 @@ public static <K, V> SwiftDictionaryMap<K, V> wrapMemoryAddressUnsafe(long selfP
@Override
public long $memoryAddress() {
$ensureAlive();
return selfPointer;
return selfPointer.get();
}

@Override
public long $typeMetadataAddress() {
$ensureAlive();
return $typeMetadataAddress(selfPointer);
return $typeMetadataAddress(selfPointer.get());
}

@Override
Expand All @@ -64,7 +64,7 @@ public static <K, V> SwiftDictionaryMap<K, V> wrapMemoryAddressUnsafe(long selfP

@Override
public Runnable $createDestroyFunction() {
final long p = this.selfPointer;
final long p = this.selfPointer.get();
return () -> $destroy(p);
}

Expand All @@ -73,28 +73,28 @@ public static <K, V> SwiftDictionaryMap<K, V> wrapMemoryAddressUnsafe(long selfP
@Override
public int size() {
$ensureAlive();
return $size(selfPointer);
return $size(selfPointer.get());
}

@Override
@SuppressWarnings("unchecked")
public V get(Object key) {
$ensureAlive();
return (V) $get(selfPointer, key);
return (V) $get(selfPointer.get(), key);
}

@Override
public boolean containsKey(Object key) {
$ensureAlive();
return $containsKey(selfPointer, key);
return $containsKey(selfPointer.get(), key);
}

@Override
@SuppressWarnings("unchecked")
public Set<Entry<K, V>> entrySet() {
$ensureAlive();
Object[] keys = $keys(selfPointer);
Object[] values = $values(selfPointer);
Object[] keys = $keys(selfPointer.get());
Object[] values = $values(selfPointer.get());
Set<Entry<K, V>> entries = new LinkedHashSet<>();
for (int i = 0; i < keys.length; i++) {
entries.add(new AbstractMap.SimpleImmutableEntry<>((K) keys[i], (V) values[i]));
Expand Down
Loading
Loading