1
#[allow(unused_imports)]
2
pub use super::*;
3
/// Adversarial tests for the host-invoker registry.
4
///
5
/// Everything here that touches `HOST_HANDLE_RELEASER` / `GENERIC_INVOKER` /
6
/// the per-kind slot holds [`tests::TEST_LOCK`] — those slots are
7
/// process-global, so a parallel test thread would otherwise observe (or
8
/// clobber) another test's registration.
9
///
10
/// Deliberately NOT tested: a host releaser / host invoker that panics. Those
11
/// are `extern "C" fn`s, so Rust's abort-on-unwind shim fires *inside the
12
/// callee*, before the caller's `catch_unwind` can see the payload — such a
13
/// test would abort the whole test binary rather than assert anything. The
14
/// realistic containment path (a panic raised inside the thunk body, before
15
/// the FFI boundary) is already covered by
16
/// `tests::thunk_contains_panic_and_returns_default`.
17
#[cfg(all(test, feature = "std"))]
18
#[allow(
19
    clippy::items_after_statements,
20
    clippy::redundant_clone,
21
    clippy::cast_possible_truncation,
22
    clippy::cast_sign_loss,
23
    trivial_casts,
24
    clippy::borrow_as_ptr,
25
    clippy::cast_ptr_alignment,
26
    clippy::unused_self,
27
    unused_qualifications,
28
    unreachable_pub,
29
    private_interfaces,
30
    improper_ctypes_definitions,
31
    missing_debug_implementations,
32
    missing_copy_implementations
33
)] // test-only fakes drive the FFI macro; pedantic lints are noise here
34
mod autotest_generated {
35
    use core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering as AtOrdering};
36
    use std::{ffi::CStr, sync::PoisonError};
37

            
38
    use crate::{
39
        host_invoker::{tests::TEST_LOCK, *},
40
        refany::OptionRefAny,
41
    };
42

            
43
    /// Lock the shared slot mutex, tolerating poisoning from an earlier failed
44
    /// test (otherwise one genuine failure cascades into N spurious ones).
45
    fn lock_slots() -> std::sync::MutexGuard<'static, ()> {
46
        TEST_LOCK.lock().unwrap_or_else(PoisonError::into_inner)
47
    }
48

            
49
    /// Zero every process-global slot this module touches, so a test that
50
    /// asserts "unregistered" behaviour can't be fooled by a leftover pointer.
51
    fn clear_all_slots() {
52
        HOST_HANDLE_RELEASER.set(0);
53
        GENERIC_INVOKER.set(0);
54
        AZ_AUTOTEST_INVOKER.set(0);
55
    }
56

            
57
    /// Ids chosen to bracket every interesting `u64` boundary: the "no value"
58
    /// sentinel, the low/high extremes, the 32-bit rollover (managed hosts
59
    /// love to truncate to i32/f64), the sign bit, and the RTTI id itself.
60
    const BOUNDARY_IDS: [u64; 11] = [
61
        0,
62
        1,
63
        2,
64
        u32::MAX as u64,
65
        u32::MAX as u64 + 1, // 32-bit rollover: a host truncating to u32 wraps to 0
66
        0xDEAD_BEEF_CAFE_BABE,
67
        1 << 63,
68
        (1 << 53) + 1, // > f64 mantissa: a JS/Lua host would round this
69
        u64::MAX - 1,
70
        u64::MAX,
71
        AZ_HOST_HANDLE_RTTI_ID,
72
    ];
73

            
74
    // ---------------------------------------------------------------------
75
    // InvokerSlot — constructor / numeric set / getter
76
    // ---------------------------------------------------------------------
77

            
78
    #[test]
79
    fn slot_new_and_default_start_unregistered() {
80
        assert_eq!(InvokerSlot::new().get(), 0);
81
        assert_eq!(InvokerSlot::default().get(), 0);
82
    }
83

            
84
    #[test]
85
    fn slot_new_is_const_usable_in_static() {
86
        // The whole point of `const fn new()` — `impl_managed_callback!`
87
        // declares per-kind slots as `static`.
88
        static SLOT: InvokerSlot = InvokerSlot::new();
89
        assert_eq!(SLOT.get(), 0);
90
        SLOT.set(0x1234);
91
        assert_eq!(SLOT.get(), 0x1234);
92
        SLOT.set(0); // leave the process-global-shaped static clean
93
    }
