1
//! Host-language callback invoker registry.
2
//!
3
//! Managed-FFI bindings (Lua, Ruby, Perl, PHP, OCaml, Node, C#, Java, …) can't
4
//! generate C-ABI trampolines for callback typedefs that take aggregate args
5
//! by value — that's a libffi / LuaJIT FFI / ruby-ffi limitation we can't fix
6
//! at the host. This module provides the alternative the user's analysis
7
//! settled on: each language registers **one** generic invoker function at
8
//! module load time, plus a releaser that fires when a host-language handle
9
//! goes out of use.
10
//!
11
//! Every callback the host registers becomes a `Callback { cb, ctx }` pair
12
//! whose `cb` is a *static thunk* in libazul (so by-value args land on a
13
//! native frame the way the framework already expects), and whose `ctx` is
14
//! a `RefAny` payload that carries an opaque host-language `u64` handle.
15
//! The thunk reads `info.get_ctx()`, extracts the handle, and dispatches to
16
//! the registered per-kind invoker — which, on the host side, looks up the
17
//! callable by id in a host-managed table and runs it. When the RefAny's
18
//! refcount drops to zero, the destructor calls back through the registered
19
//! releaser so the host can drop its table entry, mirroring Python's
20
//! `Py<PyAny>` lifetime story without making libazul link against any host
21
//! runtime.
22
//!
23
//! ## API surface
24
//!
25
//! - [`AzApp_setHostHandleReleaser`] — register the host's "drop this id" callback once per
26
//!   process. Fires when a host-handle [`RefAny`] is collected.
27
//! - Per callback kind, [`crate::impl_managed_callback!`] expands to:
28
//!   - A static thunk (`extern "C" fn`) compiled into libazul.
29
//!   - A `<Wrapper>::create_from_host_handle(u64)` constructor.
30
//!   - An `AzApp_set<Kind>Invoker(...)` setter for the host-side per-kind pointer-arg invoker.
31
//!
32
//! ## Why a single shared releaser
33
//!
34
//! Per-kind invokers are necessarily distinct — each callback typedef has
35
//! a different signature, so the host has to register a libffi closure per
36
//! typedef anyway. The releaser, on the other hand, has the same signature
37
//! for every kind (`extern "C" fn(u64)`), so we can share one slot across
38
//! all callbacks; the host registers it once and every kind's destructor
39
//! routes through it.
40

            
41
use core::{
42
    ffi::c_void,
43
    sync::atomic::{AtomicUsize, Ordering},
44
};
45

            
46
use azul_css::AzString;
47

            
48
use crate::refany::RefAny;
49

            
50
/// RTTI id stamped into every `RefAny` created via [`host_handle_to_refany`].
51
///
52
/// Hosts must not reuse this id for their own user-data `RefAnys`, otherwise
53
/// `refany_to_host_handle` would mis-identify their data as a host handle
54
/// and the destructor would call the registered releaser with a bogus id.
55
/// The high 32 bits are reserved for azul-internal RTTI ids; the low 32
56
/// spell `'H','S','T','H'` so the value reads `0xA20A_4853_5448_5F44`.
57
pub const AZ_HOST_HANDLE_RTTI_ID: u64 = 0xA20A_4853_5448_5F44;
58

            
59
/// Heap payload stored inside the [`RefAny`] returned by
60
/// [`host_handle_to_refany`]. Just the opaque host-language id — the actual
61
/// host callable lives on the host side keyed by this id.
62
#[repr(C)]
63
#[derive(Debug, Copy, Clone)]
64
pub struct HostHandlePayload {
65
    pub id: u64,
66
}
67

            
68
/// A single atomic-pointer slot for one registered host-side function
69
/// pointer.
70
///
71
/// `0` means "not registered"; the static thunks bail out (returning
72
/// the kind's default value) when they see an unregistered slot rather than
73
/// transmuting `0` into a fn pointer and crashing.
74
#[repr(C)]
75
#[derive(Debug)]
76
pub struct InvokerSlot {
77
    fn_ptr: AtomicUsize,
78
}
79

            
80
impl InvokerSlot {
81
    /// Create an empty slot. `const` so it can be used to declare `static`
82
    /// per-kind slots in `impl_managed_callback!` expansions.
83
    #[must_use]
84
6
    pub const fn new() -> Self {
85
6
        Self {
86
6
            fn_ptr: AtomicUsize::new(0),
87
6
        }
88
6
    }
89

            
90
    /// Replace the registered function pointer.
91
    ///
92
    /// `SeqCst` because the slot is read on every callback fire and we
93
    /// don't want any stale-pointer windows after the host swaps invokers
94
    /// (rare but legal — e.g. unloading a Lua module that registered).
95
1012
    pub fn set(&self, ptr: usize) {
96
1012
        self.fn_ptr.store(ptr, Ordering::SeqCst);
97
1012
    }
98

            
99
    /// Read the current function pointer; `0` if unregistered.
100
1019
    pub fn get(&self) -> usize {
101
1019
        self.fn_ptr.load(Ordering::SeqCst)
102
1019
    }
103
}
104

            
105
impl Default for InvokerSlot {
106
1
    fn default() -> Self {
107
1
        Self::new()
108
1
    }
109
}
110

            
111
/// Process-global slot for the host's "drop a handle id" callback. Set via
112
/// [`AzApp_setHostHandleReleaser`]. Read by [`host_handle_destructor`]
113
/// when a host-handle [`RefAny`]'s last clone drops.
114
pub static HOST_HANDLE_RELEASER: InvokerSlot = InvokerSlot::new();
115

            
116
/// Process-global slot for the host's *generic* invoker.
117
///
118
/// Set via
119
/// [`AzApp_setGenericInvoker`]. Used as a fallback in macro-generated
120
/// per-kind thunks when the per-kind invoker is not registered, and as
121
/// the **only** dispatch path for user-defined custom callback kinds in
122
/// libffi-restricted hosts (Lua, PHP, koffi, …) that can't easily ship
123
/// an upstream `impl_managed_callback!` invocation.
124
///
125
/// Signature on the host side:
126
///
127
/// ```c
128
/// typedef void (*AzGenericInvoker)(
129
///     uint64_t           handle,    /* host-handle id from the RefAny ctx */
130
///     const char*        kind,      /* null-terminated wrapper name */
131
///     const void* const* args,      /* array of pointers, one per arg, in declared order */
132
///     size_t             n_args,    /* args[] length */
133
///     void*              ret        /* where to write the return value (kind-specific size) */
134
/// );
135
/// extern void AzApp_setGenericInvoker(AzGenericInvoker);
136
/// ```
137
///
138
/// The args array carries pointers into the framework's by-value frame
139
/// — host code must not retain them past the call. The host decides what
140
/// to do per kind from the `kind` string (which matches the wrapper
141
/// struct name, e.g. `"Callback"`, `"LayoutCallback"`,
142
/// `"ButtonOnClickCallback"`).
143
pub static GENERIC_INVOKER: InvokerSlot = InvokerSlot::new();
144

            
145
/// Type alias for the generic invoker callable. Hosts cast a libffi
146
/// closure to this signature once at module load.
147
pub type AzGenericInvoker = extern "C" fn(
148
    handle: u64,
149
    kind: *const core::ffi::c_char,
150
    args: *const *const c_void,
151
    n_args: usize,
152
    ret: *mut c_void,
153
);
154

            
155
/// Register the generic invoker for user-defined custom callback kinds
156
/// or as a fallback for per-kind dispatch. Called once at module load;
157
/// subsequent registrations replace the previous slot.
158
///
159
/// Safety: `invoker` must be a valid [`AzGenericInvoker`] function
160
/// pointer for the lifetime of any callback that might be dispatched
161
/// through it — typically the whole process.
162
#[no_mangle]
163
25
pub extern "C" fn AzApp_setGenericInvoker(invoker: AzGenericInvoker) {
164
25
    GENERIC_INVOKER.set(invoker as usize);
165
25
}
166

            
167
/// Register the host-language releaser. Hosts call this once at module
168
/// load time; subsequent registrations replace the previous slot.
169
///
170
/// `releaser` will be invoked as `releaser(id)` whenever a host-handle
171
/// `RefAny` (the kind built by [`host_handle_to_refany`]) drops its last
172
/// reference. The host should remove `id` from whatever id→callable table
173
/// it maintains.
174
///
175
/// Safety: `releaser` must be a valid `extern "C" fn(u64)` for the lifetime
176
/// of any host-handle [`RefAny`] that may still be alive — typically the
177
/// whole process. Passing a function pointer that becomes invalid (e.g.,
178
/// from an unloaded library) without first re-registering will cause a
179
/// crash on the next collection.
180
#[no_mangle]
181
65
pub extern "C" fn AzApp_setHostHandleReleaser(releaser: extern "C" fn(u64)) {
182
65
    HOST_HANDLE_RELEASER.set(releaser as usize);
183
65
}
184

            
185
/// Destructor stamped into every host-handle [`RefAny`]. Reads the payload's
186
/// `id` and forwards it to the registered releaser; if no releaser has been
187
/// registered (e.g., host hasn't initialized yet, or this is a release-build
188
/// dll loaded by a non-managed-FFI consumer) the destructor is a no-op so
189
/// the C side doesn't crash.
190
140
extern "C" fn host_handle_destructor(ptr: *mut c_void) {
191
140
    if ptr.is_null() {
192
2
        return;
193
138
    }
194
    // SAFETY: the destructor only runs for RefAnys built via
195
    // host_handle_to_refany, whose payload type is HostHandlePayload.
196
138
    let payload = unsafe { &*(ptr as *const HostHandlePayload) };
197

            
198
138
    let releaser_addr = HOST_HANDLE_RELEASER.get();
199
138
    if releaser_addr == 0 {
200
67
        return;
201
71
    }
202
    // SAFETY: HOST_HANDLE_RELEASER only ever holds a value that came from
203
    // `releaser as usize` in `AzApp_setHostHandleReleaser`, where `releaser`
204
    // is an `extern "C" fn(u64)`.
205
71
    let releaser: extern "C" fn(u64) = unsafe { core::mem::transmute(releaser_addr) };
206
    // AUDIT: this destructor is `extern "C"` and the host releaser is arbitrary
207
    // (often a Rust closure via libffi). A panic escaping it would unwind across
208
    // the FFI boundary (UB), so contain it. `catch_unwind` needs `std`; `no_std`
209
    // builds use `panic = "abort"` where unwinding cannot occur.
210
    #[cfg(feature = "std")]
211
    {
212
71
        drop(std::panic::catch_unwind(std::panic::AssertUnwindSafe(
213
71
            || releaser(payload.id),
214
        )));
215
    }
216
    #[cfg(not(feature = "std"))]
217
    {
218
        releaser(payload.id);
219
    }
220
140
}
221

            
222
/// Wrap a host-language `u64` handle in a [`RefAny`] suitable for storing
223
/// in a callback wrapper's `ctx` field.
224
///
225
/// The returned `RefAny`'s destructor calls back through the registered
226
/// host releaser when the last clone is dropped, giving the host an
227
/// opportunity to release whatever its `id` was keying.
228
137
pub fn host_handle_to_refany(id: u64) -> RefAny {
229
137
    let payload = HostHandlePayload { id };
230
137
    let type_name: AzString = "AzHostHandle".into();
231
137
    RefAny::new_c(
232
137
        &raw const payload as *const c_void,
233
137
        size_of::<HostHandlePayload>(),
234
137
        align_of::<HostHandlePayload>(),
235
        AZ_HOST_HANDLE_RTTI_ID,
236
137
        type_name,
237
137
        host_handle_destructor,
238
        0,
239
        0,
240
    )
241
137
}
242

            
243
/// Read the host-language id back out of a [`RefAny`] previously created
244
/// via [`host_handle_to_refany`].
245
///
246
/// Returns `None` for any other `RefAny`, so
247
/// a static thunk that mistakenly receives a non-host-handle ctx falls
248
/// back to the kind's default value rather than reading random bytes.
249
#[must_use]
250
130
pub fn refany_to_host_handle(refany: &RefAny) -> Option<u64> {
251
130
    if !refany.is_type(AZ_HOST_HANDLE_RTTI_ID) {
252
26
        return None;
253
104
    }
254
104
    let ptr = refany.get_data_ptr() as *const HostHandlePayload;
255
104
    if ptr.is_null() {
256
        return None;
257
104
    }
258
    // SAFETY: type-id check above guarantees the payload was a HostHandlePayload.
259
104
    Some(unsafe { (*ptr).id })
260
130
}
261

            
262
/// C-ABI: build a [`RefAny`] wrapping a host-language id.
263
///
264
/// Lets managed-FFI
265
/// bindings use the same machinery for user data that callbacks already use
266
/// — one releaser, one id-keyed table, one lifetime story.
267
///
268
/// The returned `RefAny`'s destructor fires the releaser registered via
269
/// [`AzApp_setHostHandleReleaser`] once the last clone drops, so the host
270
/// can drop its `id → value` entry.
271
#[no_mangle]
272
12
pub extern "C" fn AzRefAny_newHostHandle(id: u64) -> RefAny {
273
12
    host_handle_to_refany(id)
274
12
}
275

            
276
/// C-ABI: read the host-language id from a [`RefAny`] previously built via
277
/// [`AzRefAny_newHostHandle`] (or any other host-handle constructor).
278
///
279
/// Returns `0` if `refany` is null or wasn't a host handle. Host bindings
280
/// must reserve `0` as "no value" — [`host_handle_to_refany`] never produces
281
/// `0` if the host's id allocator starts at `1` (the convention used by
282
/// every binding in this repo).
283
#[no_mangle]
284
#[allow(clippy::not_unsafe_ptr_arg_deref)] // SAFETY/FFI: `*const T` is the C-ABI signature; the fn
285
                                           // null-checks then derefs under the documented caller
