Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async implementation #101

Merged
merged 16 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion bindgen/src/gen_cs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ impl CsCodeOracle {
FfiType::UInt8 => "byte".to_string(),
FfiType::Float32 => "float".to_string(),
FfiType::Float64 => "double".to_string(),
FfiType::RustArcPtr(name) => format!("{}SafeHandle", self.class_name(name).as_str()),
FfiType::RustArcPtr(_) => "IntPtr".to_string(),
FfiType::RustBuffer(_) => "RustBuffer".to_string(),
FfiType::ForeignBytes => "ForeignBytes".to_string(),
FfiType::ForeignCallback => "ForeignCallback".to_string(),
Expand Down
95 changes: 95 additions & 0 deletions bindgen/templates/Async.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
{{ self.add_import("System.Threading.Tasks")}}

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void UniFfiFutureCallback(IntPtr continuationHandle, byte pollResult);

internal static class _UniFFIAsync {
internal const byte UNIFFI_RUST_FUTURE_POLL_READY = 0;
// internal const byte UNIFFI_RUST_FUTURE_POLL_MAYBE_READY = 1;

static _UniFFIAsync() {
UniffiRustFutureContinuationCallback.Register();
}

// FFI type for Rust future continuations
internal class UniffiRustFutureContinuationCallback
{
public static UniFfiFutureCallback callback = Callback;

public static void Callback(IntPtr continuationHandle, byte pollResult)
{
GCHandle handle = GCHandle.FromIntPtr(continuationHandle);
if (handle.Target is TaskCompletionSource<byte> tcs)
{
tcs.SetResult(pollResult);
}
else
{
throw new InternalException("Unable to cast unmanaged IntPtr to TaskCompletionSource<byte>");
}
}

public static void Register()
{
IntPtr fn = Marshal.GetFunctionPointerForDelegate(callback);
_UniFFILib.{{ ci.ffi_rust_future_continuation_callback_set().name() }}(fn);
}
}

public delegate F CompleteFuncDelegate<F>(IntPtr ptr, ref RustCallStatus status);

public delegate void CompleteActionDelegate(IntPtr ptr, ref RustCallStatus status);

private static async Task PollFuture(IntPtr rustFuture, Action<IntPtr, IntPtr> pollFunc)
{
byte pollResult;
do
{
var tcs = new TaskCompletionSource<byte>(TaskCreationOptions.RunContinuationsAsynchronously);
var handle = GCHandle.Alloc(tcs);
cmcknight-bb marked this conversation as resolved.
Show resolved Hide resolved
pollFunc(rustFuture, GCHandle.ToIntPtr(handle));
pollResult = await tcs.Task;
handle.Free();
}
while(pollResult != UNIFFI_RUST_FUTURE_POLL_READY);
}

public static async Task<T> UniffiRustCallAsync<T, F, E>(
IntPtr rustFuture,
Action<IntPtr, IntPtr> pollFunc,
CompleteFuncDelegate<F> completeFunc,
Action<IntPtr> freeFunc,
Func<F, T> liftFunc,
CallStatusErrorHandler<E> errorHandler
) where E : UniffiException
{
try {
await PollFuture(rustFuture, pollFunc);
var result = _UniffiHelpers.RustCallWithError(errorHandler, (ref RustCallStatus status) => completeFunc(rustFuture, ref status));
return liftFunc(result);
}
finally
{
freeFunc(rustFuture);
}
}

public static async Task UniffiRustCallAsync<E>(
IntPtr rustFuture,
Action<IntPtr, IntPtr> pollFunc,
CompleteActionDelegate completeFunc,
Action<IntPtr> freeFunc,
CallStatusErrorHandler<E> errorHandler
) where E : UniffiException
{
try {
await PollFuture(rustFuture, pollFunc);
_UniffiHelpers.RustCallWithError(errorHandler, (ref RustCallStatus status) => completeFunc(rustFuture, ref status));

}
finally
{
freeFunc(rustFuture);
}
}
}
37 changes: 37 additions & 0 deletions bindgen/templates/Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,40 @@ public static void RustCall(RustCallAction callback) {
});
}
}