94

            
95
    #[test]
96
    fn slot_set_get_roundtrips_at_usize_boundaries() {
97
        let slot = InvokerSlot::new();
98
        for ptr in [
99
            0usize,
100
            1,
101
            2,
102
            usize::MAX,
103
            usize::MAX - 1,
104
            usize::MAX / 2,
105
            1usize << (usize::BITS - 1), // sign bit, if reinterpreted as isize
106
            usize::try_from(u32::MAX).unwrap(),
107
            0xDEAD_BEEF,
108
        ] {
109
            slot.set(ptr);
110
            assert_eq!(slot.get(), ptr, "set/get must round-trip {ptr:#x} exactly");
111
        }
112
    }
113

            
114
    #[test]
115
    fn slot_set_is_last_write_wins_and_zero_clears() {
116
        let slot = InvokerSlot::new();
117
        slot.set(usize::MAX);
118
        slot.set(0x42);
119
        assert_eq!(slot.get(), 0x42);
120
        // `0` is the "unregistered" sentinel — setting it back must actually
121
        // un-register, not be treated as a no-op.
122
        slot.set(0);
123
        assert_eq!(slot.get(), 0);
124
    }
125

            
126
    #[test]
127
    fn slot_get_is_idempotent() {
128
        // `get` is a load, not a take: reading must not clear the slot.
129
        let slot = InvokerSlot::new();
130
        slot.set(0xABCD);
131
        assert_eq!(slot.get(), 0xABCD);
132
        assert_eq!(slot.get(), 0xABCD);
133
        assert_eq!(slot.get(), 0xABCD);
134
    }
135

            
136
    #[test]
137
    fn slot_concurrent_writes_never_tear() {
138
        // The slot is read on every callback fire while a host may be swapping
139
        // invokers. A torn read would transmute into a wild fn pointer, so
140
        // assert every observed value is one that was actually written.
141
        let slot = InvokerSlot::new();
142
        let written: [usize; 4] = [0, 1, usize::MAX, 1usize << (usize::BITS - 1)];
143
        let slot_ref = &slot;
144
        std::thread::scope(|s| {
145
            for &w in &written {
146
                // `move` copies `w`/`written` (both Copy) and the &-borrow of
147
                // `slot`; a borrowing closure would capture the loop-local `w`,
148
                // which does not outlive the scope.
149
                s.spawn(move || {
150
                    for _ in 0..200 {
151
                        slot_ref.set(w);
152
                        let seen = slot_ref.get();
153
                        assert!(
154
                            written.contains(&seen),
155
                            "torn/garbage value observed in slot: {seen:#x}"
156
                        );
157
                    }
158
                });
159
            }
160
        });
161
        assert!(written.contains(&slot.get()));
162
    }
163

            
164
    // ---------------------------------------------------------------------
165
    // Layout / RTTI invariants the FFI contract depends on
166
    // ---------------------------------------------------------------------
167

            
168
    #[test]
169
    fn rtti_id_matches_documented_constant() {
170
        // Hosts hard-code this value in their bindings; changing it silently
171
        // would make every previously-built host handle unrecognisable.
172
        assert_eq!(AZ_HOST_HANDLE_RTTI_ID, 0xA20A_4853_5448_5F44);
173
        assert_ne!(AZ_HOST_HANDLE_RTTI_ID, 0);
174
    }
175

            
176
    #[test]
177
    fn host_handle_payload_layout_is_a_bare_u64() {
178
        assert_eq!(size_of::<HostHandlePayload>(), size_of::<u64>());
179
        assert_eq!(align_of::<HostHandlePayload>(), align_of::<u64>());
180
    }
181

            
182
    // ---------------------------------------------------------------------
183
    // host_handle_to_refany / refany_to_host_handle — round-trip + rejection
184
    // ---------------------------------------------------------------------
185

            
186
    #[test]
187
    fn host_handle_roundtrips_at_every_u64_boundary() {
188
        let _g = lock_slots();
189
        clear_all_slots(); // no releaser: these RefAnys drop into a no-op
190
        for id in BOUNDARY_IDS {
191
            let refany = host_handle_to_refany(id);
192
            assert_eq!(
193
                refany_to_host_handle(&refany),
194
                Some(id),
195
                "encode/decode must be lossless for id {id:#x}"
196
            );
197
        }
198
    }
