| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
//! This module defines a Rust Future that wraps an async foreign function call. |
| 6 |
//! |
| 7 |
//! The general idea is to create a oneshot channel, hand the sender to the foreign side, and |
| 8 |
//! await the receiver side on the Rust side. |
| 9 |
//! |
| 10 |
//! The foreign side should: |
| 11 |
//! * Input a [ForeignFutureCallback] and a `u64` handle in their scaffolding function. |
| 12 |
//! This is the sender, converted to a raw pointer, and an extern "C" function that sends the result. |
| 13 |
//! * Return a [ForeignFuture], which represents the foreign task object corresponding to the async function. |
| 14 |
//! * Call the [ForeignFutureCallback] when the async function completes with: |
| 15 |
//! * The `u64` handle initially passed in |
| 16 |
//! * The `ForeignFutureResult` for the call |
| 17 |
//! * Wait for the [ForeignFutureHandle::free] function to be called to free the task object. |
| 18 |
//! If this is called before the task completes, then the task will be cancelled. |
| 19 |
|
| 20 |
use crate::{oneshot, LiftReturn, RustCallStatus}; |
| 21 |
|
| 22 |
/// Handle for a foreign future |
| 23 |
pub type ForeignFutureHandle = u64; |
| 24 |
|
| 25 |
/// Handle for a callback data associated with a foreign future. |
| 26 |
pub type ForeignFutureCallbackData = *mut (); |
| 27 |
|
| 28 |
/// Callback that's passed to a foreign async functions. |
| 29 |
/// |
| 30 |
/// See `LiftReturn` trait for how this is implemented. |
| 31 |
pub type ForeignFutureCallback<FfiType> = |
| 32 |
extern "C" fn(oneshot_handle: u64, ForeignFutureResult<FfiType>); |
| 33 |
|
| 34 |
/// C struct that represents the result of a foreign future |
| 35 |
#[repr(C)] |
| 36 |
pub struct ForeignFutureResult<T> { |
| 37 |
// Note: for void returns, T is `()`, which isn't directly representable with C since it's a ZST. |
| 38 |
// Foreign code should treat that case as if there was no `return_value` field. |
| 39 |
return_value: T, |
| 40 |
call_status: RustCallStatus, |
| 41 |
} |
| 42 |
|
| 43 |
/// C struct that represents a foreign future, used to perform a call to a foreign async method. |
| 44 |
/// |
| 45 |
/// This is what's returned by the async scaffolding functions. |
| 46 |
#[repr(C)] |
| 47 |
pub struct ForeignFuture { |
| 48 |
pub handle: ForeignFutureHandle, |
| 49 |
pub free: extern "C" fn(handle: ForeignFutureHandle), |
| 50 |
} |
| 51 |
|
| 52 |
impl Drop for ForeignFuture { |
| 53 |
fn drop(&mut self) { |
| 54 |
(self.free)(self.handle) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
unsafe impl Send for ForeignFuture {} |
| 59 |
|
| 60 |
pub async fn foreign_async_call<F, T, UT>(call_scaffolding_function: F) -> T |
| 61 |
where |
| 62 |
F: FnOnce(ForeignFutureCallback<T::ReturnType>, u64) -> ForeignFuture, |
| 63 |
T: LiftReturn<UT>, |
| 64 |
{ |
| 65 |
let (sender, receiver) = oneshot::channel::<ForeignFutureResult<T::ReturnType>>(); |
| 66 |
// Keep the ForeignFuture around, even though we don't ever use it. |
| 67 |
// The important thing is that the ForeignFuture will be dropped when this Future is. |
| 68 |
let _foreign_future = |
| 69 |
call_scaffolding_function(foreign_future_complete::<T, UT>, sender.into_raw() as u64); |
| 70 |
let result = receiver.await; |
| 71 |
T::lift_foreign_return(result.return_value, result.call_status) |
| 72 |
} |
| 73 |
|
| 74 |
pub extern "C" fn foreign_future_complete<T: LiftReturn<UT>, UT>( |
| 75 |
oneshot_handle: u64, |
| 76 |
result: ForeignFutureResult<T::ReturnType>, |
| 77 |
) { |
| 78 |
let channel = unsafe { oneshot::Sender::from_raw(oneshot_handle as *mut ()) }; |
| 79 |
channel.send(result); |
| 80 |
} |
| 81 |
|
| 82 |
#[cfg(test)] |
| 83 |
mod test { |
| 84 |
use super::*; |
| 85 |
use crate::{Lower, RustBuffer}; |
| 86 |
use once_cell::sync::OnceCell; |
| 87 |
use std::{ |
| 88 |
future::Future, |
| 89 |
pin::Pin, |
| 90 |
sync::{ |
| 91 |
atomic::{AtomicU32, Ordering}, |
| 92 |
Arc, |
| 93 |
}, |
| 94 |
task::{Context, Poll, Wake}, |
| 95 |
}; |
| 96 |
|
| 97 |
struct MockForeignFuture { |
| 98 |
freed: Arc<AtomicU32>, |
| 99 |
callback_info: Arc<OnceCell<(ForeignFutureCallback<RustBuffer>, u64)>>, |
| 100 |
rust_future: Option<Pin<Box<dyn Future<Output = String>>>>, |
| 101 |
} |
| 102 |
|
| 103 |
impl MockForeignFuture { |
| 104 |
fn new() -> Self { |
| 105 |
let callback_info = Arc::new(OnceCell::new()); |
| 106 |
let freed = Arc::new(AtomicU32::new(0)); |
| 107 |
|
| 108 |
let rust_future: Pin<Box<dyn Future<Output = String>>> = { |
| 109 |
let callback_info = callback_info.clone(); |
| 110 |
let freed = freed.clone(); |
| 111 |
Box::pin(foreign_async_call::<_, String, crate::UniFfiTag>( |
| 112 |
move |callback, data| { |
| 113 |
callback_info.set((callback, data)).unwrap(); |
| 114 |
ForeignFuture { |
| 115 |
handle: Arc::into_raw(freed) as *mut () as u64, |
| 116 |
free: Self::free, |
| 117 |
} |
| 118 |
}, |
| 119 |
)) |
| 120 |
}; |
| 121 |
let rust_future = Some(rust_future); |
| 122 |
let mut mock_foreign_future = Self { |
| 123 |
freed, |
| 124 |
callback_info, |
| 125 |
rust_future, |
| 126 |
}; |
| 127 |
// Poll the future once, to start it up. This ensures that `callback_info` is set. |
| 128 |
let _ = mock_foreign_future.poll(); |
| 129 |
mock_foreign_future |
| 130 |
} |
| 131 |
|
| 132 |
fn poll(&mut self) -> Poll<String> { |
| 133 |
let waker = Arc::new(NoopWaker).into(); |
| 134 |
let mut context = Context::from_waker(&waker); |
| 135 |
self.rust_future |
| 136 |
.as_mut() |
| 137 |
.unwrap() |
| 138 |
.as_mut() |
| 139 |
.poll(&mut context) |
| 140 |
} |
| 141 |
|
| 142 |
fn complete_success(&self, value: String) { |
| 143 |
let (callback, data) = self.callback_info.get().unwrap(); |
| 144 |
callback( |
| 145 |
*data, |
| 146 |
ForeignFutureResult { |
| 147 |
return_value: <String as Lower<crate::UniFfiTag>>::lower(value), |
| 148 |
call_status: RustCallStatus::default(), |
| 149 |
}, |
| 150 |
); |
| 151 |
} |
| 152 |
|
| 153 |
fn complete_error(&self, error_message: String) { |
| 154 |
let (callback, data) = self.callback_info.get().unwrap(); |
| 155 |
callback( |
| 156 |
*data, |
| 157 |
ForeignFutureResult { |
| 158 |
return_value: RustBuffer::default(), |
| 159 |
call_status: RustCallStatus::error(error_message), |
| 160 |
}, |
| 161 |
); |
| 162 |
} |
| 163 |
|
| 164 |
fn drop_future(&mut self) { |
| 165 |
self.rust_future = None |
| 166 |
} |
| 167 |
|
| 168 |
fn free_count(&self) -> u32 { |
| 169 |
self.freed.load(Ordering::Relaxed) |
| 170 |
} |
| 171 |
|
| 172 |
extern "C" fn free(handle: u64) { |
| 173 |
let flag = unsafe { Arc::from_raw(handle as *mut AtomicU32) }; |
| 174 |
flag.fetch_add(1, Ordering::Relaxed); |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
struct NoopWaker; |
| 179 |
|
| 180 |
impl Wake for NoopWaker { |
| 181 |
fn wake(self: Arc<Self>) {} |
| 182 |
} |
| 183 |
|
| 184 |
#[test] |
| 185 |
fn test_foreign_future() { |
| 186 |
let mut mock_foreign_future = MockForeignFuture::new(); |
| 187 |
assert_eq!(mock_foreign_future.poll(), Poll::Pending); |
| 188 |
mock_foreign_future.complete_success("It worked!".to_owned()); |
| 189 |
assert_eq!( |
| 190 |
mock_foreign_future.poll(), |
| 191 |
Poll::Ready("It worked!".to_owned()) |
| 192 |
); |
| 193 |
// Since the future is complete, it should free the foreign future |
| 194 |
assert_eq!(mock_foreign_future.free_count(), 1); |
| 195 |
} |
| 196 |
|
| 197 |
#[test] |
| 198 |
#[should_panic] |
| 199 |
fn test_foreign_future_error() { |
| 200 |
let mut mock_foreign_future = MockForeignFuture::new(); |
| 201 |
assert_eq!(mock_foreign_future.poll(), Poll::Pending); |
| 202 |
mock_foreign_future.complete_error("It Failed!".to_owned()); |
| 203 |
let _ = mock_foreign_future.poll(); |
| 204 |
} |
| 205 |
|
| 206 |
#[test] |
| 207 |
fn test_drop_after_complete() { |
| 208 |
let mut mock_foreign_future = MockForeignFuture::new(); |
| 209 |
mock_foreign_future.complete_success("It worked!".to_owned()); |
| 210 |
assert_eq!(mock_foreign_future.free_count(), 0); |
| 211 |
assert_eq!( |
| 212 |
mock_foreign_future.poll(), |
| 213 |
Poll::Ready("It worked!".to_owned()) |
| 214 |
); |
| 215 |
// Dropping the future after it's complete should not panic, and not cause a double-free |
| 216 |
mock_foreign_future.drop_future(); |
| 217 |
assert_eq!(mock_foreign_future.free_count(), 1); |
| 218 |
} |
| 219 |
|
| 220 |
#[test] |
| 221 |
fn test_drop_before_complete() { |
| 222 |
let mut mock_foreign_future = MockForeignFuture::new(); |
| 223 |
mock_foreign_future.complete_success("It worked!".to_owned()); |
| 224 |
// Dropping the future before it's complete should cancel the future |
| 225 |
assert_eq!(mock_foreign_future.free_count(), 0); |
| 226 |
mock_foreign_future.drop_future(); |
| 227 |
assert_eq!(mock_foreign_future.free_count(), 1); |
| 228 |
} |
| 229 |
} |