diff options
Diffstat (limited to 'third_party/rust/uniffi/src/ffi')
-rw-r--r-- | third_party/rust/uniffi/src/ffi/ffidefault.rs | 52 | ||||
-rw-r--r-- | third_party/rust/uniffi/src/ffi/foreignbytes.rs | 118 | ||||
-rw-r--r-- | third_party/rust/uniffi/src/ffi/foreigncallbacks.rs | 229 | ||||
-rw-r--r-- | third_party/rust/uniffi/src/ffi/mod.rs | 15 | ||||
-rw-r--r-- | third_party/rust/uniffi/src/ffi/rustbuffer.rs | 353 | ||||
-rw-r--r-- | third_party/rust/uniffi/src/ffi/rustcalls.rs | 279 |
6 files changed, 1046 insertions, 0 deletions
diff --git a/third_party/rust/uniffi/src/ffi/ffidefault.rs b/third_party/rust/uniffi/src/ffi/ffidefault.rs new file mode 100644 index 0000000000..f247312be8 --- /dev/null +++ b/third_party/rust/uniffi/src/ffi/ffidefault.rs @@ -0,0 +1,52 @@ +/* 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/. */ + +//! FfiDefault trait +//! +//! When we make a FFI call into Rust we always need to return a value, even if that value will be +//! ignored because we're flagging an exception. This trait defines what that value is for our +//! supported FFI types. + +use paste::paste; + +pub trait FfiDefault { + fn ffi_default() -> Self; +} + +// Most types can be handled by delegating to Default +macro_rules! impl_ffi_default_with_default { + ($($T:ty,)+) => { impl_ffi_default_with_default!($($T),+); }; + ($($T:ty),*) => { + $( + paste! { + impl FfiDefault for $T { + fn ffi_default() -> Self { + $T::default() + } + } + } + )* + }; +} + +impl_ffi_default_with_default! { + i8, u8, i16, u16, i32, u32, i64, u64, f32, f64 +} + +// Implement FfiDefault for the remaining types +impl FfiDefault for () { + fn ffi_default() {} +} + +impl FfiDefault for *const std::ffi::c_void { + fn ffi_default() -> Self { + std::ptr::null() + } +} + +impl FfiDefault for crate::RustBuffer { + fn ffi_default() -> Self { + unsafe { Self::from_raw_parts(std::ptr::null_mut(), 0, 0) } + } +} diff --git a/third_party/rust/uniffi/src/ffi/foreignbytes.rs b/third_party/rust/uniffi/src/ffi/foreignbytes.rs new file mode 100644 index 0000000000..5ec93118ad --- /dev/null +++ b/third_party/rust/uniffi/src/ffi/foreignbytes.rs @@ -0,0 +1,118 @@ +/* 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/. */ + +/// Support for reading a slice of foreign-language-allocated bytes over the FFI. +/// +/// Foreign language code can pass a slice of bytes by providing a data pointer +/// and length, and this struct provides a convenient wrapper for working with +/// that pair. Naturally, this can be tremendously unsafe! So here are the details: +/// +/// * The foreign language code must ensure the provided buffer stays alive +/// and unchanged for the duration of the call to which the `ForeignBytes` +/// struct was provided. +/// +/// To work with the bytes in Rust code, use `as_slice()` to view the data +/// as a `&[u8]`. +/// +/// Implementation note: all the fields of this struct are private and it has no +/// constructors, so consuming crates cant create instances of it. If you've +/// got a `ForeignBytes`, then you received it over the FFI and are assuming that +/// the foreign language code is upholding the above invariants. +/// +/// This struct is based on `ByteBuffer` from the `ffi-support` crate, but modified +/// to give a read-only view of externally-provided bytes. +#[repr(C)] +pub struct ForeignBytes { + /// The length of the pointed-to data. + /// We use an `i32` for compatibility with JNA. + len: i32, + /// The pointer to the foreign-owned bytes. + data: *const u8, +} + +impl ForeignBytes { + /// Creates a `ForeignBytes` from its constituent fields. + /// + /// This is intended mainly as an internal convenience function and should not + /// be used outside of this module. + /// + /// # Safety + /// + /// You must ensure that the raw parts uphold the documented invariants of this class. + pub unsafe fn from_raw_parts(data: *const u8, len: i32) -> Self { + Self { len, data } + } + + /// View the foreign bytes as a `&[u8]`. + /// + /// # Panics + /// + /// Panics if the provided struct has a null pointer but non-zero length. + /// Panics if the provided length is negative. + pub fn as_slice(&self) -> &[u8] { + if self.data.is_null() { + assert!(self.len == 0, "null ForeignBytes had non-zero length"); + &[] + } else { + unsafe { std::slice::from_raw_parts(self.data, self.len()) } + } + } + + /// Get the length of this slice of bytes. + /// + /// # Panics + /// + /// Panics if the provided length is negative. + pub fn len(&self) -> usize { + self.len + .try_into() + .expect("bytes length negative or overflowed") + } + + /// Returns true if the length of this slice of bytes is 0. + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn test_foreignbytes_access() { + let v = vec![1u8, 2, 3]; + let fbuf = unsafe { ForeignBytes::from_raw_parts(v.as_ptr(), 3) }; + assert_eq!(fbuf.len(), 3); + assert_eq!(fbuf.as_slice(), &[1u8, 2, 3]); + } + + #[test] + fn test_foreignbytes_empty() { + let v = Vec::<u8>::new(); + let fbuf = unsafe { ForeignBytes::from_raw_parts(v.as_ptr(), 0) }; + assert_eq!(fbuf.len(), 0); + assert_eq!(fbuf.as_slice(), &[0u8; 0]); + } + + #[test] + fn test_foreignbytes_null_means_empty() { + let fbuf = unsafe { ForeignBytes::from_raw_parts(std::ptr::null_mut(), 0) }; + assert_eq!(fbuf.as_slice(), &[0u8; 0]); + } + + #[test] + #[should_panic] + fn test_foreignbytes_null_must_have_zero_length() { + let fbuf = unsafe { ForeignBytes::from_raw_parts(std::ptr::null_mut(), 12) }; + fbuf.as_slice(); + } + + #[test] + #[should_panic] + fn test_foreignbytes_provided_len_must_be_non_negative() { + let v = vec![0u8, 1, 2]; + let fbuf = unsafe { ForeignBytes::from_raw_parts(v.as_ptr(), -1) }; + fbuf.as_slice(); + } +} diff --git a/third_party/rust/uniffi/src/ffi/foreigncallbacks.rs b/third_party/rust/uniffi/src/ffi/foreigncallbacks.rs new file mode 100644 index 0000000000..092b635255 --- /dev/null +++ b/third_party/rust/uniffi/src/ffi/foreigncallbacks.rs @@ -0,0 +1,229 @@ +/* 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/. */ + +//! Callback interfaces are traits specified in UDL which can be implemented by foreign languages. +//! +//! # Using callback interfaces +//! +//! 1. Define a Rust trait. +//! +//! This toy example defines a way of Rust accessing a key-value store exposed +//! by the host operating system (e.g. the key chain). +//! +//! ``` +//! trait Keychain: Send { +//! fn get(&self, key: String) -> Option<String>; +//! fn put(&self, key: String, value: String); +//! } +//! ``` +//! +//! 2. Define a callback interface in the UDL +//! +//! ```idl +//! callback interface Keychain { +//! string? get(string key); +//! void put(string key, string data); +//! }; +//! ``` +//! +//! 3. And allow it to be passed into Rust. +//! +//! Here, we define a constructor to pass the keychain to rust, and then another method +//! which may use it. +//! +//! In UDL: +//! ```idl +//! object Authenticator { +//! constructor(Keychain keychain); +//! void login(); +//! } +//! ``` +//! +//! In Rust: +//! +//! ``` +//!# trait Keychain: Send { +//!# fn get(&self, key: String) -> Option<String>; +//!# fn put(&self, key: String, value: String); +//!# } +//! struct Authenticator { +//! keychain: Box<dyn Keychain>, +//! } +//! +//! impl Authenticator { +//! pub fn new(keychain: Box<dyn Keychain>) -> Self { +//! Self { keychain } +//! } +//! pub fn login(&self) { +//! let username = self.keychain.get("username".into()); +//! let password = self.keychain.get("password".into()); +//! } +//! } +//! ``` +//! 4. Create an foreign language implementation of the callback interface. +//! +//! In this example, here's a Kotlin implementation. +//! +//! ```kotlin +//! class AndroidKeychain: Keychain { +//! override fun get(key: String): String? { +//! // … elide the implementation. +//! return value +//! } +//! override fun put(key: String) { +//! // … elide the implementation. +//! } +//! } +//! ``` +//! 5. Pass the implementation to Rust. +//! +//! Again, in Kotlin +//! +//! ```kotlin +//! val authenticator = Authenticator(AndroidKeychain()) +//! authenticator.login() +//! ``` +//! +//! # How it works. +//! +//! ## High level +//! +//! Uniffi generates a protocol or interface in client code in the foreign language must implement. +//! +//! For each callback interface, a `CallbackInternals` (on the Foreign Language side) and `ForeignCallbackInternals` +//! (on Rust side) manages the process through a `ForeignCallback`. There is one `ForeignCallback` per callback interface. +//! +//! Passing a callback interface implementation from foreign language (e.g. `AndroidKeychain`) into Rust causes the +//! `KeychainCallbackInternals` to store the instance in a handlemap. +//! +//! The object handle is passed over to Rust, and used to instantiate a struct `KeychainProxy` which implements +//! the trait. This proxy implementation is generate by Uniffi. The `KeychainProxy` object is then passed to +//! client code as `Box<dyn Keychain>`. +//! +//! Methods on `KeychainProxy` objects (e.g. `self.keychain.get("username".into())`) encode the arguments into a `RustBuffer`. +//! Using the `ForeignCallback`, it calls the `CallbackInternals` object on the foreign language side using the +//! object handle, and the method selector. +//! +//! The `CallbackInternals` object unpacks the arguments from the passed buffer, gets the object out from the handlemap, +//! and calls the actual implementation of the method. +//! +//! If there's a return value, it is packed up in to another `RustBuffer` and used as the return value for +//! `ForeignCallback`. The caller of `ForeignCallback`, the `KeychainProxy` unpacks the returned buffer into the correct +//! type and then returns to client code. +//! + +use super::RustBuffer; +use std::fmt; +use std::os::raw::c_int; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// ForeignCallback is the Rust representation of a foreign language function. +/// It is the basis for all callbacks interfaces. It is registered exactly once per callback interface, +/// at library start up time. +/// Calling this method is only done by generated objects which mirror callback interfaces objects in the foreign language. +/// +/// * The `handle` is the key into a handle map on the other side of the FFI used to look up the foreign language object +/// that implements the callback interface/trait. +/// * The `method` selector specifies the method that will be called on the object, by looking it up in a list of methods from +/// the IDL. The index is 1 indexed. Note that the list of methods is generated by at uniffi from the IDL and used in all +/// bindings: so we can rely on the method list being stable within the same run of uniffi. +/// * `args` is a serialized buffer of arguments to the function. UniFFI will deserialize it before +/// passing individual arguments to the user's callback. +/// * `buf_ptr` is a pointer to where the resulting buffer will be written. UniFFI will allocate a +/// buffer to write the result into. +/// * A callback returns: +/// - `-2` An error occured that was serialized to buf_ptr +/// - `-1` An unexpected error ocurred +/// - `0` is a deprecated way to signal that if the call succeeded, but did not modify buf_ptr +/// - `1` If the call succeeded. For non-void functions the return value should be serialized +/// to buf_ptr. +/// Note: The output buffer might still contain 0 bytes of data. +pub type ForeignCallback = unsafe extern "C" fn( + handle: u64, + method: u32, + args: RustBuffer, + buf_ptr: *mut RustBuffer, +) -> c_int; + +/// The method index used by the Drop trait to communicate to the foreign language side that Rust has finished with it, +/// and it can be deleted from the handle map. +pub const IDX_CALLBACK_FREE: u32 = 0; + +// Overly-paranoid sanity checking to ensure that these types are +// convertible between each-other. `transmute` actually should check this for +// us too, but this helps document the invariants we rely on in this code. +// +// Note that these are guaranteed by +// https://rust-lang.github.io/unsafe-code-guidelines/layout/function-pointers.html +// and thus this is a little paranoid. +static_assertions::assert_eq_size!(usize, ForeignCallback); +static_assertions::assert_eq_size!(usize, Option<ForeignCallback>); + +/// Struct to hold a foreign callback. +pub struct ForeignCallbackInternals { + callback_ptr: AtomicUsize, +} + +const EMPTY_PTR: usize = 0; + +impl ForeignCallbackInternals { + pub const fn new() -> Self { + ForeignCallbackInternals { + callback_ptr: AtomicUsize::new(EMPTY_PTR), + } + } + + pub fn set_callback(&self, callback: ForeignCallback) { + let as_usize = callback as usize; + let old_ptr = self.callback_ptr.compare_exchange( + EMPTY_PTR, + as_usize, + Ordering::SeqCst, + Ordering::SeqCst, + ); + match old_ptr { + // We get the previous value back. If this is anything except EMPTY_PTR, + // then this has been set before we get here. + Ok(EMPTY_PTR) => (), + _ => + // This is an internal bug, the other side of the FFI should ensure + // it sets this only once. + { + panic!("Bug: call set_callback multiple times. This is likely a uniffi bug") + } + }; + } + + pub fn get_callback(&self) -> Option<ForeignCallback> { + let ptr_value = self.callback_ptr.load(Ordering::SeqCst); + unsafe { std::mem::transmute::<usize, Option<ForeignCallback>>(ptr_value) } + } +} + +/// Used when internal/unexpected error happened when calling a foreign callback, for example when +/// a unknown exception is raised +/// +/// User callback error types must implement a From impl from this type to their own error type. +#[derive(Debug)] +pub struct UnexpectedUniFFICallbackError { + pub reason: String, +} + +impl UnexpectedUniFFICallbackError { + pub fn from_reason(reason: String) -> Self { + Self { reason } + } +} + +impl fmt::Display for UnexpectedUniFFICallbackError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "UnexpectedUniFFICallbackError(reason: {:?})", + self.reason + ) + } +} + +impl std::error::Error for UnexpectedUniFFICallbackError {} diff --git a/third_party/rust/uniffi/src/ffi/mod.rs b/third_party/rust/uniffi/src/ffi/mod.rs new file mode 100644 index 0000000000..73ee721435 --- /dev/null +++ b/third_party/rust/uniffi/src/ffi/mod.rs @@ -0,0 +1,15 @@ +/* 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/. */ + +pub mod ffidefault; +pub mod foreignbytes; +pub mod foreigncallbacks; +pub mod rustbuffer; +pub mod rustcalls; + +use ffidefault::FfiDefault; +pub use foreignbytes::*; +pub use foreigncallbacks::*; +pub use rustbuffer::*; +pub use rustcalls::*; diff --git a/third_party/rust/uniffi/src/ffi/rustbuffer.rs b/third_party/rust/uniffi/src/ffi/rustbuffer.rs new file mode 100644 index 0000000000..63af586fb6 --- /dev/null +++ b/third_party/rust/uniffi/src/ffi/rustbuffer.rs @@ -0,0 +1,353 @@ +/* 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/. */ + +use crate::ffi::{call_with_output, ForeignBytes, RustCallStatus}; + +/// Support for passing an allocated-by-Rust buffer of bytes over the FFI. +/// +/// We can pass a `Vec<u8>` to foreign language code by decomposing it into +/// its raw parts (buffer pointer, length, and capacity) and passing those +/// around as a struct. Naturally, this can be tremendously unsafe! So here +/// are the details: +/// +/// * `RustBuffer` structs must only ever be constructed from a `Vec<u8>`, +/// either explicitly via `RustBuffer::from_vec` or indirectly by calling +/// one of the `RustBuffer::new*` constructors. +/// +/// * `RustBuffer` structs do not implement `Drop`, since they are intended +/// to be passed to foreign-language code outside of the control of Rust's +/// ownership system. To avoid memory leaks they *must* passed back into +/// Rust and either explicitly destroyed using `RustBuffer::destroy`, or +/// converted back to a `Vec<u8>` using `RustBuffer::destroy_into_vec` +/// (which will then be dropped via Rust's usual ownership-tracking system). +/// +/// Foreign-language code should not construct `RustBuffer` structs other than +/// by receiving them from a call into the Rust code, and should not modify them +/// apart from the following safe operations: +/// +/// * Writing bytes into the buffer pointed to by `data`, without writing +/// beyond the indicated `capacity`. +/// +/// * Adjusting the `len` property to indicate the amount of data written, +/// while ensuring that 0 <= `len` <= `capacity`. +/// +/// * As a special case, constructing a `RustBuffer` with zero capacity, zero +/// length, and a null `data` pointer to indicate an empty buffer. +/// +/// In particular, it is not safe for foreign-language code to construct a `RustBuffer` +/// that points to its own allocated memory; use the `ForeignBytes` struct to +/// pass a view of foreign-owned memory in to Rust code. +/// +/// Implementation note: all the fields of this struct are private, so you can't +/// manually construct instances that don't come from a `Vec<u8>`. If you've got +/// a `RustBuffer` then it either came from a public constructor (all of which +/// are safe) or it came from foreign-language code (which should have in turn +/// received it by calling some Rust function, and should be respecting the +/// invariants listed above). +/// +/// This struct is based on `ByteBuffer` from the `ffi-support` crate, but modified +/// to retain unallocated capacity rather than truncating to the occupied length. +#[repr(C)] +pub struct RustBuffer { + /// The allocated capacity of the underlying `Vec<u8>`. + /// In Rust this is a `usize`, but we use an `i32` for compatibility with JNA. + capacity: i32, + /// The occupied length of the underlying `Vec<u8>`. + /// In Rust this is a `usize`, but we use an `i32` for compatibility with JNA. + len: i32, + /// The pointer to the allocated buffer of the `Vec<u8>`. + data: *mut u8, +} + +impl RustBuffer { + /// Creates an empty `RustBuffer`. + /// + /// The buffer will not allocate. + /// The resulting vector will not be automatically dropped; you must + /// arrange to call `destroy` or `destroy_into_vec` when finished with it. + pub fn new() -> Self { + Self::from_vec(Vec::new()) + } + + /// Creates a `RustBuffer` from its constituent fields. + /// + /// This is intended mainly as an internal convenience function and should not + /// be used outside of this module. + /// + /// # Safety + /// + /// You must ensure that the raw parts uphold the documented invariants of this class. + pub unsafe fn from_raw_parts(data: *mut u8, len: i32, capacity: i32) -> Self { + Self { + capacity, + len, + data, + } + } + + /// Get the current length of the buffer, as a `usize`. + /// + /// This is mostly a helper function to convert the `i32` length field + /// into a `usize`, which is what Rust code usually expects. + /// + /// # Panics + /// + /// Panics if called on an invalid struct obtained from foreign-language code, + /// in which the `len` field is negative. + pub fn len(&self) -> usize { + self.len + .try_into() + .expect("buffer length negative or overflowed") + } + + /// Returns true if the length of the buffer is 0. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Creates a `RustBuffer` zero-filed to the requested size. + /// + /// The resulting vector will not be automatically dropped; you must + /// arrange to call `destroy` or `destroy_into_vec` when finished with it. + /// + /// # Panics + /// + /// Panics if the requested size is too large to fit in an `i32`, and + /// hence would risk incompatibility with some foreign-language code. + pub fn new_with_size(size: usize) -> Self { + assert!( + size < i32::MAX as usize, + "RustBuffer requested size too large" + ); + Self::from_vec(vec![0u8; size]) + } + + /// Consumes a `Vec<u8>` and returns its raw parts as a `RustBuffer`. + /// + /// The resulting vector will not be automatically dropped; you must + /// arrange to call `destroy` or `destroy_into_vec` when finished with it. + /// + /// # Panics + /// + /// Panics if the vector's length or capacity are too large to fit in an `i32`, + /// and hence would risk incompatibility with some foreign-language code. + pub fn from_vec(v: Vec<u8>) -> Self { + let capacity = i32::try_from(v.capacity()).expect("buffer capacity cannot fit into a i32."); + let len = i32::try_from(v.len()).expect("buffer length cannot fit into a i32."); + let mut v = std::mem::ManuallyDrop::new(v); + unsafe { Self::from_raw_parts(v.as_mut_ptr(), len, capacity) } + } + + /// Converts this `RustBuffer` back into an owned `Vec<u8>`. + /// + /// This restores ownership of the underlying buffer to Rust, meaning it will + /// be dropped when the `Vec<u8>` is dropped. The `RustBuffer` *must* have been + /// previously obtained from a valid `Vec<u8>` owned by this Rust code. + /// + /// # Panics + /// + /// Panics if called on an invalid struct obtained from foreign-language code, + /// which does not respect the invairiants on `len` and `capacity`. + pub fn destroy_into_vec(self) -> Vec<u8> { + // Rust will never give us a null `data` pointer for a `Vec`, but + // foreign-language code can use it to cheaply pass an empty buffer. + if self.data.is_null() { + assert!(self.capacity == 0, "null RustBuffer had non-zero capacity"); + assert!(self.len == 0, "null RustBuffer had non-zero length"); + vec![] + } else { + let capacity: usize = self + .capacity + .try_into() + .expect("buffer capacity negative or overflowed"); + let len: usize = self + .len + .try_into() + .expect("buffer length negative or overflowed"); + assert!(len <= capacity, "RustBuffer length exceeds capacity"); + unsafe { Vec::from_raw_parts(self.data, len, capacity) } + } + } + + /// Reclaim memory stored in this `RustBuffer`. + /// + /// # Panics + /// + /// Panics if called on an invalid struct obtained from foreign-language code, + /// which does not respect the invairiants on `len` and `capacity`. + pub fn destroy(self) { + drop(self.destroy_into_vec()); + } +} + +impl Default for RustBuffer { + fn default() -> Self { + Self::new() + } +} + +// extern "C" functions for the RustBuffer functionality. +// +// These are used in two ways: +// 1. Code that statically links to UniFFI can use these directly to handle RustBuffer +// allocation/destruction. The plan is to use this for the Firefox desktop JS bindings. +// +// 2. The scaffolding code re-exports these functions, prefixed with the component name and UDL +// hash This creates a separate set of functions for each UniFFIed component, which is needed +// in the case where we create multiple dylib artifacts since each dylib will have its own +// allocator. + +/// This helper allocates a new byte buffer owned by the Rust code, and returns it +/// to the foreign-language code as a `RustBuffer` struct. Callers must eventually +/// free the resulting buffer, either by explicitly calling [`uniffi_rustbuffer_free`] defined +/// below, or by passing ownership of the buffer back into Rust code. +#[no_mangle] +pub extern "C" fn uniffi_rustbuffer_alloc( + size: i32, + call_status: &mut RustCallStatus, +) -> RustBuffer { + call_with_output(call_status, || { + RustBuffer::new_with_size(size.max(0) as usize) + }) +} + +/// This helper copies bytes owned by the foreign-language code into a new byte buffer owned +/// by the Rust code, and returns it as a `RustBuffer` struct. Callers must eventually +/// free the resulting buffer, either by explicitly calling the destructor defined below, +/// or by passing ownership of the buffer back into Rust code. +/// +/// # Safety +/// This function will dereference a provided pointer in order to copy bytes from it, so +/// make sure the `ForeignBytes` struct contains a valid pointer and length. +#[no_mangle] +pub unsafe extern "C" fn uniffi_rustbuffer_from_bytes( + bytes: ForeignBytes, + call_status: &mut RustCallStatus, +) -> RustBuffer { + call_with_output(call_status, || { + let bytes = bytes.as_slice(); + RustBuffer::from_vec(bytes.to_vec()) + }) +} + +/// Free a byte buffer that had previously been passed to the foreign language code. +/// +/// # Safety +/// The argument *must* be a uniquely-owned `RustBuffer` previously obtained from a call +/// into the Rust code that returned a buffer, or you'll risk freeing unowned memory or +/// corrupting the allocator state. +#[no_mangle] +pub unsafe extern "C" fn uniffi_rustbuffer_free(buf: RustBuffer, call_status: &mut RustCallStatus) { + call_with_output(call_status, || RustBuffer::destroy(buf)) +} + +/// Reserve additional capacity in a byte buffer that had previously been passed to the +/// foreign language code. +/// +/// The first argument *must* be a uniquely-owned `RustBuffer` previously +/// obtained from a call into the Rust code that returned a buffer. Its underlying data pointer +/// will be reallocated if necessary and returned in a new `RustBuffer` struct. +/// +/// The second argument must be the minimum number of *additional* bytes to reserve +/// capacity for in the buffer; it is likely to reserve additional capacity in practice +/// due to amortized growth strategy of Rust vectors. +/// +/// # Safety +/// The first argument *must* be a uniquely-owned `RustBuffer` previously obtained from a call +/// into the Rust code that returned a buffer, or you'll risk freeing unowned memory or +/// corrupting the allocator state. +#[no_mangle] +pub unsafe extern "C" fn uniffi_rustbuffer_reserve( + buf: RustBuffer, + additional: i32, + call_status: &mut RustCallStatus, +) -> RustBuffer { + call_with_output(call_status, || { + let additional: usize = additional + .try_into() + .expect("additional buffer length negative or overflowed"); + let mut v = buf.destroy_into_vec(); + v.reserve(additional); + RustBuffer::from_vec(v) + }) +} + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn test_rustbuffer_from_vec() { + let rbuf = RustBuffer::from_vec(vec![1u8, 2, 3]); + assert_eq!(rbuf.len(), 3); + assert_eq!(rbuf.destroy_into_vec(), vec![1u8, 2, 3]); + } + + #[test] + fn test_rustbuffer_empty() { + let rbuf = RustBuffer::new(); + assert_eq!(rbuf.len(), 0); + // Rust will never give us a null pointer, even for an empty buffer. + assert!(!rbuf.data.is_null()); + assert_eq!(rbuf.destroy_into_vec(), Vec::<u8>::new()); + } + + #[test] + fn test_rustbuffer_new_with_size() { + let rbuf = RustBuffer::new_with_size(5); + assert_eq!(rbuf.destroy_into_vec().as_slice(), &[0u8, 0, 0, 0, 0]); + + let rbuf = RustBuffer::new_with_size(0); + assert!(!rbuf.data.is_null()); + assert_eq!(rbuf.destroy_into_vec().as_slice(), &[0u8; 0]); + } + + #[test] + fn test_rustbuffer_null_means_empty() { + // This is how foreign-language code might cheaply indicate an empty buffer. + let rbuf = unsafe { RustBuffer::from_raw_parts(std::ptr::null_mut(), 0, 0) }; + assert_eq!(rbuf.destroy_into_vec().as_slice(), &[0u8; 0]); + } + + #[test] + #[should_panic] + fn test_rustbuffer_null_must_have_no_capacity() { + // We guard against foreign-language code providing this kind of invalid struct. + let rbuf = unsafe { RustBuffer::from_raw_parts(std::ptr::null_mut(), 0, 1) }; + rbuf.destroy_into_vec(); + } + #[test] + #[should_panic] + fn test_rustbuffer_null_must_have_zero_length() { + // We guard against foreign-language code providing this kind of invalid struct. + let rbuf = unsafe { RustBuffer::from_raw_parts(std::ptr::null_mut(), 12, 0) }; + rbuf.destroy_into_vec(); + } + + #[test] + #[should_panic] + fn test_rustbuffer_provided_capacity_must_be_non_negative() { + // We guard against foreign-language code providing this kind of invalid struct. + let mut v = vec![0u8, 1, 2]; + let rbuf = unsafe { RustBuffer::from_raw_parts(v.as_mut_ptr(), 3, -7) }; + rbuf.destroy_into_vec(); + } + + #[test] + #[should_panic] + fn test_rustbuffer_provided_len_must_be_non_negative() { + // We guard against foreign-language code providing this kind of invalid struct. + let mut v = vec![0u8, 1, 2]; + let rbuf = unsafe { RustBuffer::from_raw_parts(v.as_mut_ptr(), -1, 3) }; + rbuf.destroy_into_vec(); + } + + #[test] + #[should_panic] + fn test_rustbuffer_provided_len_must_not_exceed_capacity() { + // We guard against foreign-language code providing this kind of invalid struct. + let mut v = vec![0u8, 1, 2]; + let rbuf = unsafe { RustBuffer::from_raw_parts(v.as_mut_ptr(), 3, 2) }; + rbuf.destroy_into_vec(); + } +} diff --git a/third_party/rust/uniffi/src/ffi/rustcalls.rs b/third_party/rust/uniffi/src/ffi/rustcalls.rs new file mode 100644 index 0000000000..a22f776d74 --- /dev/null +++ b/third_party/rust/uniffi/src/ffi/rustcalls.rs @@ -0,0 +1,279 @@ +/* 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/. */ + +//! # Low-level support for calling rust functions +//! +//! This module helps the scaffolding code make calls to rust functions and pass back the result to the FFI bindings code. +//! +//! It handles: +//! - Catching panics +//! - Adapting `Result<>` types into either a return value or an error + +use super::FfiDefault; +use crate::{FfiConverter, RustBuffer, RustBufferFfiConverter}; +use anyhow::Result; +use std::mem::MaybeUninit; +use std::panic; + +/// Represents the success/error of a rust call +/// +/// ## Usage +/// +/// - The consumer code creates a `RustCallStatus` with an empty `RustBuffer` and `CALL_SUCCESS` +/// (0) as the status code +/// - A pointer to this object is passed to the rust FFI function. This is an +/// "out parameter" which will be updated with any error that occurred during the function's +/// execution. +/// - After the call, if `code` is `CALL_ERROR` then `error_buf` will be updated to contain +/// the serialized error object. The consumer is responsible for freeing `error_buf`. +/// +/// ## Layout/fields +/// +/// The layout of this struct is important since consumers on the other side of the FFI need to +/// construct it. If this were a C struct, it would look like: +/// +/// ```c,no_run +/// struct RustCallStatus { +/// int8_t code; +/// RustBuffer error_buf; +/// }; +/// ``` +/// +/// #### The `code` field. +/// +/// - `CALL_SUCCESS` (0) for successful calls +/// - `CALL_ERROR` (1) for calls that returned an `Err` value +/// - `CALL_PANIC` (2) for calls that panicked +/// +/// #### The `error_buf` field. +/// +/// - For `CALL_ERROR` this is a `RustBuffer` with the serialized error. The consumer code is +/// responsible for freeing this `RustBuffer`. +#[repr(C)] +pub struct RustCallStatus { + pub code: i8, + // code is signed because unsigned types are experimental in Kotlin + pub error_buf: MaybeUninit<RustBuffer>, + // error_buf is MaybeUninit to avoid dropping the value that the consumer code sends in: + // - Consumers should send in a zeroed out RustBuffer. In this case dropping is a no-op and + // avoiding the drop is a small optimization. + // - If consumers pass in invalid data, then we should avoid trying to drop it. In + // particular, we don't want to try to free any data the consumer has allocated. + // + // `MaybeUninit` requires unsafe code, since we are preventing rust from dropping the value. + // To use this safely we need to make sure that no code paths set this twice, since that will + // leak the first `RustBuffer`. +} + +impl Default for RustCallStatus { + fn default() -> Self { + Self { + code: 0, + error_buf: MaybeUninit::uninit(), + } + } +} + +#[allow(dead_code)] +const CALL_SUCCESS: i8 = 0; // CALL_SUCCESS is set by the calling code +const CALL_ERROR: i8 = 1; +const CALL_PANIC: i8 = 2; + +// A trait for errors that can be thrown to the FFI code +// +// This gets implemented in uniffi_bindgen/src/scaffolding/templates/ErrorTemplate.rs +pub trait FfiError: RustBufferFfiConverter {} + +// Generalized rust call handling function +fn make_call<F, R>(out_status: &mut RustCallStatus, callback: F) -> R +where + F: panic::UnwindSafe + FnOnce() -> Result<R, RustBuffer>, + R: FfiDefault, +{ + let result = panic::catch_unwind(|| { + crate::panichook::ensure_setup(); + callback() + }); + match result { + // Happy path. Note: no need to update out_status in this case because the calling code + // initializes it to CALL_SUCCESS + Ok(Ok(v)) => v, + // Callback returned an Err. + Ok(Err(buf)) => { + out_status.code = CALL_ERROR; + unsafe { + // Unsafe because we're setting the `MaybeUninit` value, see above for safety + // invariants. + out_status.error_buf.as_mut_ptr().write(buf); + } + R::ffi_default() + } + // Callback panicked + Err(cause) => { + out_status.code = CALL_PANIC; + // Try to coerce the cause into a RustBuffer containing a String. Since this code can + // panic, we need to use a second catch_unwind(). + let message_result = panic::catch_unwind(panic::AssertUnwindSafe(move || { + // The documentation suggests that it will *usually* be a str or String. + let message = if let Some(s) = cause.downcast_ref::<&'static str>() { + (*s).to_string() + } else if let Some(s) = cause.downcast_ref::<String>() { + s.clone() + } else { + "Unknown panic!".to_string() + }; + log::error!("Caught a panic calling rust code: {:?}", message); + String::lower(message) + })); + if let Ok(buf) = message_result { + unsafe { + // Unsafe because we're setting the `MaybeUninit` value, see above for safety + // invariants. + out_status.error_buf.as_mut_ptr().write(buf); + } + } + // Ignore the error case. We've done all that we can at this point. In the bindings + // code, we handle this by checking if `error_buf` still has an empty `RustBuffer` and + // using a generic message. + R::ffi_default() + } + } +} + +/// Wrap a rust function call and return the result directly +/// +/// `callback` is responsible for making the call to the Rust function. It must convert any return +/// value into a type that implements `IntoFfi` (typically handled with `FfiConverter::lower()`). +/// +/// - If the function succeeds then the function's return value will be returned to the outer code +/// - If the function panics: +/// - `out_status.code` will be set to `CALL_PANIC` +/// - the return value is undefined +pub fn call_with_output<F, R>(out_status: &mut RustCallStatus, callback: F) -> R +where + F: panic::UnwindSafe + FnOnce() -> R, + R: FfiDefault, +{ + make_call(out_status, || Ok(callback())) +} + +/// Wrap a rust function call that returns a `Result<_, RustBuffer>` +/// +/// `callback` is responsible for making the call to the Rust function. +/// - `callback` must convert any return value into a type that implements `IntoFfi` +/// - `callback` must convert any `Error` the into a `RustBuffer` to be returned over the FFI +/// - (Both of these are typically handled with `FfiConverter::lower()`) +/// +/// - If the function returns an `Ok` value it will be unwrapped and returned +/// - If the function returns an `Err`: +/// - `out_status.code` will be set to `CALL_ERROR` +/// - `out_status.error_buf` will be set to a newly allocated `RustBuffer` containing the error. The calling +/// code is responsible for freeing the `RustBuffer` +/// - the return value is undefined +/// - If the function panics: +/// - `out_status.code` will be set to `CALL_PANIC` +/// - the return value is undefined +pub fn call_with_result<F, R>(out_status: &mut RustCallStatus, callback: F) -> R +where + F: panic::UnwindSafe + FnOnce() -> Result<R, RustBuffer>, + R: FfiDefault, +{ + make_call(out_status, callback) +} + +#[cfg(test)] +mod test { + use super::*; + use crate::{FfiConverter, RustBufferFfiConverter}; + + fn function(a: u8) -> i8 { + match a { + 0 => 100, + x => panic!("Unexpected value: {x}"), + } + } + + fn create_call_status() -> RustCallStatus { + RustCallStatus { + code: 0, + error_buf: MaybeUninit::new(RustBuffer::new()), + } + } + + #[test] + fn test_call_with_output() { + let mut status = create_call_status(); + let return_value = call_with_output(&mut status, || function(0)); + assert_eq!(status.code, CALL_SUCCESS); + assert_eq!(return_value, 100); + + call_with_output(&mut status, || function(1)); + assert_eq!(status.code, CALL_PANIC); + unsafe { + assert_eq!( + String::try_lift(status.error_buf.assume_init()).unwrap(), + "Unexpected value: 1" + ); + } + } + + #[derive(Debug, PartialEq)] + struct TestError(String); + + // Use RustBufferFfiConverter to simplify lifting TestError out of RustBuffer to check it + impl RustBufferFfiConverter for TestError { + type RustType = Self; + + fn write(obj: Self::RustType, buf: &mut Vec<u8>) { + <String as FfiConverter>::write(obj.0, buf); + } + + fn try_read(buf: &mut &[u8]) -> Result<Self> { + String::try_read(buf).map(TestError) + } + } + + impl FfiError for TestError {} + + fn function_with_result(a: u8) -> Result<i8, TestError> { + match a { + 0 => Ok(100), + 1 => Err(TestError("Error".to_owned())), + x => panic!("Unexpected value: {x}"), + } + } + + #[test] + fn test_call_with_result() { + let mut status = create_call_status(); + let return_value = call_with_result(&mut status, || { + function_with_result(0).map_err(TestError::lower) + }); + assert_eq!(status.code, CALL_SUCCESS); + assert_eq!(return_value, 100); + + call_with_result(&mut status, || { + function_with_result(1).map_err(TestError::lower) + }); + assert_eq!(status.code, CALL_ERROR); + unsafe { + assert_eq!( + TestError::try_lift(status.error_buf.assume_init()).unwrap(), + TestError("Error".to_owned()) + ); + } + + let mut status = create_call_status(); + call_with_result(&mut status, || { + function_with_result(2).map_err(TestError::lower) + }); + assert_eq!(status.code, CALL_PANIC); + unsafe { + assert_eq!( + String::try_lift(status.error_buf.assume_init()).unwrap(), + "Unexpected value: 2" + ); + } + } +} |