199

            
200
    #[test]
201
    fn host_handle_refany_carries_the_expected_rtti_metadata() {
202
        let _g = lock_slots();
203
        clear_all_slots();
204
        let refany = host_handle_to_refany(9);
205
        assert!(refany.is_type(AZ_HOST_HANDLE_RTTI_ID));
206
        assert_eq!(refany.get_type_id(), AZ_HOST_HANDLE_RTTI_ID);
207
        assert_eq!(refany.get_type_name().as_str(), "AzHostHandle");
208
        assert_eq!(refany.get_data_len(), size_of::<HostHandlePayload>());
209
        assert_eq!(refany.get_ref_count(), 1);
210
        assert!(!refany.get_data_ptr().is_null());
211
    }
212

            
213
    #[test]
214
    fn host_handle_id_survives_cloning() {
215
        let _g = lock_slots();
216
        clear_all_slots();
217
        let refany = host_handle_to_refany(u64::MAX);
218
        let clone = refany.clone();
219
        assert_eq!(refany.get_ref_count(), 2);
220
        assert_eq!(refany_to_host_handle(&clone), Some(u64::MAX));
221
        assert_eq!(refany_to_host_handle(&refany), Some(u64::MAX));
222
    }
223

            
224
    #[test]
225
    fn refany_to_host_handle_rejects_foreign_refanys() {
226
        // A stray ctx must decode as None (-> thunk returns its default),
227
        // never as random bytes reinterpreted as an id.
228
        assert_eq!(refany_to_host_handle(&RefAny::new(0u64)), None);
229
        assert_eq!(refany_to_host_handle(&RefAny::new(u64::MAX)), None);
230
        assert_eq!(refany_to_host_handle(&RefAny::new(())), None);
231
        assert_eq!(refany_to_host_handle(&RefAny::new([0xFFu8; 64])), None);
232
        // Same *payload type*, but built through RefAny::new -> TypeId-derived
233
        // id, not the host RTTI id. Layout-compatible but must still be
234
        // rejected: the guard is the id, not the shape.
235
        let same_shape = RefAny::new(HostHandlePayload { id: 0x1111 });
236
        assert_ne!(same_shape.get_type_id(), AZ_HOST_HANDLE_RTTI_ID);
237
        assert_eq!(refany_to_host_handle(&same_shape), None);
238
    }
239

            
240
    extern "C" fn noop_destructor(_ptr: *mut c_void) {}
241

            
242
    #[test]
243
    fn refany_to_host_handle_trusts_the_rtti_id_alone() {
244
        // Pins the documented hazard on AZ_HOST_HANDLE_RTTI_ID: a host that
245
        // reuses the id for its own (layout-compatible) payload gets its bytes
246
        // read back as a handle. If this ever starts returning None, the guard
247
        // grew a second check and the doc comment needs updating.
248
        let _g = lock_slots();
249
        clear_all_slots();
250
        let payload = HostHandlePayload {
251
            id: 0x1234_5678_9ABC_DEF0,
252
        };
253
        let spoofed = RefAny::new_c(
254
            (&raw const payload).cast::<c_void>(),
255
            size_of::<HostHandlePayload>(),
256
            align_of::<HostHandlePayload>(),
257
            AZ_HOST_HANDLE_RTTI_ID,
258
            "NotAHostHandle".into(),
259
            noop_destructor,
260
            0,
261
            0,
262
        );
263
        assert_eq!(refany_to_host_handle(&spoofed), Some(0x1234_5678_9ABC_DEF0));
264
    }
265

            
266
    // ---------------------------------------------------------------------
267
    // C-ABI surface: AzRefAny_newHostHandle / AzRefAny_getHostHandle
268
    // ---------------------------------------------------------------------
269

            
270
    #[test]
271
    fn c_abi_new_and_get_host_handle_roundtrip() {
272
        let _g = lock_slots();
273
        clear_all_slots();
274
        for id in BOUNDARY_IDS {
275
            let refany = AzRefAny_newHostHandle(id);
276
            assert_eq!(refany_to_host_handle(&refany), Some(id));
277
            assert_eq!(AzRefAny_getHostHandle(&raw const refany), id);
278
        }
279
    }