286
                                           // contract (C guarantees a valid ptr/len). Marking it
287
                                           // `unsafe fn` would force unsafe blocks into the
288
                                           // generated dll bindings.
289
15
pub extern "C" fn AzRefAny_getHostHandle(refany: *const RefAny) -> u64 {
290
15
    if refany.is_null() {
291
2
        return 0;
292
13
    }
293
    // SAFETY: caller's responsibility per `*const` signature.
294
13
    let r = unsafe { &*refany };
295
13
    refany_to_host_handle(r).unwrap_or(0)
296
15
}
297

            
298
/// Macro that expands to the per-callback-kind boilerplate:
299
///
300
/// a static thunk
301
/// (compiled into libazul) that the framework calls with by-value args, a
302
/// `<Wrapper>::create_from_host_handle(u64)` constructor, and an
303
/// `AzApp_set<Kind>Invoker` setter the host calls once at module load.
304
///
305
/// All identifiers are passed in explicitly so we don't need a proc-macro
306
/// dependency just to concatenate idents. Codegen emits invocations of this
307
/// macro from `ir.callback_typedefs`.
308
///
309
/// Caller responsibilities:
310
///
311
/// - The wrapper type must have public fields `cb: <typedef>` and `ctx: OptionRefAny` — that's the
312
///   standard shape every callback wrapper in the framework already follows.
313
/// - `info_ty` must expose a `.get_ctx() -> OptionRefAny` method (also standard for `*CallbackInfo`
314
///   types).
315
/// - `default_ret` is returned when:
316
///   - the framework invokes the thunk with `OptionRefAny::None` ctx (host called the typedef
317
///     directly without going through this path),
318
///   - the ctx isn't a host-handle (host registered the wrapper but the ctx came from somewhere
319
///     else),
320
///   - or no invoker has been registered yet for this kind. Pick a value that can't be confused
321
///     with a "real" return — typically the kind's "do nothing" / "empty body" default.
322
#[macro_export]
323
macro_rules! impl_managed_callback {
324
    // Form 1: simple two-argument callbacks `(RefAny, info) -> ret` —
325
    // matches `Callback`, `LayoutCallback`, `ButtonOnClickCallback`,
326
    // and the bulk of widget event callbacks. Identical to the
327
    // extras-form below with an empty extra-args list.
328
    (
329
        wrapper:        $wrapper:ty,
330
        info_ty:        $info_ty:ty,
331
        return_ty:      $ret:ty,
332
        default_ret:    $default:expr,
333
        invoker_static: $invoker_static:ident,
334
        invoker_ty:     $invoker_ty:ident,
335
        thunk_fn:       $thunk_fn:ident,
336
        setter_fn:      $setter_fn:ident,
337
        from_handle_fn: $from_handle_fn:ident,
338
    ) => {
339
        $crate::impl_managed_callback! {
340
            wrapper:        $wrapper,
341
            info_ty:        $info_ty,
342
            return_ty:      $ret,
343
            default_ret:    $default,
344
            invoker_static: $invoker_static,
345
            invoker_ty:     $invoker_ty,
346
            thunk_fn:       $thunk_fn,
347
            setter_fn:      $setter_fn,
348
            from_handle_fn: $from_handle_fn,
349
            extra_args:     [],
350
        }
351
    };
352
    // Form 2: callbacks that take additional state after info — e.g.
353
    // `CheckBoxOnToggleCallback(RefAny, CallbackInfo, CheckBoxState)`.
354
    // The extras list is forwarded by reference into the host invoker
355
    // so libffi-style runtimes never have to handle aggregate-by-value
356
    // returns OR aggregate-by-value args.
357
    (
358
        wrapper:        $wrapper:ty,
359
        info_ty:        $info_ty:ty,
360
        return_ty:      $ret:ty,
361
        default_ret:    $default:expr,
362
        invoker_static: $invoker_static:ident,
363
        invoker_ty:     $invoker_ty:ident,
364
        thunk_fn:       $thunk_fn:ident,
365
        setter_fn:      $setter_fn:ident,
366
        from_handle_fn: $from_handle_fn:ident,
367
        extra_args:     [ $( $extra_name:ident : $extra_ty:ty ),* $(,)? ] $(,)?
368
    ) => {
369
        /// Process-global slot for this callback kind's host-side invoker.
370
        pub static $invoker_static: $crate::host_invoker::InvokerSlot =
371
            $crate::host_invoker::InvokerSlot::new();
372

            
373
        /// Pointer-arg variant of this callback kind's typedef.
374
        ///
375
        /// The host's libffi closure casts to this signature (which all
376
        /// managed-FFI runtimes can handle — args and return are passed
377
        /// by pointer, no aggregate-by-value anywhere). The static thunk
378
        /// in libazul does the by-value plumbing on the C ABI side.
379
        ///
380
        /// `LuaJIT` FFI in particular cannot return aggregates larger than
381
        /// 8 bytes from a callback, so we use an out-pointer for the
382
        /// return value uniformly across kinds — even for `Update` which
383
        /// would fit in a register, so the macro stays homogeneous.
384
        pub type $invoker_ty = extern "C" fn(
385
            handle: u64,
386
            data: *const $crate::refany::RefAny,
387
            info: *const $info_ty,
388
            $( $extra_name : *const $extra_ty , )*
389
            out: *mut $ret,
390
        );
391

            
392
        /// Register the host-side invoker for this callback kind.
393
        #[no_mangle]
394
5
        pub extern "C" fn $setter_fn(invoker: $invoker_ty) {
395
5
            $invoker_static.set(invoker as usize);
396
5
        }
397

            
398
        /// Static thunk compiled into libazul. The framework calls this
399
        /// with by-value args; we extract the host handle from `info.ctx`,
400
        /// allocate space for the return value on our stack, and forward
401
        /// pointers to the registered invoker.
402
18
        extern "C" fn $thunk_fn(
403
18
            data: $crate::refany::RefAny,
404
18
            info: $info_ty,
405
18
            $( $extra_name : $extra_ty , )*
406
18
        ) -> $ret {
407
            // Wrapper name as a null-terminated C string. `stringify!`
408
            // expands `$wrapper:ty` to e.g. `Callback`,
409
            // `ButtonOnClickCallback`, etc. — matching what the host's
410
            // dispatch table keys on.
411
            const KIND_STR: &str = concat!(stringify!($wrapper), "\0");
412

            
413
            // AUDIT: this thunk is `extern "C"` and dispatches into arbitrary
414
            // host code (via a transmuted invoker pointer). A panic escaping the
415
            // dispatch would unwind across the FFI boundary (UB), so run the
416
            // whole body inside `catch_unwind` and fall back to `$default` on a
417
            // panic. `catch_unwind` needs `std`; `no_std` builds use
418
            // `panic = "abort"` where unwinding cannot occur. The body captures
419
            // `data`/`info`/extras by move (they are consumed either way).
420
18
            let body = move || -> $ret {
421
18
                let ctx = info.get_ctx();
422
18
                let handle = match ctx {
423
17
                    $crate::refany::OptionRefAny::Some(ref refany) => {
424
17
                        match $crate::host_invoker::refany_to_host_handle(refany) {
425
15
                            Some(id) => id,
426
                            None => return $default,
427
                        }
428
                    }
429
                    _ => return $default,
430
                };
431
15
                let invoker_addr = $invoker_static.get();
432
15
                if invoker_addr == 0 {
433
                    // Per-kind invoker not registered — fall back to the
434
                    // generic invoker for hosts that wired up only the
435
                    // single `AzApp_setGenericInvoker` slot (or for custom
436
                    // user-defined kinds emitted by a downstream
437
                    // `impl_managed_callback!` whose host hasn't shipped a
438
                    // per-kind invoker setter yet).
439
2
                    let generic_addr = $crate::host_invoker::GENERIC_INVOKER.get();
440
2
                    if generic_addr == 0 {
441
                        return $default;
442
1
                    }
443
                    // SAFETY: GENERIC_INVOKER only ever holds an address that
444
                    // came from `invoker as usize` in `AzApp_setGenericInvoker`,
445
                    // whose parameter is typed as `AzGenericInvoker`.
446
1
                    let generic: $crate::host_invoker::AzGenericInvoker =
447
1
                        unsafe { core::mem::transmute(generic_addr) };
448

            
449
                    // Build the args array: pointers to each by-value frame
450
                    // arg, in declared order (data, info, extras…). Lifetime
451
                    // is the scope of this thunk; the host MUST NOT retain
452
                    // these pointers past the call. Array size is inferred
453
                    // (2 base args + however many extras the macro forwarded).
454
1
                    let args = [
455
1
                        &raw const data as *const core::ffi::c_void,
456
1
                        &raw const info as *const core::ffi::c_void,
457
1
                        $( & $extra_name as *const _ as *const core::ffi::c_void , )*
458
1
                    ];
459

            
460
1
                    let mut out: $ret = $default;
461
1
                    generic(
462
1
                        handle,
463
1
                        KIND_STR.as_ptr() as *const core::ffi::c_char,
464
1
                        args.as_ptr(),
465
1
                        args.len(),
466
1
                        &raw mut out as *mut core::ffi::c_void,
467
1
                    );
468
1
                    return out;
469
13
                }
470
                // SAFETY: $invoker_static only ever holds a value that came from
471
                // `invoker as usize` in `$setter_fn`, where `invoker` has type
472
                // `$invoker_ty`.
473
13
                let invoker: $invoker_ty = unsafe { core::mem::transmute(invoker_addr) };
474

            
475
                // Pre-fill `out` with the kind's default so a host that fails
476
                // to write to the out-pointer (e.g. a buggy invoker) leaves us
477
                // with a sane value rather than uninitialized memory.
478
13
                let mut out: $ret = $default;
479
13
                invoker(
480
13
                    handle,
481
13
                    &raw const data,
482
13
                    &raw const info,
483
13
                    $( & $extra_name as *const $extra_ty , )*
484
13
                    &raw mut out,
485
13
                );
486
13
                out
487
18
            };
488

            
489
            #[cfg(feature = "std")]
490
            {
491
18
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(body))
492
18
                    .unwrap_or($default)
493
            }
494
            #[cfg(not(feature = "std"))]
495
            {
496
                body()
497
            }
498
18
        }
499

            
500
        impl $wrapper {
501
            /// Build a wrapper whose `cb` is the static thunk above and
502
            /// whose `ctx` carries the host's `u64` handle. The host
503
            /// language is responsible for keeping its id→callable table
504
            /// in sync with the releaser registered via
505
            /// `AzApp_setHostHandleReleaser`.
506
41
            #[must_use] pub fn create_from_host_handle(handle: u64) -> Self {
507
41
                Self {
508
41
                    cb: $thunk_fn,
509
41
                    ctx: $crate::refany::OptionRefAny::Some(
510
41
                        $crate::host_invoker::host_handle_to_refany(handle),
511
41
                    ),
512
41
                }
513
41
            }
514
        }
