diff --git a/Samples/SwiftAndJavaJarFFMSampleLib/src/test/java/org/swift/swiftkit/ffm/SwiftArenaTest.java b/Samples/SwiftAndJavaJarFFMSampleLib/src/test/java/org/swift/swiftkit/ffm/SwiftArenaTest.java index 8d786d952..b749a0900 100644 --- a/Samples/SwiftAndJavaJarFFMSampleLib/src/test/java/org/swift/swiftkit/ffm/SwiftArenaTest.java +++ b/Samples/SwiftAndJavaJarFFMSampleLib/src/test/java/org/swift/swiftkit/ffm/SwiftArenaTest.java @@ -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 { @@ -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)); @@ -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); } } diff --git a/Samples/SwiftJavaExtractFFMSampleApp/src/test/java/org/swift/swiftkitffm/SwiftArenaTest.java b/Samples/SwiftJavaExtractFFMSampleApp/src/test/java/org/swift/swiftkitffm/SwiftArenaTest.java index 08dd9b1bc..05844aae9 100644 --- a/Samples/SwiftJavaExtractFFMSampleApp/src/test/java/org/swift/swiftkitffm/SwiftArenaTest.java +++ b/Samples/SwiftJavaExtractFFMSampleApp/src/test/java/org/swift/swiftkitffm/SwiftArenaTest.java @@ -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 diff --git a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift index 9ef746282..30249dbfb 100644 --- a/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift +++ b/Sources/JExtractSwiftLib/JNI/JNISwift2JavaGenerator+JavaBindingsPrinting.swift @@ -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; @@ -266,7 +266,8 @@ extension JNISwift2JavaGenerator { private final SwiftInstanceCleanup $cleanup; public long $memoryAddress() { - return this.selfPointer; + $ensureAlive(); + return this.selfPointer.get(); } @Override @@ -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 @@ -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); diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstance.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstance.java index 7c8c89344..b11980eab 100644 --- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstance.java +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstance.java @@ -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. + *
+ * 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); } } diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstanceCleanup.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstanceCleanup.java index 3719c3ad3..9d921c556 100644 --- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstanceCleanup.java +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/JNISwiftInstanceCleanup.java @@ -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 @@ -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!"); } diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftErrorException.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftErrorException.java index 3f602016f..496dd0304 100644 --- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftErrorException.java +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftErrorException.java @@ -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; @@ -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); @@ -70,7 +70,8 @@ public static SwiftErrorException wrapMemoryAddressUnsafe(long selfPointer, long @Override public long $memoryAddress() { - return this.selfPointer; + $ensureAlive(); + return this.selfPointer.get(); } @Override diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstance.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstance.java index 865a368ea..7d1b8eecd 100644 --- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstance.java +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstance.java @@ -18,9 +18,13 @@ public interface SwiftInstance { /** * Pointer to the {@code self} of the underlying Swift object or value. * - * API Note: 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. + *
Throws {@link IllegalStateException} if this instance has already been destroyed, + * for example after its {@link SwiftArena} was closed. + * + * API Note: 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(); @@ -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() + "!"); } } diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstancePointer.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstancePointer.java new file mode 100644 index 000000000..551a6a489 --- /dev/null +++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/SwiftInstancePointer.java @@ -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. + *
+ * 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;
+ }
+}
diff --git a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/collections/SwiftDictionaryMap.java b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/collections/SwiftDictionaryMap.java
index 68f4d5c73..03986507c 100644
--- a/SwiftKitCore/src/main/java/org/swift/swiftkit/core/collections/SwiftDictionaryMap.java
+++ b/SwiftKitCore/src/main/java/org/swift/swiftkit/core/collections/SwiftDictionaryMap.java
@@ -31,12 +31,12 @@
*/
public class SwiftDictionaryMap
+ * Shared by the Java wrapper and its cleanup so the segment can be cleared after
+ * destroy without the cleanup capturing the wrapper itself.
+ */
+final class FFMInstanceMemory {
+ private volatile MemorySegment segment;
+
+ FFMInstanceMemory(MemorySegment segment) {
+ this.segment = segment;
+ }
+
+ MemorySegment get() {
+ return segment;
+ }
+
+ void clear() {
+ this.segment = null;
+ }
+}
diff --git a/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftErrorInstance.java b/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftErrorInstance.java
index 4fa41f3c7..8e76df1a9 100644
--- a/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftErrorInstance.java
+++ b/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftErrorInstance.java
@@ -25,25 +25,30 @@
* {@link SwiftInstance} for proper lifecycle management.
*/
public abstract class FFMSwiftErrorInstance extends Exception implements SwiftInstance {
- private final MemorySegment memorySegment;
+ private final FFMInstanceMemory memorySegment;
private final FFMSwiftInstanceCleanup cleanup;
protected FFMSwiftErrorInstance(String message, MemorySegment segment, AllocatingSwiftArena arena) {
super(message);
- this.memorySegment = segment;
- this.cleanup = new FFMSwiftInstanceCleanup(segment, $swiftType());
+ this.memorySegment = new FFMInstanceMemory(segment);
+ this.cleanup = new FFMSwiftInstanceCleanup(this.memorySegment, $swiftType());
arena.register(this);
}
protected FFMSwiftErrorInstance(MemorySegment segment, AllocatingSwiftArena arena) {
super();
- this.memorySegment = segment;
- this.cleanup = new FFMSwiftInstanceCleanup(segment, $swiftType());
+ this.memorySegment = new FFMInstanceMemory(segment);
+ this.cleanup = new FFMSwiftInstanceCleanup(this.memorySegment, $swiftType());
arena.register(this);
}
public final MemorySegment $memorySegment() {
- return memorySegment;
+ $ensureAlive();
+ MemorySegment segment = memorySegment.get();
+ if (segment == null) {
+ throw new IllegalStateException("Attempted to call method on already destroyed instance of " + getClass().getSimpleName() + "!");
+ }
+ return segment;
}
@Override
diff --git a/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstance.java b/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstance.java
index 11476087f..f87d39e63 100644
--- a/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstance.java
+++ b/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstance.java
@@ -20,7 +20,7 @@
import java.lang.foreign.MemorySegment;
public abstract class FFMSwiftInstance implements SwiftInstance {
- private final MemorySegment memorySegment;
+ private final FFMInstanceMemory memorySegment;
private final FFMSwiftInstanceCleanup cleanup;
/**
@@ -30,8 +30,8 @@ public abstract class FFMSwiftInstance implements SwiftInstance {
* @param arena the arena this object belongs to. When the arena goes out of scope, this value is destroyed.
*/
protected FFMSwiftInstance(MemorySegment segment, AllocatingSwiftArena arena) {
- this.memorySegment = segment;
- this.cleanup = new FFMSwiftInstanceCleanup(segment, $swiftType());
+ this.memorySegment = new FFMInstanceMemory(segment);
+ this.cleanup = new FFMSwiftInstanceCleanup(this.memorySegment, $swiftType());
// Only register once we have fully initialized the object since this will need the object pointer.
arena.register(this);
@@ -41,7 +41,12 @@ protected FFMSwiftInstance(MemorySegment segment, AllocatingSwiftArena arena) {
* The pointer to the instance in memory. I.e. the {@code self} of the Swift object or value.
*/
public final MemorySegment $memorySegment() {
- return this.memorySegment;
+ $ensureAlive();
+ MemorySegment segment = this.memorySegment.get();
+ if (segment == null) {
+ throw new IllegalStateException("Attempted to call method on already destroyed instance of " + getClass().getSimpleName() + "!");
+ }
+ return segment;
}
@Override
diff --git a/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstanceCleanup.java b/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstanceCleanup.java
index 6f4f6e1ee..f00d8e030 100644
--- a/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstanceCleanup.java
+++ b/SwiftKitFFM/src/main/java/org/swift/swiftkit/ffm/FFMSwiftInstanceCleanup.java
@@ -25,13 +25,13 @@ class FFMSwiftInstanceCleanup implements SwiftInstanceCleanup {
private static final AtomicIntegerFieldUpdater