280

            
281
    #[test]
282
    fn c_abi_get_host_handle_null_returns_zero() {
283
        assert_eq!(AzRefAny_getHostHandle(core::ptr::null()), 0);
284
    }
285

            
286
    #[test]
287
    fn c_abi_get_host_handle_foreign_refany_returns_zero() {
288
        let foreign = RefAny::new(0xDEAD_BEEF_u64);
289
        assert_eq!(AzRefAny_getHostHandle(&raw const foreign), 0);
290
    }
291

            
292
    #[test]
293
    fn c_abi_get_host_handle_cannot_distinguish_id_zero_from_failure() {
294
        // Documented contract: `0` is reserved as "no value", so a host whose
295
        // id allocator starts at 0 gets an unfixable ambiguity across the C
296
        // ABI. Assert the ambiguity exists (so nobody "fixes" getHostHandle
297
        // without also fixing the bindings) AND that the Rust-side accessor
298
        // stays lossless.
299
        let _g = lock_slots();
300
        clear_all_slots();
301
        let zero_handle = AzRefAny_newHostHandle(0);
302
        assert_eq!(AzRefAny_getHostHandle(&raw const zero_handle), 0);
303
        assert_eq!(AzRefAny_getHostHandle(core::ptr::null()), 0);
304
        // Rust callers can still tell the two apart:
305
        assert_eq!(refany_to_host_handle(&zero_handle), Some(0));
306
    }
307

            
308
    // ---------------------------------------------------------------------
309
    // Releaser registration + destructor firing
310
    // ---------------------------------------------------------------------
311

            
312
    static RELEASE_COUNT: AtomicUsize = AtomicUsize::new(0);
313
    static RELEASED_ID: AtomicU64 = AtomicU64::new(0);
314

            
315
    extern "C" fn counting_releaser(id: u64) {
316
        RELEASED_ID.store(id, AtOrdering::SeqCst);
317
        RELEASE_COUNT.fetch_add(1, AtOrdering::SeqCst);
318
    }
319

            
320
    static OTHER_RELEASE_COUNT: AtomicUsize = AtomicUsize::new(0);
321

            
322
    extern "C" fn other_releaser(_id: u64) {
323
        OTHER_RELEASE_COUNT.fetch_add(1, AtOrdering::SeqCst);
324
    }
325

            
326
    fn reset_release_recorder() {
327
        RELEASE_COUNT.store(0, AtOrdering::SeqCst);
328
        RELEASED_ID.store(0, AtOrdering::SeqCst);
329
        OTHER_RELEASE_COUNT.store(0, AtOrdering::SeqCst);
330
    }
331

            
332
    #[test]
333
    fn set_releaser_stores_the_fn_address_and_replaces_it() {
334
        let _g = lock_slots();
335
        clear_all_slots();
336
        let expected: extern "C" fn(u64) = counting_releaser;
337
        AzApp_setHostHandleReleaser(counting_releaser);
338
        assert_eq!(HOST_HANDLE_RELEASER.get(), expected as usize);
339
        assert_ne!(HOST_HANDLE_RELEASER.get(), 0);
340
        // "subsequent registrations replace the previous slot"
341
        let replacement: extern "C" fn(u64) = other_releaser;
342
        AzApp_setHostHandleReleaser(other_releaser);
343
        assert_eq!(HOST_HANDLE_RELEASER.get(), replacement as usize);
344
        clear_all_slots();
345
    }
346

            
347
    #[test]
348
    fn releaser_fires_exactly_once_on_the_last_drop() {
349
        let _g = lock_slots();
350
        clear_all_slots();
351
        reset_release_recorder();
352
        AzApp_setHostHandleReleaser(counting_releaser);
353

            
354
        let refany = host_handle_to_refany(0xABC_DEF);
355
        let clone_a = refany.clone();
356
        let clone_b = refany.clone();
357

            
358
        drop(clone_a);
359
        drop(clone_b);
360
        // Two of three refs gone — the host's table entry must still be alive.
361
        assert_eq!(RELEASE_COUNT.load(AtOrdering::SeqCst), 0);
362

            
363
        drop(refany);
364
        assert_eq!(RELEASE_COUNT.load(AtOrdering::SeqCst), 1);
365
        assert_eq!(RELEASED_ID.load(AtOrdering::SeqCst), 0xABC_DEF);
366

            
367
        clear_all_slots();
368
    }