515

            
516
        /// C-ABI export wrapping `<Wrapper>::create_from_host_handle`.
517
        #[no_mangle]
518
11
        pub extern "C" fn $from_handle_fn(handle: u64) -> $wrapper {
519
11
            <$wrapper>::create_from_host_handle(handle)
520
11
        }
521
    };
522
}
523

            
524
// NOTE on Miri coverage: the *genuine* FFI transmutes here (a raw host fn
525
// pointer stored as `usize` in an `InvokerSlot`, transmuted back to a fn
526
// pointer) cannot be driven from real C under Miri. Instead the tests below
527
// register real Rust `extern "C"` fns through the public C-ABI setters, so the
528
// `set(ptr as usize)` -> `get()` -> `transmute` round-trip is exercised
529
// end-to-end with a live pointer (Miri-clean, no UB). The panic-containment
530
// test drives the macro-generated thunk's `catch_unwind` with a pure-Rust
531
// panic raised *inside* the thunk body (before any extern-"C" boundary), which
532
// is the realistic containment path.
533
#[cfg(all(test, feature = "std"))]
534
#[allow(
535
    clippy::items_after_statements,
536
    clippy::redundant_clone,
537
    clippy::cast_possible_truncation,
538
    clippy::cast_sign_loss,
539
    trivial_casts,
