diff --git a/CHANGELOG.md b/CHANGELOG.md index c3b429a..27c76fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ ## 0.5.2 -- fix a narrow race in async cancellation. If `cancel()` on a `CompletableFuture` returned by an async function landed in the few instructions between the pipeline's `isCancelled()` check and its own `rust_future_free`, or between a wake and the re-poll it triggers, the Rust future was freed twice or polled after being freed. Seen once in CI as a glibc `tcache_thread_shutdown()` abort. Every use of the handle now runs under the future's monitor and stops once it has been freed. No measurable change to async call overhead. -- fix generated Java failing to compile when a Rust field or parameter name matched a name the generator used in the same scope, such as an enum variant field named `value` ([#63](https://github.com/IronCoreLabs/uniffi-bindgen-java/issues/63)). Enum and error variant field names, and function, method, constructor and callback-interface parameter names can no longer collide with anything the Java generator emits. Names uniffi-rs itself reserves on the Rust side, such as a field named `buf` or a callback-interface parameter named `uniffi_handle`, are rejected by the Rust derive before bindings are generated and remain unavailable. +- fix a narrow race in async cancellation. If `cancel()` on a `CompletableFuture` returned by an async function landed in the few instructions between the pipeline's `isCancelled()` check and its own `rust_future_free`, or between a wake and the re-poll it triggers, the Rust future was freed twice or polled after being freed. Seen once in CI as a glibc `tcache_thread_shutdown()` abort. `cancel()` now signals Rust with `rust_future_cancel` and the poll/complete pipeline is the only thing that frees. The Rust future is dropped once the in-flight poll's continuation fires, on whichever thread the executor runs that continuation on; with a pool that is an executor thread rather than the cancelling one. Cancelling with an executor that accepts a task and never runs it now leaks the Rust future, where before `cancel()` freed it inline; see the executor notes in the README. +- fix generated Java failing to compile when a Rust field or parameter name matched a name the generator used in the same scope, such as an enum variant field named `value` ([#63](https://github.com/IronCoreLabs/uniffi-bindgen-java/issues/63)). Record, enum variant and error variant field names, and function, method, constructor and callback-interface parameter names can no longer collide with anything the Java generator emits, including the locals of the generated `equals`/`hashCode` and of the async poll/complete/cancel/free lambdas. Names uniffi-rs itself reserves on the Rust side, such as a field named `buf` or a callback-interface parameter named `uniffi_handle`, are rejected by the Rust derive before bindings are generated and remain unavailable. ## 0.5.1 diff --git a/Cargo.lock b/Cargo.lock index 5e3e365..529cb76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1605,6 +1605,7 @@ dependencies = [ "uniffi-example-rondpoint", "uniffi-example-sprites", "uniffi-example-todolist", + "uniffi-fixture-async-lifecycle", "uniffi-fixture-benchmarks", "uniffi-fixture-coverall", "uniffi-fixture-enum-types", @@ -1686,6 +1687,14 @@ dependencies = [ "uniffi", ] +[[package]] +name = "uniffi-fixture-async-lifecycle" +version = "0.1.0" +dependencies = [ + "async-trait", + "uniffi", +] + [[package]] name = "uniffi-fixture-benchmarks" version = "0.22.0" diff --git a/Cargo.toml b/Cargo.toml index b650f2a..7f05bfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,7 @@ uniffi-example-geometry = { git = "https://github.com/mozilla/uniffi-rs.git", br uniffi-example-rondpoint = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } uniffi-example-sprites = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } uniffi-example-todolist = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } +uniffi-fixture-async-lifecycle = { path = "fixtures/async-lifecycle" } uniffi-fixture-benchmarks = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } uniffi-fixture-coverall = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } uniffi-fixture-enum-types = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } diff --git a/README.md b/README.md index e4a9de8..aa7f289 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,7 @@ scope). - a Rust `&[u8]` argument is borrowed by Rust for the duration of the call rather than copied, and takes a **direct** `java.nio.ByteBuffer` (as in Kotlin) instead of `byte[]`. Build one with `ByteBuffer.allocateDirect(arr.length).put(arr).flip()`; a heap buffer throws `IllegalArgumentException`. Reuse the buffer across calls where you can, and don't let another thread write to it while a call is in flight. `Vec` is unaffected and still maps to `byte[]`. - failures in CompletableFutures will cause them to `completeExceptionally`. The error that caused the failure can be checked with `e.getCause()`. When implementing an async Rust trait in Java, you'll need to `completeExceptionally` instead of throwing. See `TestFixtureFutures.java` for an example trait implementation with errors. +- every async function and method has an overload taking a `java.util.concurrent.Executor`; the other overload uses `ForkJoinPool.commonPool()`. The first poll runs on the calling thread, before the method returns; the executor runs every re-poll and the completion of the returned `CompletableFuture`. Any executor that hands tasks to its own threads works: the common pool, `Executors.newFixedThreadPool`, `newCachedThreadPool`, `newSingleThreadExecutor`, or a virtual-thread executor. Rust invokes the continuation from inside `Waker::wake()`, so an executor that runs tasks on the submitting thread (such as `Runnable::run`) polls the future from within its own waker and deadlocks any future that holds a lock while waking. Cancelling the returned future signals Rust with `rust_future_cancel` and the poll/complete pipeline frees the Rust future once the in-flight poll's continuation fires, on whichever thread the executor runs that continuation on. Two consequences: an executor that accepts a task and never runs it (`ThreadPoolExecutor.DiscardPolicy`, or a queue drained by `shutdownNow()`) leaks the Rust future and everything it owns, and with an inline executor the free happens on the cancelling thread. - all primitives are signed in Java by default. Rust correctly interprets the a signed primitive value from Java as unsigned when told to. Callers of Uniffi functions need to be aware when making comparisons (`compareUnsigned`) or printing when a value is actually unsigned to code around footguns on this side. - this is an internal note for development but because Enum variants are not cases/hanging off their parent in Java, their named standalone, they can conflict with any/all `java.lang` types. We could do extensive checking and forced renaming around this, but instead we use fully qualified names for all `java.lang` types in all templates. Ensure that when you're making changes you're not dropping those qualified names or adding generated code without them. diff --git a/fixtures/async-lifecycle/Cargo.toml b/fixtures/async-lifecycle/Cargo.toml new file mode 100644 index 0000000..ec922c9 --- /dev/null +++ b/fixtures/async-lifecycle/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "uniffi-fixture-async-lifecycle" +version = "0.1.0" +edition = "2024" + +[lib] +crate-type = ["cdylib", "lib"] +name = "uniffi_fixture_async_lifecycle" + +[dependencies] +async-trait = "0.1" +uniffi = { git = "https://github.com/mozilla/uniffi-rs.git", branch = "release-v0.32.x" } diff --git a/fixtures/async-lifecycle/src/lib.rs b/fixtures/async-lifecycle/src/lib.rs new file mode 100644 index 0000000..89dfe6e --- /dev/null +++ b/fixtures/async-lifecycle/src/lib.rs @@ -0,0 +1,141 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +//! Async functions whose futures count their own construction and drop. + +use std::{ + future::Future, + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + }, + task::{Context, Poll, Waker}, + thread, + time::Duration, +}; + +uniffi::setup_scaffolding!("async_lifecycle"); + +static CREATED: AtomicU64 = AtomicU64::new(0); +static DROPPED: AtomicU64 = AtomicU64::new(0); + +struct DropTracker; + +impl DropTracker { + fn new() -> Self { + CREATED.fetch_add(1, Ordering::SeqCst); + Self + } +} + +impl Drop for DropTracker { + fn drop(&mut self) { + DROPPED.fetch_add(1, Ordering::SeqCst); + } +} + +#[uniffi::export] +pub fn created_count() -> u64 { + CREATED.load(Ordering::SeqCst) +} + +#[uniffi::export] +pub fn dropped_count() -> u64 { + DROPPED.load(Ordering::SeqCst) +} + +#[uniffi::export] +pub fn reset_counts() { + CREATED.store(0, Ordering::SeqCst); + DROPPED.store(0, Ordering::SeqCst); +} + +struct TimerState { + completed: bool, + waker: Option, +} + +/// Completes after `duration` on a spawned thread, having woken the future `spurious_wakes` times +/// first. A wake with no waker stored yet is dropped. +struct Timer { + state: Arc>, +} + +impl Timer { + fn new(duration: Duration, spurious_wakes: u16) -> Self { + let state = Arc::new(Mutex::new(TimerState { + completed: false, + waker: None, + })); + let thread_state = Arc::clone(&state); + // Wakers are invoked with the lock released: an inline foreign executor re-polls from + // inside `wake()`, on this thread. + thread::spawn(move || { + for _ in 0..spurious_wakes { + thread::sleep(Duration::from_millis(1)); + let waker = thread_state.lock().unwrap().waker.take(); + if let Some(waker) = waker { + waker.wake(); + } + } + thread::sleep(duration); + let waker = { + let mut state = thread_state.lock().unwrap(); + state.completed = true; + state.waker.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + }); + Self { state } + } +} + +impl Future for Timer { + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + let mut state = self.state.lock().unwrap(); + if state.completed { + Poll::Ready(()) + } else { + state.waker = Some(cx.waker().clone()); + Poll::Pending + } + } +} + +#[uniffi::export] +pub async fn tracked_ready() { + let _tracker = DropTracker::new(); +} + +#[uniffi::export] +pub async fn tracked_sleep(ms: u16) { + let _tracker = DropTracker::new(); + Timer::new(Duration::from_millis(ms.into()), 0).await; +} + +#[uniffi::export] +pub async fn tracked_wake_storm(ms: u16, spurious_wakes: u16) { + let _tracker = DropTracker::new(); + Timer::new(Duration::from_millis(ms.into()), spurious_wakes).await; +} + +#[uniffi::export(with_foreign)] +#[async_trait::async_trait] +pub trait Notifier: Send + Sync { + async fn on_ready(&self); +} + +/// The sleep guarantees the foreign caller holds the future before `on_ready` is upcalled from +/// a re-poll. +#[uniffi::export] +pub async fn sleep_then_notify(ms: u16, notifier: Arc) { + let _tracker = DropTracker::new(); + Timer::new(Duration::from_millis(ms.into()), 0).await; + notifier.on_ready().await; +} diff --git a/fixtures/name-collisions/src/lib.rs b/fixtures/name-collisions/src/lib.rs index f3133c2..f19f850 100644 --- a/fixtures/name-collisions/src/lib.rs +++ b/fixtures/name-collisions/src/lib.rs @@ -34,6 +34,35 @@ fn enum_named_value(buf: Shadowing) -> Option { } } +/// `other`, `t` and `result` are the locals the generated `equals`/`hashCode` bind. The `Vec` +/// field is what selects the deep-comparison form of those overrides. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct Shadowed { + pub other: String, + pub t: i32, + pub result: Vec, +} + +#[uniffi::export] +fn roundtrip_record(value: Shadowed) -> Shadowed { + value +} + +/// The same three names on an enum variant, which renders its own `equals`/`hashCode`. +#[derive(Debug, Clone, PartialEq, uniffi::Enum)] +pub enum ShadowingArrays { + Named { + other: String, + t: i32, + result: Vec, + }, +} + +#[uniffi::export] +fn roundtrip_enum_arrays(value: ShadowingArrays) -> ShadowingArrays { + value +} + /// `x` is the error converter's type-pattern binding. #[derive(Debug, Clone, PartialEq, thiserror::Error, uniffi::Error)] pub enum ShadowError { @@ -58,10 +87,22 @@ fn sync_fn( format!("{uniffi_out_err}|{status}|{allocator}|{it}|{e}") } -/// Parameters named after the locals of the async call path. +/// Parameters named after the locals of the async call path, including the parameters of the +/// poll/complete/cancel/free lambdas the async filters emit into this same scope. #[uniffi::export] -async fn async_fn(uniffi_executor: String, it: String, uniffi_result: String) -> String { - format!("{uniffi_executor}|{it}|{uniffi_result}") +async fn async_fn( + uniffi_executor: String, + it: String, + uniffi_result: String, + future: String, + callback: String, + continuation_handle: String, + allocator: String, + status: String, +) -> String { + format!( + "{uniffi_executor}|{it}|{uniffi_result}|{future}|{callback}|{continuation_handle}|{allocator}|{status}" + ) } #[derive(uniffi::Object)] @@ -85,8 +126,12 @@ impl Holder { uniffi_handle: String, uniffi_executor: String, it: String, + future: String, ) -> String { - format!("{}|{uniffi_handle}|{uniffi_executor}|{it}", self.tag) + format!( + "{}|{uniffi_handle}|{uniffi_executor}|{it}|{future}", + self.tag + ) } } diff --git a/src/gen_java/mod.rs b/src/gen_java/mod.rs index 296ddf9..2350051 100644 --- a/src/gen_java/mod.rs +++ b/src/gen_java/mod.rs @@ -1886,7 +1886,7 @@ mod filters { ) -> Result { let ffi_func = callable.ffi_rust_future_poll(ci); Ok(format!( - "(future, callback, continuationHandle) -> UniffiLib.{ffi_func}(future, callback, continuationHandle)" + "(_uniffiFuture, _uniffiCallback, _uniffiContinuationHandle) -> UniffiLib.{ffi_func}(_uniffiFuture, _uniffiCallback, _uniffiContinuationHandle)" )) } @@ -1904,9 +1904,27 @@ mod filters { let ffi_type: FfiType = t.into(); JavaCodeOracle.ffi_type_is_struct(&ffi_type) }); - let allocator_arg = if needs_allocator { "_allocator, " } else { "" }; - let call = format!("UniffiLib.{ffi_func}({allocator_arg}future, continuation)"); - Ok(format!("(_allocator, future, continuation) -> {call}")) + let allocator_arg = if needs_allocator { + "_uniffiAllocator, " + } else { + "" + }; + let call = format!("UniffiLib.{ffi_func}({allocator_arg}_uniffiFuture, _uniffiStatus)"); + Ok(format!( + "(_uniffiAllocator, _uniffiFuture, _uniffiStatus) -> {call}" + )) + } + + #[askama::filter_fn] + pub fn async_cancel( + callable: impl Callable, + _v: &dyn askama::Values, + ci: &ComponentInterface, + ) -> Result { + let ffi_func = callable.ffi_rust_future_cancel(ci); + Ok(format!( + "(_uniffiFuture) -> UniffiLib.{ffi_func}(_uniffiFuture)" + )) } #[askama::filter_fn] @@ -1916,7 +1934,9 @@ mod filters { ci: &ComponentInterface, ) -> Result { let ffi_func = callable.ffi_rust_future_free(ci); - Ok(format!("(future) -> UniffiLib.{ffi_func}(future)")) + Ok(format!( + "(_uniffiFuture) -> UniffiLib.{ffi_func}(_uniffiFuture)" + )) } /// Remove the "`" chars we put around function/variable names @@ -1936,11 +1956,51 @@ mod filters { _v: &dyn askama::Values, spaces: &i32, ) -> Result { - let middle = textwrap::indent(&textwrap::dedent(docstring.as_ref()), " * "); - let wrapped = format!("/**\n{middle}\n */"); + Ok(javadoc(&textwrap::dedent(docstring.as_ref()), *spaces)) + } - let spaces = usize::try_from(*spaces).unwrap_or_default(); - Ok(textwrap::indent(&wrapped, &" ".repeat(spaces))) + /// Javadoc for one overload of an async callable. + #[askama::filter_fn] + pub fn async_docstring( + callable: impl Callable, + _v: &dyn askama::Values, + spaces: &i32, + with_executor: bool, + ) -> Result { + let mut body = String::new(); + if let Some(docstring) = callable.docstring() { + body.push_str(&textwrap::dedent(docstring)); + body.push_str("\n\n"); + } + body.push_str(if with_executor { + ASYNC_EXECUTOR_PARAM_DOC + } else { + ASYNC_COMMON_POOL_DOC + }); + Ok(javadoc(&body, *spaces)) + } + + const ASYNC_COMMON_POOL_DOC: &str = "\ +Re-polls and completes on {@link java.util.concurrent.ForkJoinPool#commonPool()}. See the overload +taking an {@link java.util.concurrent.Executor} for the contract an executor must meet."; + + const ASYNC_EXECUTOR_PARAM_DOC: &str = "\ +@param _uniffiExecutor runs every re-poll and the completion of the returned future. The first + poll runs on the calling thread, before this method returns. Any executor that hands tasks to + its own threads works: {@link java.util.concurrent.ForkJoinPool#commonPool()}, a fixed, cached + or single-thread pool, or a virtual-thread executor. Rust invokes the continuation from inside + {@code Waker::wake()}, so an executor that runs tasks on the submitting thread, such as + {@code Runnable::run}, polls the future from within its own waker and deadlocks any future + that holds a lock while waking. Cancelling the returned future signals Rust; the pipeline then + frees the Rust future, so an executor that accepts a task and never runs it, such as one using + {@link java.util.concurrent.ThreadPoolExecutor.DiscardPolicy} or one whose queue was drained + by {@code shutdownNow()}, leaks the Rust future and everything it owns."; + + fn javadoc(body: &str, spaces: i32) -> String { + let middle = textwrap::indent(body, " * "); + let wrapped = format!("/**\n{middle}\n */"); + let spaces = usize::try_from(spaces).unwrap_or_default(); + textwrap::indent(&wrapped, &" ".repeat(spaces)) } /// Returns the type name suitable for use in field declarations, method parameters, and return types. @@ -2898,19 +2958,19 @@ mod tests { let bindings = generate_bindings(&Config::default(), &ci).unwrap(); assert!( - bindings.contains("UniffiDeepValue.equals(data, t.data)"), + bindings.contains("UniffiDeepValue.equals(data, _uniffiThat.data)"), "array fields must compare by value:\n{bindings}" ); assert!( - bindings.contains("java.lang.Double.compare(ratio, t.ratio) == 0"), + bindings.contains("java.lang.Double.compare(ratio, _uniffiThat.ratio) == 0"), "`==` on a double breaks reflexivity for NaN:\n{bindings}" ); assert!( - bindings.contains("31 * result + UniffiDeepValue.hashCode(data)"), + bindings.contains("31 * _uniffiHash + UniffiDeepValue.hashCode(data)"), "array fields must hash by value:\n{bindings}" ); assert!( - bindings.contains("31 * result + java.lang.Double.hashCode(ratio)"), + bindings.contains("31 * _uniffiHash + java.lang.Double.hashCode(ratio)"), "double fields must hash without boxing:\n{bindings}" ); } @@ -2930,11 +2990,11 @@ mod tests { "expected an immutable record:\n{bindings}" ); assert!( - bindings.contains("UniffiDeepValue.equals(data, t.data)"), + bindings.contains("UniffiDeepValue.equals(data, _uniffiThat.data)"), "the record-generated equals sees array components by identity:\n{bindings}" ); assert!( - bindings.contains("java.lang.Double.compare(ratio, t.ratio) == 0"), + bindings.contains("java.lang.Double.compare(ratio, _uniffiThat.ratio) == 0"), "the override must keep the record default's NaN reflexivity:\n{bindings}" ); } @@ -2989,11 +3049,11 @@ mod tests { let bindings = generate_bindings(&Config::default(), &ci).unwrap(); assert!( - bindings.contains("UniffiDeepValue.equals(v1, t.v1)"), + bindings.contains("UniffiDeepValue.equals(v1, _uniffiThat.v1)"), "the variant record's equals sees array components by identity:\n{bindings}" ); assert!( - bindings.contains("31 * result + UniffiDeepValue.hashCode(v1)"), + bindings.contains("31 * _uniffiHash + UniffiDeepValue.hashCode(v1)"), "the variant record's hashCode must match its equals:\n{bindings}" ); } diff --git a/src/templates/Async.java b/src/templates/Async.java index 5641e5a..4b6aa59 100644 --- a/src/templates/Async.java +++ b/src/templates/Async.java @@ -44,67 +44,55 @@ interface AsyncCompleteVoidFunction { void apply(java.lang.foreign.SegmentAllocator allocator, long rustFuture, java.lang.foreign.MemorySegment status); } - // Every use of the handle holds the monitor and checks `freed` first. cancel() frees on the - // calling thread while the poll/complete pipeline may be mid-call on an executor thread. + // The pipeline is the sole freer; cancel() only signals Rust, which makes later polls return + // Ready. The lock keeps rust_future_cancel off a handle that free() has already consumed, which + // is the one ordering uniffi requires of us. A failed tryLock means free() or another cancel() + // holds it: the first case has nothing left to cancel, the second has already signalled. + // rust_future_cancel also fires the in-flight poll's continuation when one is stored, and under + // an inline executor that runs the completion pipeline, and a reentrant free(), on this thread + // inside the critical section. static final class UniffiFreeingFuture extends java.util.concurrent.CompletableFuture { private final long rustFuture; + private final java.util.function.Consumer cancelFunc; private final java.util.function.Consumer freeFunc; + private final java.util.concurrent.locks.ReentrantLock lock = new java.util.concurrent.locks.ReentrantLock(); private boolean freed; - UniffiFreeingFuture(long rustFuture, java.util.function.Consumer freeFunc) { + UniffiFreeingFuture( + long rustFuture, + java.util.function.Consumer cancelFunc, + java.util.function.Consumer freeFunc + ) { this.rustFuture = rustFuture; + this.cancelFunc = cancelFunc; this.freeFunc = freeFunc; } @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = super.cancel(mayInterruptIfRunning); - if (cancelled) { - free(); + if (cancelled && lock.tryLock()) { + try { + if (!freed) { + cancelFunc.accept(rustFuture); + } + } finally { + lock.unlock(); + } } return cancelled; } - synchronized void free() { - if (freed) { - return; - } - freed = true; - freeFunc.accept(rustFuture); - } - - // Returns false, without polling, once freed. - synchronized boolean poll(PollingFunction pollFunc, long continuationHandle) { - if (freed) { - return false; - } - pollFunc.apply(rustFuture, CONTINUATION_CALLBACK_STUB, continuationHandle); - return true; - } - - // Returns null once freed, which the pipeline only reaches after cancel(). - synchronized F completeRust( - AsyncCompleteFunction completeFunc, - UniffiRustCallStatusErrorHandler errorHandler - ) throws E { - if (freed) { - return null; - } - return UniffiHelpers.uniffiRustCallWithError(errorHandler, (_allocator, status) -> { - return completeFunc.apply(_allocator, rustFuture, status); - }); - } - - synchronized void completeRustVoid( - AsyncCompleteVoidFunction completeFunc, - UniffiRustCallStatusErrorHandler errorHandler - ) throws E { - if (freed) { - return; + void free() { + lock.lock(); + try { + if (!freed) { + freed = true; + freeFunc.accept(rustFuture); + } + } finally { + lock.unlock(); } - UniffiHelpers.uniffiRustCallWithError(errorHandler, (_allocator, status) -> { - completeFunc.apply(_allocator, rustFuture, status); - }); } } @@ -132,16 +120,19 @@ static java.util.concurrent.CompletableFut long rustFuture, PollingFunction pollFunc, AsyncCompleteFunction completeFunc, + java.util.function.Consumer cancelFunc, java.util.function.Consumer freeFunc, java.util.function.Function liftFunc, UniffiRustCallStatusErrorHandler errorHandler ){ - UniffiFreeingFuture future = new UniffiFreeingFuture<>(rustFuture, freeFunc); + UniffiFreeingFuture future = new UniffiFreeingFuture<>(rustFuture, cancelFunc, freeFunc); java.util.concurrent.CompletableFuture pollChain; try { - pollChain = pollUntilReady(future, pollFunc, uniffiExecutor); - } catch (java.lang.Exception e) { + pollChain = pollUntilReady(rustFuture, pollFunc, uniffiExecutor); + } catch (java.lang.Throwable e) { + // Throwable, not Exception: the UniffiLib downcall wrappers report a failed + // invokeExact as an AssertionError, which Exception would let escape unfreed. future.completeExceptionally(e); future.free(); return future; @@ -152,8 +143,10 @@ static java.util.concurrent.CompletableFut return null; } try { - F result = future.completeRust(completeFunc, errorHandler); - return result == null ? null : liftFunc.apply(result); + F result = UniffiHelpers.uniffiRustCallWithError(errorHandler, (_allocator, status) -> { + return completeFunc.apply(_allocator, rustFuture, status); + }); + return liftFunc.apply(result); } catch (java.lang.Exception e) { throw new java.util.concurrent.CompletionException(e); } @@ -184,16 +177,19 @@ static java.util.concurrent.CompletableFuture cancelFunc, java.util.function.Consumer freeFunc, java.lang.Runnable liftFunc, UniffiRustCallStatusErrorHandler errorHandler ){ - UniffiFreeingFuture future = new UniffiFreeingFuture<>(rustFuture, freeFunc); + UniffiFreeingFuture future = new UniffiFreeingFuture<>(rustFuture, cancelFunc, freeFunc); java.util.concurrent.CompletableFuture pollChain; try { - pollChain = pollUntilReady(future, pollFunc, uniffiExecutor); - } catch (java.lang.Exception e) { + pollChain = pollUntilReady(rustFuture, pollFunc, uniffiExecutor); + } catch (java.lang.Throwable e) { + // Throwable, not Exception: the UniffiLib downcall wrappers report a failed + // invokeExact as an AssertionError, which Exception would let escape unfreed. future.completeExceptionally(e); future.free(); return future; @@ -204,7 +200,9 @@ static java.util.concurrent.CompletableFuture { + completeFunc.apply(_allocator, rustFuture, status); + }); } catch (java.lang.Exception e) { throw new java.util.concurrent.CompletionException(e); } @@ -228,18 +226,21 @@ static java.util.concurrent.CompletableFuture pollUntilReady(UniffiFreeingFuture future, PollingFunction pollFunc, java.util.concurrent.Executor uniffiExecutor) { + private static java.util.concurrent.CompletableFuture pollUntilReady(long rustFuture, PollingFunction pollFunc, java.util.concurrent.Executor uniffiExecutor) { java.util.concurrent.CompletableFuture pollFuture = new java.util.concurrent.CompletableFuture<>(); var handle = uniffiContinuationHandleMap.insert(pollFuture); - if (!future.poll(pollFunc, handle)) { + try { + pollFunc.apply(rustFuture, CONTINUATION_CALLBACK_STUB, handle); + } catch (java.lang.Throwable e) { + // Rust never took the handle, so nothing else will remove it. uniffiContinuationHandleMap.remove(handle); - return java.util.concurrent.CompletableFuture.completedFuture(null); + throw e; } return pollFuture.thenComposeAsync(pollResult -> { if (pollResult == UNIFFI_RUST_FUTURE_POLL_READY) { return java.util.concurrent.CompletableFuture.completedFuture(null); } else { - return pollUntilReady(future, pollFunc, uniffiExecutor); + return pollUntilReady(rustFuture, pollFunc, uniffiExecutor); } }, uniffiExecutor); } diff --git a/src/templates/EnumTemplate.java b/src/templates/EnumTemplate.java index 9bc5ab7..fb68afa 100644 --- a/src/templates/EnumTemplate.java +++ b/src/templates/EnumTemplate.java @@ -105,11 +105,11 @@ public void close() { {#- The record-generated equals/hashCode compare array components by identity. -#} {%- if variant_trait_methods.eq_eq.is_none() && variant.fields()|has_array_rendered_field %} @Override - public boolean equals(java.lang.Object other) { - if (other instanceof {{ variant|type_name(ci, config) }}) { - {{ variant|type_name(ci, config) }} t = ({{ variant|type_name(ci, config) }}) other; + public boolean equals(java.lang.Object _uniffiOther) { + if (_uniffiOther instanceof {{ variant|type_name(ci, config) }}) { + {{ variant|type_name(ci, config) }} _uniffiThat = ({{ variant|type_name(ci, config) }}) _uniffiOther; return ({% for field in variant.fields() %}{% let fname = field|field_java_name(loop.index) %} - {{ field|boxed_equals_expr(fname, "t." ~ fname) }}{% if !loop.last %} && {% endif %} + {{ field|boxed_equals_expr(fname, "_uniffiThat." ~ fname) }}{% if !loop.last %} && {% endif %} {% endfor %} ); }; @@ -119,12 +119,12 @@ public boolean equals(java.lang.Object other) { {%- if variant_trait_methods.hash_hash.is_none() && variant.fields()|has_array_rendered_field %} @Override public int hashCode() { - int result = 17; + int _uniffiHash = 17; {%- for field in variant.fields() %} {%- let fname = field|field_java_name(loop.index) %} - result = 31 * result + {{ field|boxed_hash_code_expr(fname) }}; + _uniffiHash = 31 * _uniffiHash + {{ field|boxed_hash_code_expr(fname) }}; {%- endfor %} - return result; + return _uniffiHash; } {%- endif %} {% call java::uniffi_trait_impls(variant_trait_methods) %}{% endcall %} diff --git a/src/templates/RecordTemplate.java b/src/templates/RecordTemplate.java index e5a08c7..ec00193 100644 --- a/src/templates/RecordTemplate.java +++ b/src/templates/RecordTemplate.java @@ -22,11 +22,11 @@ public void close() { {#- The record-generated equals/hashCode compare array components by identity. -#} {%- if uniffi_trait_methods.eq_eq.is_none() && rec.fields()|has_array_rendered_field %} @Override - public boolean equals(java.lang.Object other) { - if (other instanceof {{ type_name }}) { - {{ type_name }} t = ({{ type_name }}) other; + public boolean equals(java.lang.Object _uniffiOther) { + if (_uniffiOther instanceof {{ type_name }}) { + {{ type_name }} _uniffiThat = ({{ type_name }}) _uniffiOther; return ({% for field in rec.fields() %}{% let field_var_name = field.name()|var_name %} - {{ field|equals_expr(field_var_name, "t." ~ field_var_name) }}{% if !loop.last%} && {% endif %} + {{ field|equals_expr(field_var_name, "_uniffiThat." ~ field_var_name) }}{% if !loop.last%} && {% endif %} {% endfor %} ); }; @@ -36,11 +36,11 @@ public boolean equals(java.lang.Object other) { {%- if uniffi_trait_methods.hash_hash.is_none() && rec.fields()|has_array_rendered_field %} @Override public int hashCode() { - int result = 17; + int _uniffiHash = 17; {%- for field in rec.fields() %} - result = 31 * result + {{ field|hash_code_expr(field.name()|var_name) }}; + _uniffiHash = 31 * _uniffiHash + {{ field|hash_code_expr(field.name()|var_name) }}; {%- endfor %} - return result; + return _uniffiHash; } {%- endif %} {% for meth in rec.methods() -%} @@ -92,11 +92,11 @@ public void close() { {# Use trait-based implementations if available, otherwise use hardcoded #} {%- if uniffi_trait_methods.eq_eq.is_none() %} @Override - public boolean equals(java.lang.Object other) { - if (other instanceof {{ type_name }}) { - {{ type_name }} t = ({{ type_name }}) other; + public boolean equals(java.lang.Object _uniffiOther) { + if (_uniffiOther instanceof {{ type_name }}) { + {{ type_name }} _uniffiThat = ({{ type_name }}) _uniffiOther; return ({% for field in rec.fields() %}{% let field_var_name = field.name()|var_name %} - {{ field|equals_expr(field_var_name, "t." ~ field_var_name) }}{% if !loop.last%} && {% endif %} + {{ field|equals_expr(field_var_name, "_uniffiThat." ~ field_var_name) }}{% if !loop.last%} && {% endif %} {% endfor %} ); }; @@ -107,11 +107,11 @@ public boolean equals(java.lang.Object other) { {%- if uniffi_trait_methods.hash_hash.is_none() %} @Override public int hashCode() { - int result = 17; + int _uniffiHash = 17; {%- for field in rec.fields() %} - result = 31 * result + {{ field|hash_code_expr(field.name()|var_name) }}; + _uniffiHash = 31 * _uniffiHash + {{ field|hash_code_expr(field.name()|var_name) }}; {%- endfor %} - return result; + return _uniffiHash; } {%- endif %} diff --git a/src/templates/macros.java b/src/templates/macros.java index f97776c..050ccbd 100644 --- a/src/templates/macros.java +++ b/src/templates/macros.java @@ -75,11 +75,11 @@ {%- endmacro -%} {%- macro func_decl(func_decl, annotation, callable, indent) %} - {%- call docstring(callable, indent) %}{% endcall %} + {%- if callable.is_async() %} + {{ callable|async_docstring(indent, false) }} {%- if annotation != "" %} @{{ annotation }} {% endif %} - {%- if callable.is_async() %} {#- Async methods use CompletableFuture which requires boxed types -#} {#- No-executor overload - defaults to ForkJoinPool.commonPool(), delegates to Executor version -#} {{ func_decl }} java.util.concurrent.CompletableFuture<{% match callable.return_type() -%}{%- when Some with (return_type) -%}{{ return_type|boxed_type_name(ci, config) }}{%- when None %}java.lang.Void{%- endmatch %}> {{ callable.name()|fn_name }}( @@ -89,12 +89,17 @@ } {#- With-executor overload - does the actual async work -#} + {{ callable|async_docstring(indent, true) }} {{ func_decl }} java.util.concurrent.CompletableFuture<{% match callable.return_type() -%}{%- when Some with (return_type) -%}{{ return_type|boxed_type_name(ci, config) }}{%- when None %}java.lang.Void{%- endmatch %}> {{ callable.name()|fn_name }}( {%- call arg_list(callable, !callable.self_type().is_some()) %}{% endcall -%}{% if !callable.arguments().is_empty() %}, {% endif %}java.util.concurrent.Executor _uniffiExecutor ){ return {% call call_async(callable) %}{% endcall %}; } {%- else -%} + {%- call docstring(callable, indent) %}{% endcall %} + {%- if annotation != "" %} + @{{ annotation }} + {% endif %} {#- Sync methods can use primitives for return types -#} {{ func_decl }} {% match callable.return_type() -%}{%- when Some with (return_type) -%}{{ return_type|type_name_for_field(ci, config) }}{%- when None %}void{%- endmatch %} {{ callable.name()|fn_name }}( {%- call arg_list(callable, !callable.self_type().is_some()) %}{% endcall -%} @@ -150,6 +155,7 @@ {%- endmatch %} {{ callable|async_poll(ci) }}, {{ callable|async_complete(ci, config) }}, + {{ callable|async_cancel(ci) }}, {{ callable|async_free(ci) }}, // lift function {%- match callable.return_type() %} diff --git a/tests/scripts/TestAsyncLifecycle/TestAsyncLifecycle.java b/tests/scripts/TestAsyncLifecycle/TestAsyncLifecycle.java new file mode 100644 index 0000000..c8519fb --- /dev/null +++ b/tests/scripts/TestAsyncLifecycle/TestAsyncLifecycle.java @@ -0,0 +1,90 @@ +import uniffi.async_lifecycle.*; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; + +public class TestAsyncLifecycle { + // Only a leak exhausts the bound. + static void awaitAllDropped(String label) throws Exception { + long deadline = System.nanoTime() + 10_000_000_000L; + while (AsyncLifecycle.droppedCount() != AsyncLifecycle.createdCount()) { + if (System.nanoTime() > deadline) { + throw new AssertionError(label + ": created=" + AsyncLifecycle.createdCount() + + " dropped=" + AsyncLifecycle.droppedCount()); + } + Thread.sleep(5); + } + } + + public static void main(String[] args) throws Exception { + { + AsyncLifecycle.resetCounts(); + AsyncLifecycle.trackedReady().get(); + AsyncLifecycle.trackedSleep((short)1).get(); + AsyncLifecycle.trackedWakeStorm((short)1, (short)3).get(); + AsyncLifecycle.trackedSleep((short)50).cancel(true); + AsyncLifecycle.trackedWakeStorm((short)50, (short)5).cancel(true); + awaitAllDropped("single futures"); + assert AsyncLifecycle.createdCount() == 5 : "expected 5 created, got " + AsyncLifecycle.createdCount(); + System.out.println("drop accounting (5 futures) ... ok"); + } + + { + AsyncLifecycle.resetCounts(); + int threads = 8, iters = 5_000; + var failure = new AtomicReference(); + Thread[] workers = new Thread[threads]; + for (int t = 0; t < threads; t++) { + final int seed = t; + workers[t] = new Thread(() -> { + try { + for (int i = 0; i < iters; i++) { + CompletableFuture job = switch ((i + seed) % 3) { + case 0 -> AsyncLifecycle.trackedSleep((short)1); + case 1 -> AsyncLifecycle.trackedWakeStorm((short)1, (short)1); + default -> AsyncLifecycle.trackedReady(); + }; + if (i % 2 == 0) { + Thread.yield(); + } + job.cancel(true); + } + } catch (Throwable e) { + failure.compareAndSet(null, e); + } + }); + workers[t].start(); + } + for (Thread w : workers) { + w.join(); + } + assert failure.get() == null : "cancel storm threw: " + failure.get(); + awaitAllDropped("cancel storm"); + assert AsyncLifecycle.createdCount() == (long) threads * iters; + System.out.println("drop accounting after cancel storm (" + threads + " x " + iters + ") ... ok"); + } + + // cancel() from inside an async callback, i.e. on the executor thread while rust_future_poll + // is on the stack. Freeing here would deadlock on the future's own Rust mutex. + { + AsyncLifecycle.resetCounts(); + var job = new AtomicReference>(); + Notifier cancelSelf = () -> { + boolean cancelled = job.get().cancel(true); + assert cancelled : "cancel from callback returned false"; + return CompletableFuture.completedFuture(null); + }; + var f = AsyncLifecycle.sleepThenNotify((short)10, cancelSelf); + job.set(f); + try { + f.get(); + throw new AssertionError("expected cancellation"); + } catch (java.util.concurrent.CancellationException expected) { + } + awaitAllDropped("cancel from callback"); + System.out.println("cancel from inside async callback ... ok"); + } + + uniffi.async_lifecycle.AsyncContract.run(); + } +} diff --git a/tests/scripts/TestAsyncLifecycle/uniffi/async_lifecycle/AsyncContract.java b/tests/scripts/TestAsyncLifecycle/uniffi/async_lifecycle/AsyncContract.java new file mode 100644 index 0000000..c2cc813 --- /dev/null +++ b/tests/scripts/TestAsyncLifecycle/uniffi/async_lifecycle/AsyncContract.java @@ -0,0 +1,212 @@ +package uniffi.async_lifecycle; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +// Asserts the handle contract uniffi_core documents: free exactly once, and no poll, complete or +// cancel on a handle after it has been freed. +public final class AsyncContract { + static final class Ledger { + final AtomicInteger completes = new AtomicInteger(); + final AtomicInteger frees = new AtomicInteger(); + volatile boolean freed; + // Pipeline stage in progress: at most one thread, re-entrant on an inline executor. + volatile Thread inFlight; + int depth; + } + + // Handle values are heap addresses and are reused after free, so ledgers are per call. + static final ConcurrentLinkedQueue ledgers = new ConcurrentLinkedQueue<>(); + static final ConcurrentLinkedQueue violations = new ConcurrentLinkedQueue<>(); + + static void violate(String what, long handle) { + violations.add(what + " (handle " + Long.toHexString(handle) + ", " + Thread.currentThread().getName() + ")"); + } + + // Returns whether the native call may proceed; a call on a freed handle is skipped. + static boolean enter(Ledger l, String stage, long handle) { + boolean live = !l.freed; + if (!live) { + violate(stage + " after free", handle); + } + Thread me = Thread.currentThread(); + synchronized (l) { + if (l.inFlight != null && l.inFlight != me) { + violate(stage + " concurrent with another pipeline stage", handle); + } + l.inFlight = me; + l.depth++; + } + return live; + } + + static void exit(Ledger l) { + synchronized (l) { + if (--l.depth == 0) { + l.inFlight = null; + } + } + } + + static CompletableFuture call(long handle, Executor executor) { + Ledger l = new Ledger(); + ledgers.add(l); + return UniffiAsyncHelpers.uniffiRustCallAsync( + executor, + handle, + (future, callback, continuation) -> { + boolean live = enter(l, "poll", future); + try { + // Native calls are serialized per handle only after the overlap has been + // recorded, so a violation is reported instead of executed. + synchronized (l) { + if (live && l.freed) { + violate("poll after free, won by free inside enter", future); + live = false; + } + if (live) { + UniffiLib.ffi_uniffi_fixture_async_lifecycle_rust_future_poll_void(future, callback, continuation); + } else { + // Keeps the pipeline draining so the run ends and reports. + UniffiAsyncHelpers.continuationCallback(continuation, UniffiAsyncHelpers.UNIFFI_RUST_FUTURE_POLL_READY); + } + } + } finally { + exit(l); + } + }, + (_allocator, future, status) -> { + boolean live = enter(l, "complete", future); + try { + if (l.completes.incrementAndGet() > 1) { + violate("complete twice", future); + live = false; + } + synchronized (l) { + if (live && l.freed) { + violate("complete after free, won by free inside enter", future); + live = false; + } + if (live) { + UniffiLib.ffi_uniffi_fixture_async_lifecycle_rust_future_complete_void(future, status); + } + } + } finally { + exit(l); + } + }, + (future) -> { + synchronized (l) { + if (l.freed) { + violate("cancel after free", future); + return; + } + UniffiLib.ffi_uniffi_fixture_async_lifecycle_rust_future_cancel_void(future); + } + }, + (future) -> { + if (l.frees.incrementAndGet() > 1) { + violate("free twice", future); + return; + } + if (l.inFlight != null && l.inFlight != Thread.currentThread()) { + violate("free while a pipeline stage is in flight on another thread", future); + } + synchronized (l) { + l.freed = true; + UniffiLib.ffi_uniffi_fixture_async_lifecycle_rust_future_free_void(future); + } + }, + () -> {}, + new UniffiNullRustCallStatusErrorHandler() + ); + } + + static long newHandle(int kind) { + return switch (kind % 3) { + case 0 -> UniffiLib.uniffi_uniffi_fixture_async_lifecycle_fn_func_tracked_ready(); + case 1 -> UniffiLib.uniffi_uniffi_fixture_async_lifecycle_fn_func_tracked_sleep((short) 1); + default -> UniffiLib.uniffi_uniffi_fixture_async_lifecycle_fn_func_tracked_wake_storm((short) 1, (short) 2); + }; + } + + // Cancel timings vary so cancel lands at every pipeline stage. + static void storm(String name, Executor executor, int threads, int iters, ScheduledExecutorService canceller) throws Exception { + ledgers.clear(); + violations.clear(); + List workers = new ArrayList<>(); + ConcurrentLinkedQueue> futures = new ConcurrentLinkedQueue<>(); + for (int t = 0; t < threads; t++) { + final int seed = t; + Thread w = new Thread(() -> { + var rnd = ThreadLocalRandom.current(); + for (int i = 0; i < iters; i++) { + var f = call(newHandle(i + seed), executor); + futures.add(f); + switch (rnd.nextInt(4)) { + case 0 -> {} + case 1 -> f.cancel(true); + case 2 -> { + Thread.yield(); + f.cancel(true); + } + default -> canceller.schedule(() -> f.cancel(true), rnd.nextInt(3), TimeUnit.MILLISECONDS); + } + } + }, name + "-worker-" + t); + workers.add(w); + w.start(); + } + for (Thread w : workers) { + w.join(); + } + for (var f : futures) { + try { + f.get(10, TimeUnit.SECONDS); + } catch (java.util.concurrent.CancellationException | java.util.concurrent.ExecutionException expected) { + } + } + // free runs after the future completes. + long deadline = System.nanoTime() + 10_000_000_000L; + while (ledgers.stream().anyMatch(l -> l.frees.get() == 0)) { + if (System.nanoTime() > deadline) { + long leaked = ledgers.stream().filter(l -> l.frees.get() == 0).count(); + throw new AssertionError(name + ": " + leaked + " handles never freed"); + } + Thread.sleep(5); + } + if (!violations.isEmpty()) { + throw new AssertionError(name + ": " + violations.size() + " contract violations, first: " + violations.peek()); + } + System.out.println("async handle contract [" + name + "] (" + ledgers.size() + " futures) ... ok"); + } + + public static void run() throws Exception { + ScheduledExecutorService canceller = Executors.newScheduledThreadPool(2); + ExecutorService single = Executors.newSingleThreadExecutor(); + ScheduledExecutorService jitterPool = Executors.newScheduledThreadPool(4); + Executor jittery = r -> jitterPool.schedule(r, ThreadLocalRandom.current().nextInt(3), TimeUnit.MILLISECONDS); + Executor rejecting = r -> { throw new RejectedExecutionException("rejecting executor"); }; + try { + storm("common pool", java.util.concurrent.ForkJoinPool.commonPool(), 8, 5_000, canceller); + storm("inline executor", Runnable::run, 8, 2_000, canceller); + storm("single thread executor", single, 4, 2_000, canceller); + storm("jittery executor", jittery, 4, 500, canceller); + storm("rejecting executor", rejecting, 4, 500, canceller); + } finally { + canceller.shutdownNow(); + single.shutdownNow(); + jitterPool.shutdownNow(); + } + } +} diff --git a/tests/scripts/TestNameCollisions.java b/tests/scripts/TestNameCollisions.java index 2113dfa..fbca58a 100644 --- a/tests/scripts/TestNameCollisions.java +++ b/tests/scripts/TestNameCollisions.java @@ -81,6 +81,28 @@ public static void main(String[] args) throws Exception { assert tuple.v1().equals("t") && tuple.v2() == 5L : "tuple variant"; assert NameCollisions.enumNamedValue(new Shadowing.Unit()) == null : "unit has no value"; + // Record and variant fields named after the locals of the generated equals/hashCode. + // These collisions compile either way, so assert behaviour rather than compilation. + Shadowed rec = new Shadowed("o", 1, new byte[] { 1, 2 }); + Shadowed same = NameCollisions.roundtripRecord(rec); + assert rec.equals(rec) : "record equals is not reflexive"; + assert rec.equals(same) : "record equals ignores field values"; + assert !rec.equals(new Shadowed("p", 1, new byte[] { 1, 2 })) : "record equals ignores other"; + assert !rec.equals(new Shadowed("o", 2, new byte[] { 1, 2 })) : "record equals ignores t"; + assert rec.hashCode() == same.hashCode() : "record hashCode unstable"; + assert rec.hashCode() != new Shadowed("o", 1, new byte[] { 3 }).hashCode() + : "record hashCode ignores result"; + + var variant = new ShadowingArrays.Named("o", 1, new byte[] { 1, 2 }); + var variantBack = (ShadowingArrays.Named) NameCollisions.roundtripEnumArrays(variant); + assert variant.equals(variant) : "variant equals is not reflexive"; + assert variant.equals(variantBack) : "variant equals ignores field values"; + assert !variant.equals(new ShadowingArrays.Named("p", 1, new byte[] { 1, 2 })) + : "variant equals ignores other"; + assert variant.hashCode() == variantBack.hashCode() : "variant hashCode unstable"; + assert variant.hashCode() != new ShadowingArrays.Named("o", 1, new byte[] { 3 }).hashCode() + : "variant hashCode ignores result"; + // Error variant fields named after the converter's parameter and binding. try { NameCollisions.throwNamed("value", 42); @@ -92,10 +114,11 @@ public static void main(String[] args) throws Exception { // Function and method parameters named after call-path locals. assert NameCollisions.syncFn("a", "b", "c", "d", "e").equals("a|b|c|d|e") : "syncFn"; - assert NameCollisions.asyncFn("a", "b", "c").get().equals("a|b|c") : "asyncFn"; + assert NameCollisions.asyncFn("a", "b", "c", "d", "e", "f", "g", "h").get() + .equals("a|b|c|d|e|f|g|h") : "asyncFn"; try (Holder holder = new Holder("tag")) { assert holder.syncMethod("h", "o").equals("tag|h|o") : "syncMethod"; - assert holder.asyncMethod("h", "x", "i").get().equals("tag|h|x|i") : "asyncMethod"; + assert holder.asyncMethod("h", "x", "i", "j").get().equals("tag|h|x|i|j") : "asyncMethod"; } // Callback interface parameters named after the implementation class's locals. diff --git a/tests/tests.rs b/tests/tests.rs index fa09ace..10b7b15 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -116,9 +116,12 @@ fn run_test(fixture_name: &str, test_file: &str) -> Result<()> { let jar_file = build_jar(fixture_name, &out_dir)?; // compile test + // Helper sources in a package directory beside the test compile from here, e.g. to reach + // package-private generated helpers. + let test_dir = test_path.parent().unwrap().to_path_buf(); let status = Command::new("javac") .arg("-classpath") - .arg(calc_classpath(vec![&out_dir, &jar_file])) + .arg(calc_classpath(vec![&out_dir, &jar_file, &test_dir])) // Our tests should not produce any warnings. .arg("-Werror") .arg(&test_path) @@ -132,7 +135,7 @@ fn run_test(fixture_name: &str, test_file: &str) -> Result<()> { // run resulting test let compiled_path = test_path.file_stem().unwrap(); - let run_status = Command::new("java") + let run_status = java_command() // allow for runtime assertions .arg("-ea") // Enable FFM native access @@ -140,11 +143,7 @@ fn run_test(fixture_name: &str, test_file: &str) -> Result<()> { // Set native library path so System.loadLibrary can find the cdylib .arg(format!("-Djava.library.path={}", native_lib_dir)) .arg("-classpath") - .arg(calc_classpath(vec![ - &out_dir, - &jar_file, - &test_path.parent().unwrap().to_path_buf(), - ])) + .arg(calc_classpath(vec![&out_dir, &jar_file, &test_dir])) .arg(compiled_path) .spawn() .context("Failed to spawn `java` to run Java test")? @@ -222,7 +221,7 @@ fn run_test_with_library_override( // Run with library override set to an absolute path and NO java.library.path, // so this can only work if the generated code uses System.load() for absolute paths. let compiled_path = test_path.file_stem().unwrap(); - let run_status = Command::new("java") + let run_status = java_command() .arg("-ea") .arg("--enable-native-access=ALL-UNNAMED") .arg(format!( @@ -248,6 +247,18 @@ fn run_test_with_library_override( Ok(()) } +/// `java` with allocator poisoning, so a use-after-free of native memory reads a fill pattern +/// instead of plausible data. Each platform ignores the other's variables. +fn java_command() -> Command { + let mut cmd = Command::new("java"); + // glibc: fill allocated and freed memory with 0xa5 and its complement. + cmd.env("GLIBC_TUNABLES", "glibc.malloc.perturb=165"); + // macOS libmalloc: fill freed memory, and abort on access past a guarded large allocation. + cmd.env("MallocScribble", "1"); + cmd.env("MallocGuardEdges", "1"); + cmd +} + /// Get the uniffi_toml of the fixture if it exists. /// It looks for it in the root directory of the project `name`. fn find_uniffi_toml(name: &str) -> Result> { @@ -391,6 +402,7 @@ fixture_tests! { (test_proc_macro, "uniffi-fixture-proc-macro", "scripts/TestProcMacro.java"), (test_rename, "uniffi-fixture-rename", "scripts/TestRename/TestRename.java"), (test_primitive_arrays, "uniffi-fixture-primitive-arrays", "scripts/TestPrimitiveArrays.java"), + (test_async_lifecycle, "uniffi-fixture-async-lifecycle", "scripts/TestAsyncLifecycle/TestAsyncLifecycle.java"), (test_zero_copy, "uniffi-fixture-zero-copy", "scripts/TestZeroCopy.java"), (test_name_collisions, "uniffi-fixture-name-collisions", "scripts/TestNameCollisions.java"), }