369

            
370
    #[test]
371
    fn releaser_receives_boundary_ids_verbatim() {
372
        let _g = lock_slots();
373
        clear_all_slots();
374
        reset_release_recorder();
375
        AzApp_setHostHandleReleaser(counting_releaser);
376

            
377
        for (n, id) in BOUNDARY_IDS.into_iter().enumerate() {
378
            RELEASED_ID.store(0, AtOrdering::SeqCst);
379
            drop(host_handle_to_refany(id));
380
            assert_eq!(
381
                RELEASE_COUNT.load(AtOrdering::SeqCst),
382
                n + 1,
383
                "one release per dropped handle"
384
            );
385
            assert_eq!(
386
                RELEASED_ID.load(AtOrdering::SeqCst),
387
                id,
388
                "releaser must see id {id:#x} unmangled (no truncation/saturation)"
389
            );
390
        }
391

            
392
        clear_all_slots();
393
    }
394

            
395
    #[test]
396
    fn dropping_a_handle_with_no_releaser_registered_is_a_noop() {
397
        let _g = lock_slots();
398
        clear_all_slots();
399
        reset_release_recorder();
400
        // Slot is 0 ("host hasn't initialised yet") — the destructor must bail
401
        // rather than transmute 0 into a fn pointer and jump to it.
402
        drop(host_handle_to_refany(1));
403
        drop(host_handle_to_refany(u64::MAX));
404
        assert_eq!(RELEASE_COUNT.load(AtOrdering::SeqCst), 0);
405
        assert_eq!(HOST_HANDLE_RELEASER.get(), 0);
406
    }
407

            
408
    #[test]
409
    fn re_registering_the_releaser_retires_the_old_one() {
410
        let _g = lock_slots();
411
        clear_all_slots();
412
        reset_release_recorder();
413
        AzApp_setHostHandleReleaser(counting_releaser);
414
        let live = host_handle_to_refany(7);
415
        // Host swaps releasers (e.g. module reload) while a handle is alive:
416
        // the *current* slot wins at drop time, not the one in force at
417
        // construction.
418
        AzApp_setHostHandleReleaser(other_releaser);
419
        drop(live);
420
        assert_eq!(RELEASE_COUNT.load(AtOrdering::SeqCst), 0);
421
        assert_eq!(OTHER_RELEASE_COUNT.load(AtOrdering::SeqCst), 1);
422
        clear_all_slots();
423
    }
424

            
425
    #[test]
426
    fn destructor_on_null_payload_is_a_noop_even_with_a_releaser() {
427
        let _g = lock_slots();
428
        clear_all_slots();
429
        reset_release_recorder();
430
        AzApp_setHostHandleReleaser(counting_releaser);
431
        host_handle_destructor(core::ptr::null_mut());
432
        assert_eq!(
433
            RELEASE_COUNT.load(AtOrdering::SeqCst),
434
            0,
435
            "a null payload must not be deref'd, nor reported as id 0"
436
        );
437
        clear_all_slots();
438
    }
439

            
440
    // ---------------------------------------------------------------------
441
    // A fake callback kind, so the generic/per-kind dispatch paths in
442
    // `impl_managed_callback!` can be driven end-to-end.
443
    // ---------------------------------------------------------------------
444

            
445
    #[repr(C)]
446
    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
447
    struct AutoRet(u32);
448

            
449
    const DEFAULT_RET: AutoRet = AutoRet(0xDEAD);
450

            
451
    #[repr(C)]
452
    #[derive(Debug)]
453
    struct AutoInfo {
454
        ctx: OptionRefAny,
455
    }
456

            
457
    impl AutoInfo {
458
        fn get_ctx(&self) -> OptionRefAny {
459
            self.ctx.clone()
460
        }
461
    }
462

            
463
    #[repr(C)]
464
    #[derive(Debug)]
465
    struct AutoWrapper {
466
        cb: extern "C" fn(RefAny, AutoInfo) -> AutoRet,
467
        ctx: OptionRefAny,
468
    }