540
    clippy::borrow_as_ptr,
541
    clippy::cast_ptr_alignment,
542
    clippy::unused_self,
543
    unused_qualifications,
544
    unreachable_pub,
545
    private_interfaces
546
)] // test-only fakes drive the FFI macro; pedantic lints are noise here
547
mod tests {
548
    use core::sync::atomic::{AtomicU64, Ordering as AtOrdering};
549
    use std::sync::Mutex;
550

            
551
    use super::*;
552

            
553
    // The invoker/releaser slots are process-global; serialize tests that
554
    // touch them so parallel test threads don't clobber each other.
555
    // `pub(super)` so `autotest_generated` below locks the SAME mutex — a
556
    // second, independent lock would not serialize the two modules against
557
    // each other.
558
    pub(super) static TEST_LOCK: Mutex<()> = Mutex::new(());
559

            
560
    // Records the id the releaser was called with, so we can assert the
561
    // transmuted-back fn pointer was invoked with the correct payload id.
562
    static LAST_RELEASED: AtomicU64 = AtomicU64::new(0);
563

            
564
1
    extern "C" fn recording_releaser(id: u64) {
565
1
        LAST_RELEASED.store(id, AtOrdering::SeqCst);
566
1
    }
567

            
568
    #[test]
569
1
    fn destructor_transmutes_and_invokes_releaser() {
570
1
        let _g = TEST_LOCK.lock().unwrap();
571
1
        LAST_RELEASED.store(0, AtOrdering::SeqCst);
572
        // Register via the real C-ABI setter (exercises `releaser as usize`).
573
1
        AzApp_setHostHandleReleaser(recording_releaser);
574
1
        let mut payload = HostHandlePayload { id: 0xABCD_1234 };
575
        // Drive the destructor directly with a pointer to the payload — the
576
        // same shape a host-handle RefAny hands it. Exercises the payload
577
        // deref + the usize->fn-pointer transmute + the invoke.
578
1
        host_handle_destructor((&raw mut payload).cast::<c_void>());
579
1
        assert_eq!(LAST_RELEASED.load(AtOrdering::SeqCst), 0xABCD_1234);
580
        // Clear the slot so a later drop can't call a stale test fn pointer.
581
1
        HOST_HANDLE_RELEASER.set(0);
582
1
    }
583

            
584
    #[test]
585
1
    fn destructor_null_ptr_is_noop() {
586
        // Returns before touching any global; no lock needed.
587
1
        host_handle_destructor(core::ptr::null_mut());
588
1
    }
589

            
590
    #[test]
591
1
    fn host_handle_roundtrips_through_refany() {
592
1
        let _g = TEST_LOCK.lock().unwrap();
593
        // Ensure the round-trip RefAny's drop fires no releaser.
594
1
        HOST_HANDLE_RELEASER.set(0);
595
1
        let refany = host_handle_to_refany(0x55);
596
        // Exercises the type-id-guarded raw-ptr deref in refany_to_host_handle.
597
1
        assert_eq!(refany_to_host_handle(&refany), Some(0x55));
598
1
    }
599

            
600
    // A fake callback kind used to instantiate `impl_managed_callback!` and
601
    // assert the generated thunk contains a panic instead of unwinding out of
602
    // its `extern "C"` boundary.
603
    #[derive(PartialEq, Debug)]
604
    struct FakeRet(u32);
605

            
606
    struct FakeInfo;
607
    impl FakeInfo {
608
        // Panics from *inside* the thunk body (pure-Rust unwind), so the
609
        // thunk's `catch_unwind` is the thing under test.
610
1
        fn get_ctx(&self) -> crate::refany::OptionRefAny {
611
1
            panic!("boom from get_ctx");
612
        }
613
    }
614

            
615
    struct FakeWrapper {
616
        #[allow(dead_code)]
617
        cb: extern "C" fn(crate::refany::RefAny, FakeInfo) -> FakeRet,
618
        #[allow(dead_code)]
619
        ctx: crate::refany::OptionRefAny,
620
    }
621

            
622
    crate::impl_managed_callback! {
623
        wrapper:        FakeWrapper,
624
        info_ty:        FakeInfo,
625
        return_ty:      FakeRet,
626
        default_ret:    FakeRet(99),
627
        invoker_static: AZ_TEST_FAKE_INVOKER,
628
        invoker_ty:     AzTestFakeInvoker,
629
        thunk_fn:       az_test_fake_thunk,
630
        setter_fn:      az_test_fake_set_invoker,
631
        from_handle_fn: az_test_fake_from_handle,
632
    }
633

            
634
    #[test]
635
1
    fn thunk_contains_panic_and_returns_default() {
636
1
        let _g = TEST_LOCK.lock().unwrap();
637
1
        HOST_HANDLE_RELEASER.set(0);
638
1
        let data = host_handle_to_refany(1);
639
        // get_ctx() panics inside the thunk body; catch_unwind must contain it
640
        // and hand back `default_ret` rather than unwinding across FFI.
641
1
        let out = az_test_fake_thunk(data, FakeInfo);
642
1
        assert_eq!(out, FakeRet(99));
643
1
    }
644
}
645

            
646
#[cfg(test)]
647
#[path = "host_invoker_test.rs"]
648
mod host_invoker_test;