| 1 |
// This template implements a class for working with a Rust struct via a Pointer/Arc<T> |
| 2 |
// to the live Rust struct on the other side of the FFI. |
| 3 |
// |
| 4 |
// Each instance implements core operations for working with the Rust `Arc<T>` and the |
| 5 |
// Kotlin Pointer to work with the live Rust struct on the other side of the FFI. |
| 6 |
// |
| 7 |
// There's some subtlety here, because we have to be careful not to operate on a Rust |
| 8 |
// struct after it has been dropped, and because we must expose a public API for freeing |
| 9 |
// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: |
| 10 |
// |
| 11 |
// * Each instance holds an opaque pointer to the underlying Rust struct. |
| 12 |
// Method calls need to read this pointer from the object's state and pass it in to |
| 13 |
// the Rust FFI. |
| 14 |
// |
| 15 |
// * When an instance is no longer needed, its pointer should be passed to a |
| 16 |
// special destructor function provided by the Rust FFI, which will drop the |
| 17 |
// underlying Rust struct. |
| 18 |
// |
| 19 |
// * Given an instance, calling code is expected to call the special |
| 20 |
// `destroy` method in order to free it after use, either by calling it explicitly |
| 21 |
// or by using a higher-level helper like the `use` method. Failing to do so risks |
| 22 |
// leaking the underlying Rust struct. |
| 23 |
// |
| 24 |
// * We can't assume that calling code will do the right thing, and must be prepared |
| 25 |
// to handle Kotlin method calls executing concurrently with or even after a call to |
| 26 |
// `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. |
| 27 |
// |
| 28 |
// * We must never allow Rust code to operate on the underlying Rust struct after |
| 29 |
// the destructor has been called, and must never call the destructor more than once. |
| 30 |
// Doing so may trigger memory unsafety. |
| 31 |
// |
| 32 |
// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` |
| 33 |
// is implemented to call the destructor when the Kotlin object becomes unreachable. |
| 34 |
// This is done in a background thread. This is not a panacea, and client code should be aware that |
| 35 |
// 1. the thread may starve if some there are objects that have poorly performing |
| 36 |
// `drop` methods or do significant work in their `drop` methods. |
| 37 |
// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, |
| 38 |
// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). |
| 39 |
// |
| 40 |
// If we try to implement this with mutual exclusion on access to the pointer, there is the |
| 41 |
// possibility of a race between a method call and a concurrent call to `destroy`: |
| 42 |
// |
| 43 |
// * Thread A starts a method call, reads the value of the pointer, but is interrupted |
| 44 |
// before it can pass the pointer over the FFI to Rust. |
| 45 |
// * Thread B calls `destroy` and frees the underlying Rust struct. |
| 46 |
// * Thread A resumes, passing the already-read pointer value to Rust and triggering |
| 47 |
// a use-after-free. |
| 48 |
// |
| 49 |
// One possible solution would be to use a `ReadWriteLock`, with each method call taking |
| 50 |
// a read lock (and thus allowed to run concurrently) and the special `destroy` method |
| 51 |
// taking a write lock (and thus blocking on live method calls). However, we aim not to |
| 52 |
// generate methods with any hidden blocking semantics, and a `destroy` method that might |
| 53 |
// block if called incorrectly seems to meet that bar. |
| 54 |
// |
| 55 |
// So, we achieve our goals by giving each instance an associated `AtomicLong` counter to track |
| 56 |
// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` |
| 57 |
// has been called. These are updated according to the following rules: |
| 58 |
// |
| 59 |
// * The initial value of the counter is 1, indicating a live object with no in-flight calls. |
| 60 |
// The initial value for the flag is false. |
| 61 |
// |
| 62 |
// * At the start of each method call, we atomically check the counter. |
| 63 |
// If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. |
| 64 |
// If it is nonzero them we atomically increment it by 1 and proceed with the method call. |
| 65 |
// |
| 66 |
// * At the end of each method call, we atomically decrement and check the counter. |
| 67 |
// If it has reached zero then we destroy the underlying Rust struct. |
| 68 |
// |
| 69 |
// * When `destroy` is called, we atomically flip the flag from false to true. |
| 70 |
// If the flag was already true we silently fail. |
| 71 |
// Otherwise we atomically decrement and check the counter. |
| 72 |
// If it has reached zero then we destroy the underlying Rust struct. |
| 73 |
// |
| 74 |
// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc<T>` works, |
| 75 |
// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. |
| 76 |
// |
| 77 |
// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been |
| 78 |
// called *and* all in-flight method calls have completed, avoiding violating any of the expectations |
| 79 |
// of the underlying Rust code. |
| 80 |
// |
| 81 |
// This makes a cleaner a better alternative to _not_ calling `destroy()` as |
| 82 |
// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` |
| 83 |
// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner |
| 84 |
// thread may be starved, and the app will leak memory. |
| 85 |
// |
| 86 |
// In this case, `destroy`ing manually may be a better solution. |
| 87 |
// |
| 88 |
// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects |
| 89 |
// with Rust peers are reclaimed: |
| 90 |
// |
| 91 |
// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: |
| 92 |
// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: |
| 93 |
// 3. The memory is reclaimed when the process terminates. |
| 94 |
// |
| 95 |
// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 |
| 96 |
// |
| 97 |
|
| 98 |
{{ self.add_import("java.util.concurrent.atomic.AtomicBoolean") }} |
| 99 |
|
| 100 |
{%- let obj = ci.get_object_definition(name).unwrap() %} |
| 101 |
{%- let interface_name = self::object_interface_name(ci, obj) %} |
| 102 |
{%- let impl_class_name = self::object_impl_name(ci, obj) %} |
| 103 |
{%- let methods = obj.methods() %} |
| 104 |
{%- let interface_docstring = obj.docstring() %} |
| 105 |
{%- let is_error = ci.is_name_used_as_error(name) %} |
| 106 |
{%- let ffi_converter_name = obj|ffi_converter_name %} |
| 107 |
|
| 108 |
{%- include "Interface.kt" %} |
| 109 |
|
| 110 |
{%- call kt::docstring(obj, 0) %} |
| 111 |
{% if (is_error) %} |
| 112 |
open class {{ impl_class_name }} : kotlin.Exception, Disposable, AutoCloseable, {{ interface_name }} { |
| 113 |
{% else -%} |
| 114 |
open class {{ impl_class_name }}: Disposable, AutoCloseable, {{ interface_name }} |
| 115 |
{%- for t in obj.trait_impls() %} |
| 116 |
, {{ self::trait_interface_name(ci, t.trait_name)? }} |
| 117 |
{% endfor %} |
| 118 |
{ |
| 119 |
{%- endif %} |
| 120 |
|
| 121 |
constructor(pointer: Pointer) { |
| 122 |
this.pointer = pointer |
| 123 |
this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) |
| 124 |
} |
| 125 |
|
| 126 |
/** |
| 127 |
* This constructor can be used to instantiate a fake object. Only used for tests. Any |
| 128 |
* attempt to actually use an object constructed this way will fail as there is no |
| 129 |
* connected Rust object. |
| 130 |
*/ |
| 131 |
@Suppress("UNUSED_PARAMETER") |
| 132 |
constructor(noPointer: NoPointer) { |
| 133 |
this.pointer = null |
| 134 |
this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) |
| 135 |
} |
| 136 |
|
| 137 |
{%- match obj.primary_constructor() %} |
| 138 |
{%- when Some(cons) %} |
| 139 |
{%- if cons.is_async() %} |
| 140 |
// Note no constructor generated for this object as it is async. |
| 141 |
{%- else %} |
| 142 |
{%- call kt::docstring(cons, 4) %} |
| 143 |
constructor({% call kt::arg_list(cons, true) -%}) : |
| 144 |
this({% call kt::to_ffi_call(cons) %}) |
| 145 |
{%- endif %} |
| 146 |
{%- when None %} |
| 147 |
{%- endmatch %} |
| 148 |
|
| 149 |
protected val pointer: Pointer? |
| 150 |
protected val cleanable: UniffiCleaner.Cleanable |
| 151 |
|
| 152 |
private val wasDestroyed = AtomicBoolean(false) |
| 153 |
private val callCounter = AtomicLong(1) |
| 154 |
|
| 155 |
override fun destroy() { |
| 156 |
// Only allow a single call to this method. |
| 157 |
// TODO: maybe we should log a warning if called more than once? |
| 158 |
if (this.wasDestroyed.compareAndSet(false, true)) { |
| 159 |
// This decrement always matches the initial count of 1 given at creation time. |
| 160 |
if (this.callCounter.decrementAndGet() == 0L) { |
| 161 |
cleanable.clean() |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
@Synchronized |
| 167 |
override fun close() { |
| 168 |
this.destroy() |
| 169 |
} |
| 170 |
|
| 171 |
internal inline fun <R> callWithPointer(block: (ptr: Pointer) -> R): R { |
| 172 |
// Check and increment the call counter, to keep the object alive. |
| 173 |
// This needs a compare-and-set retry loop in case of concurrent updates. |
| 174 |
do { |
| 175 |
val c = this.callCounter.get() |
| 176 |
if (c == 0L) { |
| 177 |
throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") |
| 178 |
} |
| 179 |
if (c == Long.MAX_VALUE) { |
| 180 |
throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") |
| 181 |
} |
| 182 |
} while (! this.callCounter.compareAndSet(c, c + 1L)) |
| 183 |
// Now we can safely do the method call without the pointer being freed concurrently. |
| 184 |
try { |
| 185 |
return block(this.uniffiClonePointer()) |
| 186 |
} finally { |
| 187 |
// This decrement always matches the increment we performed above. |
| 188 |
if (this.callCounter.decrementAndGet() == 0L) { |
| 189 |
cleanable.clean() |
| 190 |
} |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
// Use a static inner class instead of a closure so as not to accidentally |
| 195 |
// capture `this` as part of the cleanable's action. |
| 196 |
private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { |
| 197 |
override fun run() { |
| 198 |
pointer?.let { ptr -> |
| 199 |
uniffiRustCall { status -> |
| 200 |
UniffiLib.INSTANCE.{{ obj.ffi_object_free().name() }}(ptr, status) |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
fun uniffiClonePointer(): Pointer { |
| 207 |
return uniffiRustCall() { status -> |
| 208 |
UniffiLib.INSTANCE.{{ obj.ffi_object_clone().name() }}(pointer!!, status) |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
{% for meth in obj.methods() -%} |
| 213 |
{%- call kt::func_decl("override", meth, 4) %} |
| 214 |
{% endfor %} |
| 215 |
|
| 216 |
{%- for tm in obj.uniffi_traits() %} |
| 217 |
{%- match tm %} |
| 218 |
{% when UniffiTrait::Display { fmt } %} |
| 219 |
override fun toString(): String { |
| 220 |
return {{ fmt.return_type().unwrap()|lift_fn }}({% call kt::to_ffi_call(fmt) %}) |
| 221 |
} |
| 222 |
{% when UniffiTrait::Eq { eq, ne } %} |
| 223 |
{# only equals used #} |
| 224 |
override fun equals(other: Any?): Boolean { |
| 225 |
if (this === other) return true |
| 226 |
if (other !is {{ impl_class_name}}) return false |
| 227 |
return {{ eq.return_type().unwrap()|lift_fn }}({% call kt::to_ffi_call(eq) %}) |
| 228 |
} |
| 229 |
{% when UniffiTrait::Hash { hash } %} |
| 230 |
override fun hashCode(): Int { |
| 231 |
return {{ hash.return_type().unwrap()|lift_fn }}({%- call kt::to_ffi_call(hash) %}).toInt() |
| 232 |
} |
| 233 |
{%- else %} |
| 234 |
{%- endmatch %} |
| 235 |
{%- endfor %} |
| 236 |
|
| 237 |
{# XXX - "companion object" confusion? How to have alternate constructors *and* be an error? #} |
| 238 |
{% if !obj.alternate_constructors().is_empty() -%} |
| 239 |
companion object { |
| 240 |
{% for cons in obj.alternate_constructors() -%} |
| 241 |
{% call kt::func_decl("", cons, 4) %} |
| 242 |
{% endfor %} |
| 243 |
} |
| 244 |
{% else if is_error %} |
| 245 |
companion object ErrorHandler : UniffiRustCallStatusErrorHandler<{{ impl_class_name }}> { |
| 246 |
override fun lift(error_buf: RustBuffer.ByValue): {{ impl_class_name }} { |
| 247 |
// Due to some mismatches in the ffi converter mechanisms, errors are a RustBuffer. |
| 248 |
val bb = error_buf.asByteBuffer() |
| 249 |
if (bb == null) { |
| 250 |
throw InternalException("?") |
| 251 |
} |
| 252 |
return {{ ffi_converter_name }}.read(bb) |
| 253 |
} |
| 254 |
} |
| 255 |
{% else %} |
| 256 |
companion object |
| 257 |
{% endif %} |
| 258 |
} |
| 259 |
|
| 260 |
{%- if obj.has_callback_interface() %} |
| 261 |
{%- let vtable = obj.vtable().expect("trait interface should have a vtable") %} |
| 262 |
{%- let vtable_methods = obj.vtable_methods() %} |
| 263 |
{%- let ffi_init_callback = obj.ffi_init_callback() %} |
| 264 |
{% include "CallbackInterfaceImpl.kt" %} |
| 265 |
{%- endif %} |
| 266 |
|
| 267 |
/** |
| 268 |
* @suppress |
| 269 |
*/ |
| 270 |
public object {{ ffi_converter_name }}: FfiConverter<{{ type_name }}, Pointer> { |
| 271 |
{%- if obj.has_callback_interface() %} |
| 272 |
internal val handleMap = UniffiHandleMap<{{ type_name }}>() |
| 273 |
{%- endif %} |
| 274 |
|
| 275 |
override fun lower(value: {{ type_name }}): Pointer { |
| 276 |
{%- if obj.has_callback_interface() %} |
| 277 |
return Pointer(handleMap.insert(value)) |
| 278 |
{%- else %} |
| 279 |
return value.uniffiClonePointer() |
| 280 |
{%- endif %} |
| 281 |
} |
| 282 |
|
| 283 |
override fun lift(value: Pointer): {{ type_name }} { |
| 284 |
return {{ impl_class_name }}(value) |
| 285 |
} |
| 286 |
|
| 287 |
override fun read(buf: ByteBuffer): {{ type_name }} { |
| 288 |
// The Rust code always writes pointers as 8 bytes, and will |
| 289 |
// fail to compile if they don't fit. |
| 290 |
return lift(Pointer(buf.getLong())) |
| 291 |
} |
| 292 |
|
| 293 |
override fun allocationSize(value: {{ type_name }}) = 8UL |
| 294 |
|
| 295 |
override fun write(value: {{ type_name }}, buf: ByteBuffer) { |
| 296 |
// The Rust code always expects pointers written as 8 bytes, |
| 297 |
// and will fail to compile if they don't fit. |
| 298 |
buf.putLong(Pointer.nativeValue(lower(value))) |
| 299 |
} |
| 300 |
} |