469

            
470
    crate::impl_managed_callback! {
471
        wrapper:        AutoWrapper,
472
        info_ty:        AutoInfo,
473
        return_ty:      AutoRet,
474
        default_ret:    DEFAULT_RET,
475
        invoker_static: AZ_AUTOTEST_INVOKER,
476
        invoker_ty:     AzAutotestInvoker,
477
        thunk_fn:       az_autotest_thunk,
478
        setter_fn:      az_autotest_set_invoker,
479
        from_handle_fn: az_autotest_from_handle,
480
    }
481

            
482
    // What the fake host invokers saw. Recorded into atomics rather than
483
    // asserted in-place: these fns are `extern "C"`, so a failing assert!
484
    // inside one would abort the test binary instead of failing the test.
485
    static GENERIC_CALLS: AtomicUsize = AtomicUsize::new(0);
486
    static GENERIC_HANDLE: AtomicU64 = AtomicU64::new(0);
487
    static GENERIC_NARGS: AtomicUsize = AtomicUsize::new(0);
488
    static GENERIC_KIND_OK: AtomicBool = AtomicBool::new(false);
489
    static GENERIC_ARG0_ID: AtomicU64 = AtomicU64::new(0);
490
    static PERKIND_CALLS: AtomicUsize = AtomicUsize::new(0);
491
    static PERKIND_HANDLE: AtomicU64 = AtomicU64::new(0);
492

            
493
    fn reset_invoker_recorders() {
494
        GENERIC_CALLS.store(0, AtOrdering::SeqCst);
495
        GENERIC_HANDLE.store(0, AtOrdering::SeqCst);
496
        GENERIC_NARGS.store(0, AtOrdering::SeqCst);
497
        GENERIC_KIND_OK.store(false, AtOrdering::SeqCst);
498
        GENERIC_ARG0_ID.store(0, AtOrdering::SeqCst);
499
        PERKIND_CALLS.store(0, AtOrdering::SeqCst);
500
        PERKIND_HANDLE.store(0, AtOrdering::SeqCst);
501
    }
502

            
503
    /// Stand-in for a host's libffi generic-invoker closure.
504
    extern "C" fn recording_generic(
505
        handle: u64,
506
        kind: *const core::ffi::c_char,
507
        args: *const *const c_void,
508
        n_args: usize,
509
        ret: *mut c_void,
510
    ) {
511
        GENERIC_CALLS.fetch_add(1, AtOrdering::SeqCst);
512
        GENERIC_HANDLE.store(handle, AtOrdering::SeqCst);
513
        GENERIC_NARGS.store(n_args, AtOrdering::SeqCst);
514

            
515
        // The kind string must be a NUL-terminated "AutoWrapper" — that's what
516
        // the host's dispatch table keys on. Also gates the `ret` write below:
517
        // another kind's thunk falling back here would have a differently-sized
518
        // out-slot.
519
        let kind_ok =
520
            !kind.is_null() && unsafe { CStr::from_ptr(kind) }.to_str() == Ok("AutoWrapper");
521
        GENERIC_KIND_OK.store(kind_ok, AtOrdering::SeqCst);
522

            
523
        // args[0] is the by-value `data: RefAny` frame slot, args[1] the info.
524
        if !args.is_null() && n_args == 2 {
525
            let arg0 = unsafe { *args };
526
            if !arg0.is_null() {
527
                let data = unsafe { &*(arg0.cast::<RefAny>()) };
528
                GENERIC_ARG0_ID.store(refany_to_host_handle(data).unwrap_or(0), AtOrdering::SeqCst);
529
            }
530
        }
531

            
532
        if kind_ok && !ret.is_null() {
533
            unsafe { ret.cast::<AutoRet>().write(AutoRet(0x2222)) };
534
        }
535
    }
536

            
537
    /// Stand-in for a host's per-kind libffi closure.
538
    extern "C" fn recording_perkind(
539
        handle: u64,
540
        _data: *const RefAny,
541
        _info: *const AutoInfo,
542
        out: *mut AutoRet,
543
    ) {
544
        PERKIND_CALLS.fetch_add(1, AtOrdering::SeqCst);
545
        PERKIND_HANDLE.store(handle, AtOrdering::SeqCst);
546
        if !out.is_null() {
547
            unsafe { out.write(AutoRet(0x1111)) };
548
        }
549
    }
550

            
551
    /// A buggy host invoker: never writes the out-pointer.