static class FFIObjectUtil {
public static void DisposeAll(params Object?[] list) {
foreach (var obj in list) {
Dispose(obj);
}
}

// Dispose is implemented by recursive type inspection at runtime. This is because
// generating correct Dispose calls for recursive complex types, e.g. List<List<int>>
// is quite cumbersome.
private static void Dispose(dynamic? obj) {
if (obj == null) {
return;
}

if (obj is IDisposable disposable) {
disposable.Dispose();
return;
}

var type = obj.GetType();
if (type != null) {
if (type.IsGenericType) {
if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) {
foreach (var value in obj) {
Dispose(value);
}
} else if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>))) {
foreach (var value in obj.Values) {
Dispose(value);
}
}
}
}
}
}
118 changes: 57 additions & 61 deletions bindgen/templates/ObjectRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,87 +2,83 @@
* 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/. */#}

// `SafeHandle` implements the semantics outlined below, i.e. its thread safe, and the dispose
// method will only be called once, once all outstanding native calls have completed.
// https://github.com/mozilla/uniffi-rs/blob/0dc031132d9493ca812c3af6e7dd60ad2ea95bf0/uniffi_bindgen/src/bindings/kotlin/templates/ObjectRuntime.kt#L31
// https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.criticalhandle
{{ config.access_modifier() }} abstract class FFIObject: IDisposable {
protected IntPtr pointer;

{{ config.access_modifier() }} abstract class FFIObject<THandle>: IDisposable where THandle : FFISafeHandle {
private THandle handle;
private int _wasDestroyed = 0;
private long _callCounter = 1;

public FFIObject(THandle handle) {
this.handle = handle;
protected FFIObject(IntPtr pointer) {
this.pointer = pointer;
}

public THandle GetHandle() {
return handle;
}
protected abstract void FreeRustArcPtr();

public void Dispose() {
handle.Dispose();
public void Destroy()
{
// Only allow a single call to this method.
if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0)
{
// This decrement always matches the initial count of 1 given at creation time.
if (Interlocked.Decrement(ref _callCounter) == 0)
{
FreeRustArcPtr();
}
}
}
}

{{ config.access_modifier() }} abstract class FFISafeHandle: SafeHandle {
public FFISafeHandle(): base(new IntPtr(0), true) {
public void Dispose()
{
Destroy();
GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead.
}

public FFISafeHandle(IntPtr pointer): this() {
this.SetHandle(pointer);
~FFIObject()
{
Destroy();
}

public override bool IsInvalid {
get {
return handle.ToInt64() == 0;
}
}
private void IncrementCallCounter()
{
// Check and increment the call counter, to keep the object alive.
// This needs a compare-and-set retry loop in case of concurrent updates.
long count;
do
{
count = Interlocked.Read(ref _callCounter);
if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name));
if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name));

// TODO(CS) this completely breaks any guarantees offered by SafeHandle.. Extracting
// raw value from SafeHandle puts responsiblity on the consumer of this function to
// ensure that SafeHandle outlives the stream, and anyone who might have read the raw
// value from the stream and are holding onto it. Otherwise, the result might be a use
// after free, or free while method calls are still in flight.
//
// This is also relevant for Kotlin.
//
public IntPtr DangerousGetRawFfiValue() {
return handle;
} while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count);
}
}

static class FFIObjectUtil {
public static void DisposeAll(params Object?[] list) {
foreach (var obj in list) {
Dispose(obj);
private void DecrementCallCounter()
{
// This decrement always matches the increment we performed above.
if (Interlocked.Decrement(ref _callCounter) == 0) {
FreeRustArcPtr();
}
}

// Dispose is implemented by recursive type inspection at runtime. This is because
// generating correct Dispose calls for recursive complex types, e.g. List<List<int>>
// is quite cumbersome.
private static void Dispose(dynamic? obj) {
if (obj == null) {
return;
internal void CallWithPointer(Action<IntPtr> action)
{
IncrementCallCounter();
try {
action(this.pointer);
}

if (obj is IDisposable disposable) {
disposable.Dispose();
return;
finally {
DecrementCallCounter();
}
}

var type = obj.GetType();
if (type != null) {
if (type.IsGenericType) {
if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) {
foreach (var value in obj) {
Dispose(value);
}
} else if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>))) {
foreach (var value in obj.Values) {
Dispose(value);
}
}
}
internal T CallWithPointer<T>(Func<IntPtr, T> func)
{
IncrementCallCounter();
try {
return func(this.pointer);
}
finally {
DecrementCallCounter();
}
}
}
Loading
Loading