552
    extern "C" fn silent_perkind(
553
        _handle: u64,
554
        _data: *const RefAny,
555
        _info: *const AutoInfo,
556
        _out: *mut AutoRet,
557
    ) {
558
        PERKIND_CALLS.fetch_add(1, AtOrdering::SeqCst);
559
    }
560

            
561
    fn info_with_ctx(ctx: OptionRefAny) -> AutoInfo {
562
        AutoInfo { ctx }
563
    }
564

            
565
    #[test]
566
    fn set_generic_invoker_stores_the_fn_address_and_replaces_it() {
567
        let _g = lock_slots();
568
        clear_all_slots();
569
        let expected: AzGenericInvoker = recording_generic;
570
        AzApp_setGenericInvoker(recording_generic);
571
        assert_eq!(GENERIC_INVOKER.get(), expected as usize);
572
        assert_ne!(GENERIC_INVOKER.get(), 0);
573
        AzApp_setGenericInvoker(recording_generic); // idempotent re-register
574
        assert_eq!(GENERIC_INVOKER.get(), expected as usize);
575
        clear_all_slots();
576
    }
577

            
578
    #[test]
579
    fn create_from_host_handle_wires_the_thunk_and_ctx() {
580
        let _g = lock_slots();
581
        clear_all_slots();
582
        for id in BOUNDARY_IDS {
583
            let wrapper = AutoWrapper::create_from_host_handle(id);
584
            let expected: extern "C" fn(RefAny, AutoInfo) -> AutoRet = az_autotest_thunk;
585
            assert_eq!(wrapper.cb as usize, expected as usize);
586
            match &wrapper.ctx {
587
                OptionRefAny::Some(refany) => {
588
                    assert_eq!(refany_to_host_handle(refany), Some(id));
589
                }
590
                OptionRefAny::None => panic!("ctx must carry the host handle for id {id:#x}"),
591
            }
592
            // The C-ABI export must produce the identical wrapper.
593
            let from_c = az_autotest_from_handle(id);
594
            assert_eq!(from_c.cb as usize, expected as usize);
595
        }
596
    }
597

            
598
    #[test]
599
    fn thunk_returns_default_when_ctx_is_none() {
600
        let _g = lock_slots();
601
        clear_all_slots();
602
        reset_invoker_recorders();
603
        AzApp_setGenericInvoker(recording_generic);
604
        az_autotest_set_invoker(recording_perkind);
605

            
606
        // Framework invoked the typedef directly, without a host ctx: neither
607
        // invoker may fire (there is no handle to dispatch on).
608
        let out = az_autotest_thunk(RefAny::new(1u32), info_with_ctx(OptionRefAny::None));
609
        assert_eq!(out, DEFAULT_RET);
610
        assert_eq!(GENERIC_CALLS.load(AtOrdering::SeqCst), 0);
611
        assert_eq!(PERKIND_CALLS.load(AtOrdering::SeqCst), 0);
612
        clear_all_slots();
613
    }
614

            
615
    #[test]
616
    fn thunk_returns_default_when_ctx_is_not_a_host_handle() {
617
        let _g = lock_slots();
618
        clear_all_slots();
619
        reset_invoker_recorders();
620
        AzApp_setGenericInvoker(recording_generic);
621
        az_autotest_set_invoker(recording_perkind);
622

            
623
        // A foreign ctx must NOT be reinterpreted as a handle — that would
624
        // dispatch the host on a garbage id.
625
        let ctx = OptionRefAny::Some(RefAny::new(0xFFFF_FFFF_FFFF_FFFF_u64));
626
        let out = az_autotest_thunk(RefAny::new(1u32), info_with_ctx(ctx));
627
        assert_eq!(out, DEFAULT_RET);
628
        assert_eq!(GENERIC_CALLS.load(AtOrdering::SeqCst), 0);
629
        assert_eq!(PERKIND_CALLS.load(AtOrdering::SeqCst), 0);
630
        clear_all_slots();
631
    }
632

            
633
    #[test]
634
    fn thunk_returns_default_when_nothing_is_registered() {
635
        let _g = lock_slots();
636
        clear_all_slots();
637
        // Valid host handle, but both slots are 0 — the thunk must bail with
638
        // the default instead of transmuting 0 into a fn pointer.
639
        let ctx = OptionRefAny::Some(host_handle_to_refany(5));
640
        let out = az_autotest_thunk(RefAny::new(1u32), info_with_ctx(ctx));
641
        assert_eq!(out, DEFAULT_RET);
642
    }
643

            
644
    #[test]
645
    fn thunk_falls_back_to_the_generic_invoker() {
646
        let _g = lock_slots();
647
        clear_all_slots();
648
        reset_invoker_recorders();
649
        AzApp_setGenericInvoker(recording_generic);
650
        // AZ_AUTOTEST_INVOKER deliberately left at 0.
651

            
652
        let data = host_handle_to_refany(0xDA7A);
653
        let ctx = OptionRefAny::Some(host_handle_to_refany(0xC7_C7_C7));
654
        let out = az_autotest_thunk(data, info_with_ctx(ctx));
655

            
656
        assert_eq!(GENERIC_CALLS.load(AtOrdering::SeqCst), 1);
657
        assert_eq!(GENERIC_HANDLE.load(AtOrdering::SeqCst), 0xC7_C7_C7);
658
        assert!(
659
            GENERIC_KIND_OK.load(AtOrdering::SeqCst),
660
            "kind must be \"AutoWrapper\\0\""
661
        );
662
        assert_eq!(GENERIC_NARGS.load(AtOrdering::SeqCst), 2, "data + info");
663
        // args[] must be in *declared* order: data first, then info.
664
        assert_eq!(GENERIC_ARG0_ID.load(AtOrdering::SeqCst), 0xDA7A);
665
        // ...and the host's out-pointer write must be what the thunk returns.
666
        assert_eq!(out, AutoRet(0x2222));
667
        clear_all_slots();
668
    }
669

            
670
    #[test]
671
    fn thunk_prefers_the_per_kind_invoker_over_the_generic_one() {
672
        let _g = lock_slots();
673
        clear_all_slots();
674
        reset_invoker_recorders();
675
        AzApp_setGenericInvoker(recording_generic);
676
        az_autotest_set_invoker(recording_perkind);
677

            
678
        let ctx = OptionRefAny::Some(host_handle_to_refany(0x99));
679
        let out = az_autotest_thunk(RefAny::new(1u32), info_with_ctx(ctx));
680

            
681
        assert_eq!(out, AutoRet(0x1111));
682
        assert_eq!(PERKIND_CALLS.load(AtOrdering::SeqCst), 1);
683
        assert_eq!(PERKIND_HANDLE.load(AtOrdering::SeqCst), 0x99);
684
        assert_eq!(
685
            GENERIC_CALLS.load(AtOrdering::SeqCst),
686
            0,
687
            "generic is a fallback only — it must not also fire"
688
        );
689
        clear_all_slots();
690
    }
691

            
692
    #[test]
693
    fn thunk_returns_default_when_the_host_ignores_the_out_pointer() {
694
        let _g = lock_slots();
695
        clear_all_slots();
696
        reset_invoker_recorders();
697
        az_autotest_set_invoker(silent_perkind);
698

            
699
        // A buggy host invoker that never writes `out` must leave us with the
700
        // pre-filled default, not uninitialised memory.
701
        let ctx = OptionRefAny::Some(host_handle_to_refany(3));
702
        let out = az_autotest_thunk(RefAny::new(1u32), info_with_ctx(ctx));
703
        assert_eq!(PERKIND_CALLS.load(AtOrdering::SeqCst), 1);
704
        assert_eq!(out, DEFAULT_RET);
705
        clear_all_slots();
706
    }
707

            
708
    #[test]
709
    fn thunk_dispatches_boundary_handles_without_truncation() {
710
        let _g = lock_slots();
711
        clear_all_slots();
712
        reset_invoker_recorders();
713
        az_autotest_set_invoker(recording_perkind);
714

            
715
        for id in BOUNDARY_IDS {
716
            let ctx = OptionRefAny::Some(host_handle_to_refany(id));
717
            let out = az_autotest_thunk(RefAny::new(1u32), info_with_ctx(ctx));
718
            assert_eq!(out, AutoRet(0x1111));
719
            assert_eq!(
720
                PERKIND_HANDLE.load(AtOrdering::SeqCst),
721
                id,
722
                "handle {id:#x} must reach the host invoker unmangled"
723
            );
724
        }
725
        clear_all_slots();
726
    }
727
}