Skip to main content

nros_platform_cffi/
lib.rs

1//! Rust mirror of the canonical C ABI in `<nros/platform.h>`.
2//!
3//! Every nros binary links exactly one platform implementation; the
4//! free `extern "C"` symbols declared below are resolved at link time.
5//! There is no runtime registration step. To inject a platform from
6//! C, drop a translation unit defining the symbols (or link against
7//! a static library that does).
8//!
9//! Rust platform crates implement the [`nros_platform_api`] traits as
10//! before; a sibling `-cffi` shim crate re-exports the Rust impl as
11//! `#[unsafe(no_mangle)] extern "C"` symbols matching the names in the
12//! header. That separation lets the same Rust impl serve both
13//! trait-driven Rust callers and C-ABI consumers.
14//!
15//! # Usage
16//!
17//! - C implementor: implement the functions in `<nros/platform.h>` and
18//!   link against the nros binary.
19//! - Rust consumer: enable the `platform-cffi` feature on
20//!   `nros-platform`; [`CffiPlatform`] dispatches every trait call to
21//!   the linked C symbols.
22//!
23//! # Companion
24//!
25//! Platform sits one layer below RMW. The RMW vtable
26//! (`<nros/rmw_vtable.h>`) is a runtime-pluggable struct; the platform
27//! layer is link-time-bound free symbols. Different choice because RMW
28//! backends genuinely swap per session (zenoh vs cyclonedds vs xrce in
29//! the same binary at test time) while a platform is fixed for the life
30//! of a binary.
31
32#![no_std]
33#![allow(clippy::not_unsafe_ptr_arg_deref)]
34
35use core::ffi::c_void;
36
37// Anchor symbol so downstream crates can chain `#[used]` statics to
38// keep this rlib in the link graph. Without an explicit reference,
39// rustc elides the rlib (it's mostly extern decls + a trait impl that
40// gets inlined into callers), and the build.rs `cargo:rustc-link-lib=`
41// directive for `libnros_platform_posix.a` is dropped along with it,
42// leaving every `nros_platform_*` symbol unresolved at the binary
43// link step.
44#[cfg(feature = "posix-c-port")]
45#[doc(hidden)]
46#[inline(never)]
47pub extern "C" fn _nros_force_link_cffi() {}
48
49// ============================================================================
50// Canonical ABI declarations
51// ----------------------------------------------------------------------------
52// Hand-written mirror of `include/nros/platform.h`. Field order, names,
53// and types track the header byte-for-byte. Updates land in the header
54// first, then here.
55// ============================================================================
56
57// RFC-0054 (phase-299 W2): the extern declarations are GENERATED from the
58// platform headers (src/generated.rs, scripts/gen-abi-bindings.sh) — the
59// C headers are the SSoT. The nros_platform_export_*! macros below stay
60// hand-written: they EMIT the definitions (the port side).
61pub mod generated;
62pub use generated::*;
63
64// RFC-0132 -- the CAN frame driver's Rust face over the generated declarations.
65// Behind the `can` capability: the wrapper references the five
66// `nros_platform_can_*` symbols, which only a CAN backend defines, so an image
67// without one (every POSIX staticlib: libnros_c.a, libnros_cpp.a) must not
68// carry it (issue 2633).
69#[cfg(feature = "can")]
70pub mod can;
71
72// issue 0710 — the `LogSink` that speaks this ABI belongs with the ABI, so
73// "does this binary need `nros_platform_log_write`?" is a DEPENDENCY question
74// rather than a Cargo feature. See the module docs.
75pub mod log;
76
77/// Board-supplied writer fn type. ONLY meaningful on platforms whose
78/// `nros_platform_log_write` impl is itself a thin dispatcher to a
79/// board-registered fn (FreeRTOS, ThreadX, bare-metal). On platforms
80/// with a native logger (POSIX, Zephyr, ESP-IDF, NuttX), the symbol
81/// is absent and the board should not link against it.
82pub type NrosPlatformLogWriterFn = unsafe extern "C" fn(
83    severity: u8,
84    name_ptr: *const u8,
85    name_len: usize,
86    msg_ptr: *const u8,
87    msg_len: usize,
88);
89
90/// Board-supplied flush fn type. Pass `None` to
91/// [`nros_platform_register_log_writer`] when the writer is fully
92/// synchronous.
93pub type NrosPlatformLogFlushFn = unsafe extern "C" fn();
94
95// ============================================================================
96// Phase 121.6.rust-mirror — extended canonical ABI
97// ----------------------------------------------------------------------------
98// Mirrors `<nros/platform_timer.h>` + `<nros/platform_net.h>`. Declarations
99// only — definitions are supplied by whichever provider the binary links
100// (a per-RTOS C port via 121.6.<port>-c, or a future macro-expanded Rust
101// impl). Anyone NOT pulling these via `CffiPlatform`'s extended-surface
102// trait impls (those land in a follow-up commit) gets dead-code-stripped
103// extern refs at link time — no symbol resolution required.
104// ============================================================================
105
106// ============================================================================
107// Return codes (mirrors header)
108// ============================================================================
109
110// phase-364 W1 — RE-EXPORTED, not mirrored.
111//
112// This block used to be three hand-written constants and a hand-written `i32`
113// alias, none of which had a single user, and all of which could drift from the
114// header silently. They existed because the header wrote its values as
115// `((nros_platform_ret_t) 0)` and bindgen cannot evaluate a cast into a
116// constant, so the generated bindings carried the typedef and none of the
117// codes. The header now writes bare literals, so the generator emits all six
118// and there is one definition of each.
119//
120// `NrosPlatformRet` follows the header's own narrowing to `int8_t` (the width
121// every one of these functions already returned). The constants keep bindgen's
122// `i32` type — a code is compared against a widened return, not stored — so a
123// caller writes `ret as i32 == NROS_PLATFORM_RET_UNSUPPORTED`.
124pub use crate::generated::{
125    NROS_PLATFORM_RET_ERROR, NROS_PLATFORM_RET_INVALID, NROS_PLATFORM_RET_NOMEM,
126    NROS_PLATFORM_RET_OK, NROS_PLATFORM_RET_TIMEOUT, NROS_PLATFORM_RET_UNSUPPORTED,
127};
128
129/// The C `nros_platform_ret_t`, from the generated bindings.
130pub type NrosPlatformRet = crate::generated::nros_platform_ret_t;
131
132// ============================================================================
133// CffiPlatform — trait impls dispatching to the linked C symbols
134// ============================================================================
135
136/// Zero-sized type implementing the platform traits via the canonical
137/// `nros_platform_*` C symbols.
138///
139/// The crate that pulls `CffiPlatform` into a final binary is
140/// responsible for ensuring the symbols are supplied at link time
141/// (either by a C translation unit or a Rust `-cffi` shim crate).
142pub struct CffiPlatform;
143
144impl nros_platform_api::PlatformClock for CffiPlatform {
145    #[inline]
146    fn clock_ns() -> u64 {
147        unsafe { nros_platform_clock_ns() }
148    }
149
150    #[inline]
151    fn clock_resolution_ns() -> u64 {
152        unsafe { nros_platform_clock_resolution_ns() }
153    }
154
155    /// issue 0758 — forwards to the C symbol. NOT defaulted here: a C port
156    /// that supplies the symbol must be able to answer, and one that does
157    /// not returns `0` from its own definition. Taking the trait default
158    /// instead would silently ignore a C implementation that exists.
159    #[inline]
160    fn epoch_us() -> u64 {
161        unsafe { nros_platform_epoch_us() }
162    }
163}
164
165impl nros_platform_api::PlatformAlloc for CffiPlatform {
166    #[inline]
167    fn alloc(size: usize) -> *mut c_void {
168        unsafe { nros_platform_alloc(size) }
169    }
170
171    #[inline]
172    fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void {
173        unsafe { nros_platform_realloc(ptr, size) }
174    }
175
176    #[inline]
177    fn dealloc(ptr: *mut c_void) {
178        unsafe { nros_platform_dealloc(ptr) }
179    }
180
181    #[inline]
182    fn heap_used_bytes() -> usize {
183        unsafe { nros_platform_heap_used_bytes() }
184    }
185
186    #[inline]
187    fn heap_total_bytes() -> usize {
188        unsafe { nros_platform_heap_total_bytes() }
189    }
190}
191
192impl nros_platform_api::PlatformSleep for CffiPlatform {
193    #[inline]
194    fn sleep_us(us: usize) {
195        unsafe { nros_platform_sleep_us(us) }
196    }
197
198    #[inline]
199    fn sleep_ms(ms: usize) {
200        unsafe { nros_platform_sleep_ms(ms) }
201    }
202
203    #[inline]
204    fn sleep_s(s: usize) {
205        unsafe { nros_platform_sleep_s(s) }
206    }
207}
208
209impl nros_platform_api::PlatformYield for CffiPlatform {
210    #[inline]
211    fn yield_now() {
212        unsafe { nros_platform_yield_now() }
213    }
214}
215
216// Phase 110.D — `PlatformScheduler` is satisfied by the existing yield
217// symbol; per-thread scheduling controls land when a C consumer needs
218// hard-RT preemption.
219impl nros_platform_api::PlatformScheduler for CffiPlatform {
220    #[inline]
221    fn yield_now() {
222        unsafe { nros_platform_yield_now() }
223    }
224}
225
226// Phase 110.E.b — `PlatformTimer` dispatches to the
227// `nros_platform_timer_*` C ABI declared above. Backed by
228// `nros-platform-posix/src/timer.c` on POSIX (POSIX `timer_create` +
229// `SIGEV_THREAD` trampoline); each RTOS port supplies its own
230// `timer.c` mirroring the canonical signatures.
231//
232// `TimerHandle` is a `*mut c_void` newtype so the trait's
233// `Send + Sync` bound holds. Safety: the C layer owns the heap
234// record behind the pointer; Rust just shuttles the opaque handle
235// between `create_*` and `destroy` / `cancel`.
236#[derive(Debug)]
237pub struct CffiTimerHandle(*mut c_void);
238
239// SAFETY: the underlying `*mut c_void` is an opaque platform-owned
240// handle (POSIX `timer_t` wrapped in a heap record, FreeRTOS
241// `TimerHandle_t`, etc.). The Rust side never dereferences it; the
242// only operations are forwarding it back to `destroy` / `cancel`.
243// Send + Sync are required by the trait so the executor can stash
244// the handle across thread boundaries.
245unsafe impl Send for CffiTimerHandle {}
246unsafe impl Sync for CffiTimerHandle {}
247
248impl nros_platform_api::PlatformTimer for CffiPlatform {
249    type TimerHandle = CffiTimerHandle;
250
251    fn create_periodic(
252        period_us: u32,
253        callback: extern "C" fn(*mut c_void),
254        user_data: *mut c_void,
255    ) -> Result<Self::TimerHandle, nros_platform_api::TimerError> {
256        // `extern "C" fn` coerces structurally to `unsafe extern "C"
257        // fn` — both have the same ABI; Rust just demands the unsafe
258        // version at the C call site.
259        let cb: unsafe extern "C" fn(*mut c_void) = callback;
260        let raw = unsafe { nros_platform_timer_create_periodic(period_us, Some(cb), user_data) };
261        if raw.is_null() {
262            // The C layer returns NULL for both "unsupported on this
263            // platform" (default stub) and "syscall failed" (POSIX
264            // EINVAL / kernel error). The runtime treats both the
265            // same way (drop back to the polled-clock fallback), so
266            // surface `KernelError` to differentiate from the
267            // trait-default `Unsupported` that fires when the C
268            // symbol isn't linked at all.
269            return Err(nros_platform_api::TimerError::KernelError);
270        }
271        Ok(CffiTimerHandle(raw))
272    }
273
274    fn create_oneshot(
275        timeout_us: u32,
276        callback: extern "C" fn(*mut c_void),
277        user_data: *mut c_void,
278    ) -> Result<Self::TimerHandle, nros_platform_api::TimerError> {
279        let cb: unsafe extern "C" fn(*mut c_void) = callback;
280        let raw = unsafe { nros_platform_timer_create_oneshot(timeout_us, Some(cb), user_data) };
281        if raw.is_null() {
282            return Err(nros_platform_api::TimerError::KernelError);
283        }
284        Ok(CffiTimerHandle(raw))
285    }
286
287    fn destroy(handle: Self::TimerHandle) {
288        unsafe { nros_platform_timer_destroy(handle.0) }
289    }
290
291    fn cancel(handle: &mut Self::TimerHandle) -> bool {
292        let rc = unsafe { nros_platform_timer_cancel(handle.0) };
293        // `1` = cancellation prevented the callback from firing;
294        // `0` / `-1` = already fired (or error — treated as "not
295        // cancelled in time" by the caller).
296        rc == 1
297    }
298}
299
300impl nros_platform_api::PlatformRandom for CffiPlatform {
301    #[inline]
302    fn random_u8() -> u8 {
303        unsafe { nros_platform_random_u8() }
304    }
305
306    #[inline]
307    fn random_u16() -> u16 {
308        unsafe { nros_platform_random_u16() }
309    }
310
311    #[inline]
312    fn random_u32() -> u32 {
313        unsafe { nros_platform_random_u32() }
314    }
315
316    #[inline]
317    fn random_u64() -> u64 {
318        unsafe { nros_platform_random_u64() }
319    }
320
321    #[inline]
322    fn random_fill(buf: *mut c_void, len: usize) {
323        unsafe { nros_platform_random_fill(buf, len) }
324    }
325}
326
327impl nros_platform_api::PlatformTime for CffiPlatform {
328    #[inline]
329    fn time_now_ns() -> u64 {
330        unsafe { nros_platform_time_now_ns() }
331    }
332
333    #[inline]
334    fn wall_clock_state() -> nros_platform_api::WallClockState {
335        let st = unsafe { nros_platform_wall_clock_state() };
336        nros_platform_api::WallClockState {
337            synced: st.synced,
338            source: st.source,
339            steps: st.steps,
340        }
341    }
342}
343
344impl nros_platform_api::PlatformThreading for CffiPlatform {
345    fn task_init(
346        task: *mut c_void,
347        attr: *mut c_void,
348        entry: Option<unsafe extern "C" fn(*mut c_void) -> *mut c_void>,
349        arg: *mut c_void,
350    ) -> i8 {
351        unsafe { nros_platform_task_init(task, attr, entry, arg) }
352    }
353    fn task_join(task: *mut c_void) -> i8 {
354        unsafe { nros_platform_task_join(task) }
355    }
356    fn task_detach(task: *mut c_void) -> i8 {
357        unsafe { nros_platform_task_detach(task) }
358    }
359    fn task_cancel(task: *mut c_void) -> i8 {
360        unsafe { nros_platform_task_cancel(task) }
361    }
362    fn task_exit() {
363        unsafe { nros_platform_task_exit() }
364    }
365    fn task_free(task: *mut *mut c_void) {
366        unsafe { nros_platform_task_free(task) }
367    }
368    fn mutex_init(m: *mut c_void) -> i8 {
369        unsafe { nros_platform_mutex_init(m) }
370    }
371    fn mutex_drop(m: *mut c_void) -> i8 {
372        unsafe { nros_platform_mutex_drop(m) }
373    }
374    fn mutex_lock(m: *mut c_void) -> i8 {
375        unsafe { nros_platform_mutex_lock(m) }
376    }
377    fn mutex_try_lock(m: *mut c_void) -> i8 {
378        unsafe { nros_platform_mutex_try_lock(m) }
379    }
380    fn mutex_unlock(m: *mut c_void) -> i8 {
381        unsafe { nros_platform_mutex_unlock(m) }
382    }
383    fn mutex_rec_init(m: *mut c_void) -> i8 {
384        unsafe { nros_platform_mutex_rec_init(m) }
385    }
386    fn mutex_rec_drop(m: *mut c_void) -> i8 {
387        unsafe { nros_platform_mutex_rec_drop(m) }
388    }
389    fn mutex_rec_lock(m: *mut c_void) -> i8 {
390        unsafe { nros_platform_mutex_rec_lock(m) }
391    }
392    fn mutex_rec_try_lock(m: *mut c_void) -> i8 {
393        unsafe { nros_platform_mutex_rec_try_lock(m) }
394    }
395    fn mutex_rec_unlock(m: *mut c_void) -> i8 {
396        unsafe { nros_platform_mutex_rec_unlock(m) }
397    }
398    fn condvar_init(cv: *mut c_void) -> i8 {
399        unsafe { nros_platform_condvar_init(cv) }
400    }
401    fn condvar_drop(cv: *mut c_void) -> i8 {
402        unsafe { nros_platform_condvar_drop(cv) }
403    }
404    fn condvar_signal(cv: *mut c_void) -> i8 {
405        unsafe { nros_platform_condvar_signal(cv) }
406    }
407    fn condvar_signal_all(cv: *mut c_void) -> i8 {
408        unsafe { nros_platform_condvar_signal_all(cv) }
409    }
410    fn condvar_signal_from_isr(cv: *mut c_void) -> i8 {
411        unsafe { nros_platform_condvar_signal_from_isr(cv) }
412    }
413    fn condvar_wait_until(cv: *mut c_void, m: *mut c_void, abstime: u64) -> i8 {
414        unsafe { nros_platform_condvar_wait_until(cv, m, abstime) }
415    }
416    fn wake_init(w: *mut c_void) -> i8 {
417        unsafe { nros_platform_wake_init(w) }
418    }
419    fn wake_drop(w: *mut c_void) -> i8 {
420        unsafe { nros_platform_wake_drop(w) }
421    }
422    fn wake_wait_ms(w: *mut c_void, timeout_ms: u32) -> i8 {
423        unsafe { nros_platform_wake_wait_ms(w, timeout_ms) }
424    }
425    fn wake_signal(w: *mut c_void) -> i8 {
426        unsafe { nros_platform_wake_signal(w) }
427    }
428    fn wake_signal_from_isr(w: *mut c_void) -> i8 {
429        unsafe { nros_platform_wake_signal_from_isr(w) }
430    }
431    // `wake_park_until_us` / `wake_park_granularity_us` are deliberately NOT
432    // forwarded. `platform.h` marks them OPTIONAL — Zephyr, ThreadX, FreeRTOS
433    // and POSIX (so NuttX) define them (phase-436 W7, C1, C2); the bare-metal
434    // ports do not (C3) — and this impl is linked into EVERY C port, so forwarding
435    // made an optional symbol a required one: `undefined reference to
436    // nros_platform_wake_park_until_us` on POSIX, FreeRTOS, NuttX and every
437    // other C port (`check-staticlib-symbols`, `check-c`). The trait defaults
438    // (-1 "cannot park", 0 "no granularity") are the honest answer for a shim
439    // that cannot know whether the port it is linked beside defines them. The
440    // ports that do are reached directly by their board entries
441    // (`nros::port_park::install_port_park`), never through this impl.
442    fn wake_storage_size() -> usize {
443        unsafe { nros_platform_wake_storage_size() }
444    }
445    fn wake_storage_align() -> usize {
446        unsafe { nros_platform_wake_storage_align() }
447    }
448    fn task_storage_size() -> usize {
449        unsafe { nros_platform_task_storage_size() }
450    }
451    fn task_storage_align() -> usize {
452        unsafe { nros_platform_task_storage_align() }
453    }
454}
455
456// ============================================================================
457// Phase 121.3.deprecate-rust-migrate — extended-surface trait impls
458// ----------------------------------------------------------------------------
459// CffiPlatform dispatches PlatformTcp / PlatformUdp / PlatformUdpMulticast /
460// PlatformSocketHelpers / PlatformNetworkPoll trait calls through the
461// `unsafe extern "C"` declarations above. Whichever provider supplies the
462// matching symbol set (a per-RTOS Rust crate with `cffi-export` on, or a
463// hand-written C port) backs the dispatch transparently.
464// ============================================================================
465
466impl nros_platform_api::PlatformTcp for CffiPlatform {
467    fn create_endpoint(ep: *mut c_void, address: *const u8, port: *const u8) -> i8 {
468        unsafe { nros_platform_tcp_create_endpoint(ep, address, port) }
469    }
470    fn free_endpoint(ep: *mut c_void) {
471        unsafe { nros_platform_tcp_free_endpoint(ep) }
472    }
473    fn open(sock: *mut c_void, endpoint: *const c_void, timeout_ms: u32) -> i8 {
474        unsafe { nros_platform_tcp_open(sock, endpoint, timeout_ms) }
475    }
476    fn open_within(
477        sock: *mut c_void,
478        endpoint: *const c_void,
479        timeout_ms: u32,
480        connect_timeout_ms: i32,
481    ) -> i8 {
482        unsafe { nros_platform_tcp_open_within(sock, endpoint, timeout_ms, connect_timeout_ms) }
483    }
484    fn listen(sock: *mut c_void, endpoint: *const c_void) -> i8 {
485        unsafe { nros_platform_tcp_listen(sock, endpoint) }
486    }
487    fn close(sock: *mut c_void) {
488        unsafe { nros_platform_tcp_close(sock) }
489    }
490    fn read(sock: *const c_void, buf: *mut u8, len: usize) -> usize {
491        unsafe { nros_platform_tcp_read(sock, buf, len) }
492    }
493    fn read_exact(sock: *const c_void, buf: *mut u8, len: usize) -> usize {
494        unsafe { nros_platform_tcp_read_exact(sock, buf, len) }
495    }
496    fn send(sock: *const c_void, buf: *const u8, len: usize) -> usize {
497        unsafe { nros_platform_tcp_send(sock, buf, len) }
498    }
499    fn set_rx_notify(
500        sock: *const c_void,
501        notify: Option<unsafe extern "C" fn(*mut c_void)>,
502        ctx: *mut c_void,
503    ) -> i8 {
504        unsafe { nros_platform_tcp_set_rx_notify(sock, notify, ctx) }
505    }
506}
507
508impl nros_platform_api::PlatformUdp for CffiPlatform {
509    fn create_endpoint(ep: *mut c_void, address: *const u8, port: *const u8) -> i8 {
510        unsafe { nros_platform_udp_create_endpoint(ep, address, port) }
511    }
512    fn free_endpoint(ep: *mut c_void) {
513        unsafe { nros_platform_udp_free_endpoint(ep) }
514    }
515    fn open(sock: *mut c_void, endpoint: *const c_void, timeout_ms: u32) -> i8 {
516        unsafe { nros_platform_udp_open(sock, endpoint, timeout_ms) }
517    }
518    fn listen(sock: *mut c_void, endpoint: *const c_void, timeout_ms: u32) -> i8 {
519        unsafe { nros_platform_udp_listen(sock, endpoint, timeout_ms) }
520    }
521    fn close(sock: *mut c_void) {
522        unsafe { nros_platform_udp_close(sock) }
523    }
524    fn read(sock: *const c_void, buf: *mut u8, len: usize) -> usize {
525        unsafe { nros_platform_udp_read(sock, buf, len) }
526    }
527    fn read_exact(sock: *const c_void, buf: *mut u8, len: usize) -> usize {
528        unsafe { nros_platform_udp_read_exact(sock, buf, len) }
529    }
530    fn send(sock: *const c_void, buf: *const u8, len: usize, endpoint: *const c_void) -> usize {
531        unsafe { nros_platform_udp_send(sock, buf, len, endpoint) }
532    }
533    fn set_recv_timeout(sock: *const c_void, timeout_ms: u32) {
534        unsafe { nros_platform_udp_set_recv_timeout(sock, timeout_ms) }
535    }
536    fn readiness_handle(sock: *const c_void) -> i32 {
537        unsafe { nros_platform_udp_readiness_handle(sock) }
538    }
539    fn set_rx_notify(
540        sock: *const c_void,
541        notify: Option<unsafe extern "C" fn(*mut c_void)>,
542        ctx: *mut c_void,
543    ) -> i8 {
544        unsafe { nros_platform_udp_set_rx_notify(sock, notify, ctx) }
545    }
546}
547
548impl nros_platform_api::PlatformUdpMulticast for CffiPlatform {
549    fn mcast_open(
550        sock: *mut c_void,
551        endpoint: *const c_void,
552        lep: *mut c_void,
553        timeout_ms: u32,
554        iface: *const u8,
555    ) -> i8 {
556        unsafe { nros_platform_udp_mcast_open(sock, endpoint, lep, timeout_ms, iface) }
557    }
558    fn mcast_listen(
559        sock: *mut c_void,
560        endpoint: *const c_void,
561        timeout_ms: u32,
562        iface: *const u8,
563        join: *const u8,
564    ) -> i8 {
565        unsafe { nros_platform_udp_mcast_listen(sock, endpoint, timeout_ms, iface, join) }
566    }
567    fn mcast_close(
568        sockrecv: *mut c_void,
569        socksend: *mut c_void,
570        rep: *const c_void,
571        lep: *const c_void,
572    ) {
573        unsafe { nros_platform_udp_mcast_close(sockrecv, socksend, rep, lep) }
574    }
575    fn mcast_read(
576        sock: *const c_void,
577        buf: *mut u8,
578        len: usize,
579        lep: *const c_void,
580        addr: *mut c_void,
581    ) -> usize {
582        unsafe { nros_platform_udp_mcast_read(sock, buf, len, lep, addr) }
583    }
584    fn mcast_read_exact(
585        sock: *const c_void,
586        buf: *mut u8,
587        len: usize,
588        lep: *const c_void,
589        addr: *mut c_void,
590    ) -> usize {
591        unsafe { nros_platform_udp_mcast_read_exact(sock, buf, len, lep, addr) }
592    }
593    fn mcast_send(
594        sock: *const c_void,
595        buf: *const u8,
596        len: usize,
597        endpoint: *const c_void,
598    ) -> usize {
599        unsafe { nros_platform_udp_mcast_send(sock, buf, len, endpoint) }
600    }
601}
602
603impl nros_platform_api::PlatformSocketHelpers for CffiPlatform {
604    fn set_non_blocking(sock: *const c_void) -> i8 {
605        unsafe { nros_platform_socket_set_non_blocking(sock) }
606    }
607    fn accept(sock_in: *const c_void, sock_out: *mut c_void) -> i8 {
608        unsafe { nros_platform_socket_accept(sock_in, sock_out) }
609    }
610    fn close(sock: *mut c_void) {
611        unsafe { nros_platform_socket_close(sock) }
612    }
613    fn wait_event(peers: *mut c_void, mutex: *mut c_void) -> i8 {
614        unsafe { nros_platform_socket_wait_event(peers, mutex) }
615    }
616}
617
618impl nros_platform_api::PlatformNetworkPoll for CffiPlatform {
619    fn network_poll() {
620        unsafe { nros_platform_network_poll() }
621    }
622}
623
624impl nros_platform_api::PlatformCriticalSection for CffiPlatform {
625    fn acquire() -> u32 {
626        unsafe { nros_platform_critical_section_acquire() }
627    }
628    fn release(token: u32) {
629        unsafe { nros_platform_critical_section_release(token) }
630    }
631}
632
633impl nros_platform_api::PlatformLog for CffiPlatform {
634    fn write(severity: u8, name: &[u8], message: &[u8]) {
635        // SAFETY: extern decl matches the C ABI byte-for-byte; the
636        // pointer/length pairs come from `&[u8]` references that
637        // outlive the call.
638        unsafe {
639            nros_platform_log_write(
640                severity,
641                name.as_ptr(),
642                name.len(),
643                message.as_ptr(),
644                message.len(),
645            );
646        }
647    }
648
649    fn flush() {
650        // SAFETY: no args, no preconditions.
651        unsafe { nros_platform_log_flush() };
652    }
653}
654
655// ============================================================================
656// Phase 121.2 — export_*! macros
657// ----------------------------------------------------------------------------
658// Each macro emits the `#[unsafe(no_mangle)] extern "C"` definitions for one
659// capability group. The macro callee must implement the matching
660// `nros_platform_api::Platform*` trait; the trait bound is checked at the
661// macro-expansion site, so a missing impl produces a clear compile error in
662// the caller crate.
663//
664// Naming the symbols exactly matches `<nros/platform.h>`. Add a new ABI
665// symbol in three coordinated places, all inside this crate:
666//   1. declare it in `include/nros/platform.h`,
667//   2. declare it in the `unsafe extern "C" { … }` block above,
668//   3. emit it from the appropriate `export_*!` macro below.
669// ============================================================================
670
671/// Emit `nros_platform_clock_{ms,us}` delegating to
672/// `<$ty as PlatformClock>`.
673#[macro_export]
674macro_rules! nros_platform_export_clock {
675    ($ty:ty) => {
676        #[unsafe(no_mangle)]
677        pub extern "C" fn nros_platform_clock_ns() -> u64 {
678            <$ty as ::nros_platform_api::PlatformClock>::clock_ns()
679        }
680        #[unsafe(no_mangle)]
681        pub extern "C" fn nros_platform_clock_resolution_ns() -> u64 {
682            <$ty as ::nros_platform_api::PlatformClock>::clock_resolution_ns()
683        }
684        /// A Rust port that does not override `PlatformClock::epoch_us`
685        /// emits this and answers `0`, which is the honest reading for a
686        /// platform with no wall clock.
687        #[unsafe(no_mangle)]
688        pub extern "C" fn nros_platform_epoch_us() -> u64 {
689            <$ty as ::nros_platform_api::PlatformClock>::epoch_us()
690        }
691    };
692}
693
694/// Emit `nros_platform_panic` delegating to `<$ty as PlatformPanic>`
695/// (phase-366 / RFC-0077).
696///
697/// NOT in `nros_platform_export!` deliberately. The fatal path is the IMAGE's,
698/// and a Rust port that exports it unconditionally would be the same defect
699/// this API exists to remove: a library claiming the image's ending. A port
700/// calls this only when it is the one supplying the behaviour.
701#[macro_export]
702macro_rules! nros_platform_export_panic {
703    ($ty:ty) => {
704        #[unsafe(no_mangle)]
705        pub extern "C" fn nros_platform_panic(msg: *const u8, len: usize) -> ! {
706            <$ty as ::nros_platform_api::PlatformPanic>::panic(msg, len)
707        }
708    };
709}
710
711/// Emit `nros_platform_{alloc,realloc,dealloc}` delegating to
712/// `<$ty as PlatformAlloc>`.
713#[macro_export]
714macro_rules! nros_platform_export_alloc {
715    ($ty:ty) => {
716        #[unsafe(no_mangle)]
717        pub extern "C" fn nros_platform_alloc(size: usize) -> *mut ::core::ffi::c_void {
718            <$ty as ::nros_platform_api::PlatformAlloc>::alloc(size)
719        }
720        #[unsafe(no_mangle)]
721        pub extern "C" fn nros_platform_realloc(
722            ptr: *mut ::core::ffi::c_void,
723            size: usize,
724        ) -> *mut ::core::ffi::c_void {
725            <$ty as ::nros_platform_api::PlatformAlloc>::realloc(ptr, size)
726        }
727        #[unsafe(no_mangle)]
728        pub extern "C" fn nros_platform_dealloc(ptr: *mut ::core::ffi::c_void) {
729            <$ty as ::nros_platform_api::PlatformAlloc>::dealloc(ptr)
730        }
731        #[unsafe(no_mangle)]
732        pub extern "C" fn nros_platform_heap_used_bytes() -> usize {
733            <$ty as ::nros_platform_api::PlatformAlloc>::heap_used_bytes()
734        }
735        #[unsafe(no_mangle)]
736        pub extern "C" fn nros_platform_heap_total_bytes() -> usize {
737            <$ty as ::nros_platform_api::PlatformAlloc>::heap_total_bytes()
738        }
739    };
740}
741
742/// Emit `nros_platform_sleep_{us,ms,s}` delegating to
743/// `<$ty as PlatformSleep>`.
744#[macro_export]
745macro_rules! nros_platform_export_sleep {
746    ($ty:ty) => {
747        #[unsafe(no_mangle)]
748        pub extern "C" fn nros_platform_sleep_us(us: usize) {
749            <$ty as ::nros_platform_api::PlatformSleep>::sleep_us(us)
750        }
751        #[unsafe(no_mangle)]
752        pub extern "C" fn nros_platform_sleep_ms(ms: usize) {
753            <$ty as ::nros_platform_api::PlatformSleep>::sleep_ms(ms)
754        }
755        #[unsafe(no_mangle)]
756        pub extern "C" fn nros_platform_sleep_s(s: usize) {
757            <$ty as ::nros_platform_api::PlatformSleep>::sleep_s(s)
758        }
759    };
760}
761
762/// Emit `nros_platform_yield_now` delegating to
763/// `<$ty as PlatformYield>`.
764#[macro_export]
765macro_rules! nros_platform_export_yield {
766    ($ty:ty) => {
767        #[unsafe(no_mangle)]
768        pub extern "C" fn nros_platform_yield_now() {
769            <$ty as ::nros_platform_api::PlatformYield>::yield_now()
770        }
771    };
772}
773
774/// Emit `nros_platform_random_*` delegating to `<$ty as PlatformRandom>`.
775#[macro_export]
776macro_rules! nros_platform_export_random {
777    ($ty:ty) => {
778        #[unsafe(no_mangle)]
779        pub extern "C" fn nros_platform_random_u8() -> u8 {
780            <$ty as ::nros_platform_api::PlatformRandom>::random_u8()
781        }
782        #[unsafe(no_mangle)]
783        pub extern "C" fn nros_platform_random_u16() -> u16 {
784            <$ty as ::nros_platform_api::PlatformRandom>::random_u16()
785        }
786        #[unsafe(no_mangle)]
787        pub extern "C" fn nros_platform_random_u32() -> u32 {
788            <$ty as ::nros_platform_api::PlatformRandom>::random_u32()
789        }
790        #[unsafe(no_mangle)]
791        pub extern "C" fn nros_platform_random_u64() -> u64 {
792            <$ty as ::nros_platform_api::PlatformRandom>::random_u64()
793        }
794        #[unsafe(no_mangle)]
795        pub extern "C" fn nros_platform_random_fill(buf: *mut ::core::ffi::c_void, len: usize) {
796            <$ty as ::nros_platform_api::PlatformRandom>::random_fill(buf, len)
797        }
798    };
799}
800
801/// Emit `nros_platform_time_*` delegating to `<$ty as PlatformTime>`.
802#[macro_export]
803macro_rules! nros_platform_export_time {
804    ($ty:ty) => {
805        #[unsafe(no_mangle)]
806        pub extern "C" fn nros_platform_time_now_ns() -> u64 {
807            <$ty as ::nros_platform_api::PlatformTime>::time_now_ns()
808        }
809        #[unsafe(no_mangle)]
810        pub extern "C" fn nros_platform_wall_clock_state() -> ::nros_platform_api::WallClockState {
811            <$ty as ::nros_platform_api::PlatformTime>::wall_clock_state()
812        }
813    };
814}
815
816/// Emit `nros_platform_task_*`, `nros_platform_mutex_*`,
817/// `nros_platform_mutex_rec_*`, and `nros_platform_condvar_*` delegating
818/// to `<$ty as PlatformThreading>`. Skip this macro on platforms without
819/// kernel threads.
820#[macro_export]
821macro_rules! nros_platform_export_threading {
822    ($ty:ty) => {
823        #[unsafe(no_mangle)]
824        pub extern "C" fn nros_platform_task_init(
825            task: *mut ::core::ffi::c_void,
826            attr: *mut ::core::ffi::c_void,
827            entry: ::core::option::Option<
828                unsafe extern "C" fn(*mut ::core::ffi::c_void) -> *mut ::core::ffi::c_void,
829            >,
830            arg: *mut ::core::ffi::c_void,
831        ) -> i8 {
832            <$ty as ::nros_platform_api::PlatformThreading>::task_init(task, attr, entry, arg)
833        }
834        #[unsafe(no_mangle)]
835        pub extern "C" fn nros_platform_task_stack_unused_bytes() -> usize {
836            <$ty as ::nros_platform_api::PlatformThreading>::task_stack_unused_bytes()
837        }
838        #[unsafe(no_mangle)]
839        pub extern "C" fn nros_platform_task_stack_unused_bytes_upto(limit: usize) -> usize {
840            <$ty as ::nros_platform_api::PlatformThreading>::task_stack_unused_bytes_upto(limit)
841        }
842        #[unsafe(no_mangle)]
843        pub extern "C" fn nros_platform_task_join(task: *mut ::core::ffi::c_void) -> i8 {
844            <$ty as ::nros_platform_api::PlatformThreading>::task_join(task)
845        }
846        #[unsafe(no_mangle)]
847        pub extern "C" fn nros_platform_task_detach(task: *mut ::core::ffi::c_void) -> i8 {
848            <$ty as ::nros_platform_api::PlatformThreading>::task_detach(task)
849        }
850        #[unsafe(no_mangle)]
851        pub extern "C" fn nros_platform_task_cancel(task: *mut ::core::ffi::c_void) -> i8 {
852            <$ty as ::nros_platform_api::PlatformThreading>::task_cancel(task)
853        }
854        #[unsafe(no_mangle)]
855        pub extern "C" fn nros_platform_task_exit() {
856            <$ty as ::nros_platform_api::PlatformThreading>::task_exit()
857        }
858        #[unsafe(no_mangle)]
859        pub extern "C" fn nros_platform_task_free(task: *mut *mut ::core::ffi::c_void) {
860            <$ty as ::nros_platform_api::PlatformThreading>::task_free(task)
861        }
862        #[unsafe(no_mangle)]
863        pub extern "C" fn nros_platform_mutex_init(m: *mut ::core::ffi::c_void) -> i8 {
864            <$ty as ::nros_platform_api::PlatformThreading>::mutex_init(m)
865        }
866        #[unsafe(no_mangle)]
867        pub extern "C" fn nros_platform_mutex_drop(m: *mut ::core::ffi::c_void) -> i8 {
868            <$ty as ::nros_platform_api::PlatformThreading>::mutex_drop(m)
869        }
870        #[unsafe(no_mangle)]
871        pub extern "C" fn nros_platform_mutex_lock(m: *mut ::core::ffi::c_void) -> i8 {
872            <$ty as ::nros_platform_api::PlatformThreading>::mutex_lock(m)
873        }
874        #[unsafe(no_mangle)]
875        pub extern "C" fn nros_platform_mutex_try_lock(m: *mut ::core::ffi::c_void) -> i8 {
876            <$ty as ::nros_platform_api::PlatformThreading>::mutex_try_lock(m)
877        }
878        #[unsafe(no_mangle)]
879        pub extern "C" fn nros_platform_mutex_unlock(m: *mut ::core::ffi::c_void) -> i8 {
880            <$ty as ::nros_platform_api::PlatformThreading>::mutex_unlock(m)
881        }
882        #[unsafe(no_mangle)]
883        pub extern "C" fn nros_platform_mutex_rec_init(m: *mut ::core::ffi::c_void) -> i8 {
884            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_init(m)
885        }
886        #[unsafe(no_mangle)]
887        pub extern "C" fn nros_platform_mutex_rec_drop(m: *mut ::core::ffi::c_void) -> i8 {
888            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_drop(m)
889        }
890        #[unsafe(no_mangle)]
891        pub extern "C" fn nros_platform_mutex_rec_lock(m: *mut ::core::ffi::c_void) -> i8 {
892            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_lock(m)
893        }
894        #[unsafe(no_mangle)]
895        pub extern "C" fn nros_platform_mutex_rec_try_lock(m: *mut ::core::ffi::c_void) -> i8 {
896            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_try_lock(m)
897        }
898        #[unsafe(no_mangle)]
899        pub extern "C" fn nros_platform_mutex_rec_unlock(m: *mut ::core::ffi::c_void) -> i8 {
900            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_unlock(m)
901        }
902        #[unsafe(no_mangle)]
903        pub extern "C" fn nros_platform_condvar_init(cv: *mut ::core::ffi::c_void) -> i8 {
904            <$ty as ::nros_platform_api::PlatformThreading>::condvar_init(cv)
905        }
906        #[unsafe(no_mangle)]
907        pub extern "C" fn nros_platform_condvar_drop(cv: *mut ::core::ffi::c_void) -> i8 {
908            <$ty as ::nros_platform_api::PlatformThreading>::condvar_drop(cv)
909        }
910        #[unsafe(no_mangle)]
911        pub extern "C" fn nros_platform_condvar_signal(cv: *mut ::core::ffi::c_void) -> i8 {
912            <$ty as ::nros_platform_api::PlatformThreading>::condvar_signal(cv)
913        }
914        #[unsafe(no_mangle)]
915        pub extern "C" fn nros_platform_condvar_signal_all(cv: *mut ::core::ffi::c_void) -> i8 {
916            <$ty as ::nros_platform_api::PlatformThreading>::condvar_signal_all(cv)
917        }
918        #[unsafe(no_mangle)]
919        pub extern "C" fn nros_platform_condvar_signal_from_isr(
920            cv: *mut ::core::ffi::c_void,
921        ) -> i8 {
922            <$ty as ::nros_platform_api::PlatformThreading>::condvar_signal_from_isr(cv)
923        }
924        #[unsafe(no_mangle)]
925        pub extern "C" fn nros_platform_condvar_wait_until(
926            cv: *mut ::core::ffi::c_void,
927            m: *mut ::core::ffi::c_void,
928            abstime: u64,
929        ) -> i8 {
930            <$ty as ::nros_platform_api::PlatformThreading>::condvar_wait_until(cv, m, abstime)
931        }
932        // Phase 130 — wake primitive (binary semaphore shape).
933        #[unsafe(no_mangle)]
934        pub extern "C" fn nros_platform_wake_init(w: *mut ::core::ffi::c_void) -> i8 {
935            <$ty as ::nros_platform_api::PlatformThreading>::wake_init(w)
936        }
937        #[unsafe(no_mangle)]
938        pub extern "C" fn nros_platform_wake_drop(w: *mut ::core::ffi::c_void) -> i8 {
939            <$ty as ::nros_platform_api::PlatformThreading>::wake_drop(w)
940        }
941        #[unsafe(no_mangle)]
942        pub extern "C" fn nros_platform_wake_wait_ms(
943            w: *mut ::core::ffi::c_void,
944            timeout_ms: u32,
945        ) -> i8 {
946            <$ty as ::nros_platform_api::PlatformThreading>::wake_wait_ms(w, timeout_ms)
947        }
948        #[unsafe(no_mangle)]
949        pub extern "C" fn nros_platform_wake_signal(w: *mut ::core::ffi::c_void) -> i8 {
950            <$ty as ::nros_platform_api::PlatformThreading>::wake_signal(w)
951        }
952        #[unsafe(no_mangle)]
953        pub extern "C" fn nros_platform_wake_signal_from_isr(w: *mut ::core::ffi::c_void) -> i8 {
954            <$ty as ::nros_platform_api::PlatformThreading>::wake_signal_from_isr(w)
955        }
956        #[unsafe(no_mangle)]
957        pub extern "C" fn nros_platform_wake_park_until_us(
958            w: *mut ::core::ffi::c_void,
959            deadline_us: u64,
960        ) -> i8 {
961            <$ty as ::nros_platform_api::PlatformThreading>::wake_park_until_us(w, deadline_us)
962        }
963        #[unsafe(no_mangle)]
964        pub extern "C" fn nros_platform_wake_park_granularity_us() -> u64 {
965            <$ty as ::nros_platform_api::PlatformThreading>::wake_park_granularity_us()
966        }
967        #[unsafe(no_mangle)]
968        pub extern "C" fn nros_platform_wake_park_handles_us(
969            w: *mut ::core::ffi::c_void,
970            handles: *const i32,
971            n: usize,
972            deadline_us: u64,
973        ) -> i8 {
974            <$ty as ::nros_platform_api::PlatformThreading>::wake_park_handles_us(
975                w,
976                handles,
977                n,
978                deadline_us,
979            )
980        }
981        #[unsafe(no_mangle)]
982        pub extern "C" fn nros_platform_task_storage_size() -> usize {
983            <$ty as ::nros_platform_api::PlatformThreading>::task_storage_size()
984        }
985        #[unsafe(no_mangle)]
986        pub extern "C" fn nros_platform_task_storage_align() -> usize {
987            <$ty as ::nros_platform_api::PlatformThreading>::task_storage_align()
988        }
989        #[unsafe(no_mangle)]
990        pub extern "C" fn nros_platform_wake_storage_size() -> usize {
991            <$ty as ::nros_platform_api::PlatformThreading>::wake_storage_size()
992        }
993        #[unsafe(no_mangle)]
994        pub extern "C" fn nros_platform_wake_storage_align() -> usize {
995            <$ty as ::nros_platform_api::PlatformThreading>::wake_storage_align()
996        }
997        /// The attribute defaults are pure data, so this is emitted
998        /// concretely rather than dispatched through the trait: every port's
999        /// answer is identical, and a trait method would only invite a port
1000        /// to get it wrong.
1001        #[unsafe(no_mangle)]
1002        pub extern "C" fn nros_platform_task_attr_init(
1003            attr: *mut $crate::generated::nros_platform_task_attr_t,
1004        ) {
1005            if attr.is_null() {
1006                return;
1007            }
1008            // SAFETY: non-null, and the caller owns writable storage of this
1009            // type by the ABI contract.
1010            unsafe {
1011                (*attr).name = ::core::ptr::null();
1012                (*attr).stack_bytes = 0;
1013                (*attr).stack_mem = ::core::ptr::null_mut();
1014                (*attr).priority = i32::MIN;
1015                (*attr).core = -1;
1016                (*attr).flags = 0;
1017            }
1018        }
1019        // NOTE: `nros_platform_task_storage_{size,align}` are emitted above,
1020        // beside their `wake_storage_*` siblings — not here with the lock
1021        // family. A second copy landed here and made every port that invokes
1022        // this macro fail with E0428; both spans pointed at the same macro
1023        // call, which is what a macro emitting a symbol twice looks like.
1024        #[unsafe(no_mangle)]
1025        pub extern "C" fn nros_platform_mutex_storage_size() -> usize {
1026            <$ty as ::nros_platform_api::PlatformThreading>::mutex_storage_size()
1027        }
1028        #[unsafe(no_mangle)]
1029        pub extern "C" fn nros_platform_mutex_storage_align() -> usize {
1030            <$ty as ::nros_platform_api::PlatformThreading>::mutex_storage_align()
1031        }
1032        #[unsafe(no_mangle)]
1033        pub extern "C" fn nros_platform_mutex_rec_storage_size() -> usize {
1034            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_storage_size()
1035        }
1036        #[unsafe(no_mangle)]
1037        pub extern "C" fn nros_platform_mutex_rec_storage_align() -> usize {
1038            <$ty as ::nros_platform_api::PlatformThreading>::mutex_rec_storage_align()
1039        }
1040        #[unsafe(no_mangle)]
1041        pub extern "C" fn nros_platform_condvar_storage_size() -> usize {
1042            <$ty as ::nros_platform_api::PlatformThreading>::condvar_storage_size()
1043        }
1044        #[unsafe(no_mangle)]
1045        pub extern "C" fn nros_platform_condvar_storage_align() -> usize {
1046            <$ty as ::nros_platform_api::PlatformThreading>::condvar_storage_align()
1047        }
1048    };
1049}
1050
1051/// Phase 121.9 — emit the two `nros_platform_critical_section_*`
1052/// symbols by delegating to the caller's `PlatformCriticalSection`
1053/// impl.
1054#[macro_export]
1055macro_rules! nros_platform_export_critical_section {
1056    ($ty:ty) => {
1057        #[unsafe(no_mangle)]
1058        pub extern "C" fn nros_platform_critical_section_acquire() -> u32 {
1059            <$ty as ::nros_platform_api::PlatformCriticalSection>::acquire()
1060        }
1061        #[unsafe(no_mangle)]
1062        pub extern "C" fn nros_platform_critical_section_release(token: u32) {
1063            <$ty as ::nros_platform_api::PlatformCriticalSection>::release(token)
1064        }
1065    };
1066}
1067
1068/// Phase 88.11 — emit `nros_platform_log_write` + `nros_platform_log_flush`
1069/// from a `PlatformLog`-implementing ZST. Use this on bare-metal /
1070/// custom platforms (mps2-an385, stm32f4, esp32-baremetal, …) that
1071/// don't ship a separate C implementation file. The implementor's
1072/// `write` receives the rendered body + logger name as `&[u8]` slices.
1073#[macro_export]
1074macro_rules! nros_platform_export_log {
1075    ($ty:ty) => {
1076        #[unsafe(no_mangle)]
1077        pub extern "C" fn nros_platform_log_write(
1078            severity: u8,
1079            name_ptr: *const u8,
1080            name_len: usize,
1081            msg_ptr: *const u8,
1082            msg_len: usize,
1083        ) {
1084            // SAFETY: caller passes valid `&[u8]` slices that outlive
1085            // the call; empty-name case (name_ptr=null, name_len=0)
1086            // collapses to an empty slice.
1087            let name: &[u8] = if name_ptr.is_null() || name_len == 0 {
1088                &[]
1089            } else {
1090                unsafe { ::core::slice::from_raw_parts(name_ptr, name_len) }
1091            };
1092            let msg: &[u8] = if msg_ptr.is_null() || msg_len == 0 {
1093                &[]
1094            } else {
1095                unsafe { ::core::slice::from_raw_parts(msg_ptr, msg_len) }
1096            };
1097            <$ty as ::nros_platform_api::PlatformLog>::write(severity, name, msg);
1098        }
1099        #[unsafe(no_mangle)]
1100        pub extern "C" fn nros_platform_log_flush() {
1101            <$ty as ::nros_platform_api::PlatformLog>::flush()
1102        }
1103        /// ABI-mirror parity. Direct-impl platforms (`mps2-an385`,
1104        /// `stm32f4`, …) route every record through
1105        /// `PlatformLog::write`, so the runtime swap slot is
1106        /// meaningless to them. The header mirror nonetheless declares
1107        /// `nros_platform_register_log_writer`, so the macro emits a
1108        /// no-op stub to satisfy the ABI-mirror check. Fn-ptr-slot
1109        /// platforms (FreeRTOS / ThreadX / NuttX) don't call this macro
1110        /// — their C body ships the real strong definition.
1111        #[unsafe(no_mangle)]
1112        pub extern "C" fn nros_platform_register_log_writer(
1113            _writer: ::core::option::Option<
1114                unsafe extern "C" fn(
1115                    severity: u8,
1116                    name_ptr: *const u8,
1117                    name_len: usize,
1118                    msg_ptr: *const u8,
1119                    msg_len: usize,
1120                ),
1121            >,
1122            _flusher: ::core::option::Option<unsafe extern "C" fn()>,
1123        ) {
1124        }
1125    };
1126}
1127
1128/// Convenience: emit every `nros_platform_*` symbol declared in
1129/// `<nros/platform.h>` by delegating to the corresponding
1130/// `nros_platform_api::Platform*` trait method on `$ty`. The caller must
1131/// implement every trait covered by the capability macros.
1132///
1133/// Logging (`nros_platform_export_log!`) is NOT part of this convenience
1134/// macro: bare-metal platforms typically need to supply a writer
1135/// (`hprintln!` / `defmt::info!`) that requires extra deps not all
1136/// platforms link against. Call `nros_platform_export_log!` separately
1137/// after the platform crate implements `PlatformLog`.
1138#[macro_export]
1139macro_rules! nros_platform_export {
1140    ($ty:ty) => {
1141        $crate::nros_platform_export_clock!($ty);
1142        $crate::nros_platform_export_alloc!($ty);
1143        $crate::nros_platform_export_sleep!($ty);
1144        $crate::nros_platform_export_yield!($ty);
1145        $crate::nros_platform_export_random!($ty);
1146        $crate::nros_platform_export_time!($ty);
1147        $crate::nros_platform_export_threading!($ty);
1148        $crate::nros_platform_export_critical_section!($ty);
1149    };
1150}
1151
1152// ============================================================================
1153// Phase 121.6.macros — extended-surface export macros
1154// ----------------------------------------------------------------------------
1155// `nros_platform_export_net!` mirrors `<nros/platform_net.h>` 1:1; trait
1156// signatures match the C ABI byte-for-byte. `nros_platform_export_timer!`
1157// adapts the Rust `PlatformTimer` trait's `Result<TimerHandle, _>` to the
1158// C ABI's `*mut c_void` (NULL on error). The caller's `TimerHandle`
1159// associated type must be `*mut c_void` — enforced at macro-expansion
1160// time via a `where` clause on the emitted dispatch functions.
1161// ============================================================================
1162
1163/// Emit every `nros_platform_timer_*` symbol declared in
1164/// `<nros/platform_timer.h>` by delegating to the corresponding
1165/// `PlatformTimer` trait method on `$ty`.
1166///
1167/// **Constraint:** the implementor's `TimerHandle` associated type
1168/// must be `*mut core::ffi::c_void` so the macro can pass the handle
1169/// through the C ABI unchanged. Implementations using kernel-specific
1170/// handle types should wrap them in a `*mut c_void` (typically by
1171/// `Box::into_raw` + a thin newtype) before exporting.
1172#[macro_export]
1173macro_rules! nros_platform_export_timer {
1174    ($ty:ty) => {
1175        // Compile-time guard: handle must be pointer-sized so the
1176        // transmute below is sound. PlatformTimer requires Send +
1177        // Sync + 'static, which `*mut c_void` itself fails — so
1178        // callers wrap their handle in a `#[repr(transparent)]`
1179        // newtype that implements those (PosixTimerHandle, etc.).
1180        // We round-trip through transmute at the C ABI boundary.
1181        const _: () = {
1182            if ::core::mem::size_of::<<$ty as ::nros_platform_api::PlatformTimer>::TimerHandle>()
1183                != ::core::mem::size_of::<*mut ::core::ffi::c_void>()
1184            {
1185                panic!(
1186                    "nros_platform_export_timer! requires \
1187                     PlatformTimer::TimerHandle to be pointer-sized"
1188                );
1189            }
1190        };
1191
1192        #[unsafe(no_mangle)]
1193        pub extern "C" fn nros_platform_timer_create_periodic(
1194            period_us: u32,
1195            callback: extern "C" fn(*mut ::core::ffi::c_void),
1196            user_data: *mut ::core::ffi::c_void,
1197        ) -> *mut ::core::ffi::c_void {
1198            match <$ty as ::nros_platform_api::PlatformTimer>::create_periodic(
1199                period_us, callback, user_data,
1200            ) {
1201                Ok(h) => unsafe {
1202                    ::core::mem::transmute_copy::<
1203                        <$ty as ::nros_platform_api::PlatformTimer>::TimerHandle,
1204                        *mut ::core::ffi::c_void,
1205                    >(&::core::mem::ManuallyDrop::new(h))
1206                },
1207                Err(_) => ::core::ptr::null_mut(),
1208            }
1209        }
1210        #[unsafe(no_mangle)]
1211        pub extern "C" fn nros_platform_timer_create_oneshot(
1212            timeout_us: u32,
1213            callback: extern "C" fn(*mut ::core::ffi::c_void),
1214            user_data: *mut ::core::ffi::c_void,
1215        ) -> *mut ::core::ffi::c_void {
1216            match <$ty as ::nros_platform_api::PlatformTimer>::create_oneshot(
1217                timeout_us, callback, user_data,
1218            ) {
1219                Ok(h) => unsafe {
1220                    ::core::mem::transmute_copy::<
1221                        <$ty as ::nros_platform_api::PlatformTimer>::TimerHandle,
1222                        *mut ::core::ffi::c_void,
1223                    >(&::core::mem::ManuallyDrop::new(h))
1224                },
1225                Err(_) => ::core::ptr::null_mut(),
1226            }
1227        }
1228        #[unsafe(no_mangle)]
1229        pub extern "C" fn nros_platform_timer_destroy(handle: *mut ::core::ffi::c_void) {
1230            let h: <$ty as ::nros_platform_api::PlatformTimer>::TimerHandle = unsafe {
1231                ::core::mem::transmute_copy::<
1232                    *mut ::core::ffi::c_void,
1233                    <$ty as ::nros_platform_api::PlatformTimer>::TimerHandle,
1234                >(&handle)
1235            };
1236            <$ty as ::nros_platform_api::PlatformTimer>::destroy(h)
1237        }
1238        #[unsafe(no_mangle)]
1239        pub extern "C" fn nros_platform_timer_cancel(handle: *mut ::core::ffi::c_void) -> i8 {
1240            let mut h: <$ty as ::nros_platform_api::PlatformTimer>::TimerHandle = unsafe {
1241                ::core::mem::transmute_copy::<
1242                    *mut ::core::ffi::c_void,
1243                    <$ty as ::nros_platform_api::PlatformTimer>::TimerHandle,
1244                >(&handle)
1245            };
1246            if <$ty as ::nros_platform_api::PlatformTimer>::cancel(&mut h) {
1247                1
1248            } else {
1249                0
1250            }
1251        }
1252    };
1253}
1254
1255/// Emit every `nros_platform_tcp_*` / `nros_platform_udp_*` /
1256/// `nros_platform_udp_mcast_*` / `nros_platform_socket_*` /
1257/// `nros_platform_network_poll` symbol declared in
1258/// `<nros/platform_net.h>` by delegating to the corresponding trait
1259/// method on `$ty`. The caller must implement `PlatformTcp`,
1260/// `PlatformUdp`, `PlatformUdpMulticast`, `PlatformSocketHelpers`, and
1261/// `PlatformNetworkPoll`.
1262#[macro_export]
1263macro_rules! nros_platform_export_net {
1264    ($ty:ty) => {
1265        // ---- TCP ----
1266        #[unsafe(no_mangle)]
1267        pub extern "C" fn nros_platform_tcp_create_endpoint(
1268            ep: *mut ::core::ffi::c_void,
1269            address: *const u8,
1270            port: *const u8,
1271        ) -> i8 {
1272            <$ty as ::nros_platform_api::PlatformTcp>::create_endpoint(ep, address, port)
1273        }
1274        #[unsafe(no_mangle)]
1275        pub extern "C" fn nros_platform_tcp_free_endpoint(ep: *mut ::core::ffi::c_void) {
1276            <$ty as ::nros_platform_api::PlatformTcp>::free_endpoint(ep)
1277        }
1278        #[unsafe(no_mangle)]
1279        pub extern "C" fn nros_platform_tcp_open(
1280            sock: *mut ::core::ffi::c_void,
1281            endpoint: *const ::core::ffi::c_void,
1282            timeout_ms: u32,
1283        ) -> i8 {
1284            <$ty as ::nros_platform_api::PlatformTcp>::open(sock, endpoint, timeout_ms)
1285        }
1286        #[unsafe(no_mangle)]
1287        pub extern "C" fn nros_platform_tcp_open_within(
1288            sock: *mut ::core::ffi::c_void,
1289            endpoint: *const ::core::ffi::c_void,
1290            timeout_ms: u32,
1291            connect_timeout_ms: i32,
1292        ) -> i8 {
1293            <$ty as ::nros_platform_api::PlatformTcp>::open_within(
1294                sock,
1295                endpoint,
1296                timeout_ms,
1297                connect_timeout_ms,
1298            )
1299        }
1300        #[unsafe(no_mangle)]
1301        pub extern "C" fn nros_platform_tcp_listen(
1302            sock: *mut ::core::ffi::c_void,
1303            endpoint: *const ::core::ffi::c_void,
1304        ) -> i8 {
1305            <$ty as ::nros_platform_api::PlatformTcp>::listen(sock, endpoint)
1306        }
1307        #[unsafe(no_mangle)]
1308        pub extern "C" fn nros_platform_tcp_close(sock: *mut ::core::ffi::c_void) {
1309            <$ty as ::nros_platform_api::PlatformTcp>::close(sock)
1310        }
1311        #[unsafe(no_mangle)]
1312        pub extern "C" fn nros_platform_tcp_read(
1313            sock: *const ::core::ffi::c_void,
1314            buf: *mut u8,
1315            len: usize,
1316        ) -> usize {
1317            <$ty as ::nros_platform_api::PlatformTcp>::read(sock, buf, len)
1318        }
1319        #[unsafe(no_mangle)]
1320        pub extern "C" fn nros_platform_tcp_read_exact(
1321            sock: *const ::core::ffi::c_void,
1322            buf: *mut u8,
1323            len: usize,
1324        ) -> usize {
1325            <$ty as ::nros_platform_api::PlatformTcp>::read_exact(sock, buf, len)
1326        }
1327        #[unsafe(no_mangle)]
1328        pub extern "C" fn nros_platform_tcp_send(
1329            sock: *const ::core::ffi::c_void,
1330            buf: *const u8,
1331            len: usize,
1332        ) -> usize {
1333            <$ty as ::nros_platform_api::PlatformTcp>::send(sock, buf, len)
1334        }
1335        #[unsafe(no_mangle)]
1336        pub extern "C" fn nros_platform_tcp_set_rx_notify(
1337            sock: *const ::core::ffi::c_void,
1338            notify: ::core::option::Option<unsafe extern "C" fn(*mut ::core::ffi::c_void)>,
1339            ctx: *mut ::core::ffi::c_void,
1340        ) -> i8 {
1341            <$ty as ::nros_platform_api::PlatformTcp>::set_rx_notify(sock, notify, ctx)
1342        }
1343
1344        // ---- UDP unicast ----
1345        #[unsafe(no_mangle)]
1346        pub extern "C" fn nros_platform_udp_create_endpoint(
1347            ep: *mut ::core::ffi::c_void,
1348            address: *const u8,
1349            port: *const u8,
1350        ) -> i8 {
1351            <$ty as ::nros_platform_api::PlatformUdp>::create_endpoint(ep, address, port)
1352        }
1353        #[unsafe(no_mangle)]
1354        pub extern "C" fn nros_platform_udp_free_endpoint(ep: *mut ::core::ffi::c_void) {
1355            <$ty as ::nros_platform_api::PlatformUdp>::free_endpoint(ep)
1356        }
1357        #[unsafe(no_mangle)]
1358        pub extern "C" fn nros_platform_udp_open(
1359            sock: *mut ::core::ffi::c_void,
1360            endpoint: *const ::core::ffi::c_void,
1361            timeout_ms: u32,
1362        ) -> i8 {
1363            <$ty as ::nros_platform_api::PlatformUdp>::open(sock, endpoint, timeout_ms)
1364        }
1365        #[unsafe(no_mangle)]
1366        pub extern "C" fn nros_platform_udp_listen(
1367            sock: *mut ::core::ffi::c_void,
1368            endpoint: *const ::core::ffi::c_void,
1369            timeout_ms: u32,
1370        ) -> i8 {
1371            <$ty as ::nros_platform_api::PlatformUdp>::listen(sock, endpoint, timeout_ms)
1372        }
1373        #[unsafe(no_mangle)]
1374        pub extern "C" fn nros_platform_udp_close(sock: *mut ::core::ffi::c_void) {
1375            <$ty as ::nros_platform_api::PlatformUdp>::close(sock)
1376        }
1377        #[unsafe(no_mangle)]
1378        pub extern "C" fn nros_platform_udp_read(
1379            sock: *const ::core::ffi::c_void,
1380            buf: *mut u8,
1381            len: usize,
1382        ) -> usize {
1383            <$ty as ::nros_platform_api::PlatformUdp>::read(sock, buf, len)
1384        }
1385        #[unsafe(no_mangle)]
1386        pub extern "C" fn nros_platform_udp_read_exact(
1387            sock: *const ::core::ffi::c_void,
1388            buf: *mut u8,
1389            len: usize,
1390        ) -> usize {
1391            <$ty as ::nros_platform_api::PlatformUdp>::read_exact(sock, buf, len)
1392        }
1393        #[unsafe(no_mangle)]
1394        pub extern "C" fn nros_platform_udp_send(
1395            sock: *const ::core::ffi::c_void,
1396            buf: *const u8,
1397            len: usize,
1398            endpoint: *const ::core::ffi::c_void,
1399        ) -> usize {
1400            <$ty as ::nros_platform_api::PlatformUdp>::send(sock, buf, len, endpoint)
1401        }
1402        #[unsafe(no_mangle)]
1403        pub extern "C" fn nros_platform_udp_set_recv_timeout(
1404            sock: *const ::core::ffi::c_void,
1405            timeout_ms: u32,
1406        ) {
1407            <$ty as ::nros_platform_api::PlatformUdp>::set_recv_timeout(sock, timeout_ms)
1408        }
1409        #[unsafe(no_mangle)]
1410        pub extern "C" fn nros_platform_udp_readiness_handle(
1411            sock: *const ::core::ffi::c_void,
1412        ) -> i32 {
1413            <$ty as ::nros_platform_api::PlatformUdp>::readiness_handle(sock)
1414        }
1415        #[unsafe(no_mangle)]
1416        pub extern "C" fn nros_platform_udp_set_rx_notify(
1417            sock: *const ::core::ffi::c_void,
1418            notify: ::core::option::Option<unsafe extern "C" fn(*mut ::core::ffi::c_void)>,
1419            ctx: *mut ::core::ffi::c_void,
1420        ) -> i8 {
1421            <$ty as ::nros_platform_api::PlatformUdp>::set_rx_notify(sock, notify, ctx)
1422        }
1423
1424        // ---- UDP multicast ----
1425        #[unsafe(no_mangle)]
1426        pub extern "C" fn nros_platform_udp_mcast_open(
1427            sock: *mut ::core::ffi::c_void,
1428            endpoint: *const ::core::ffi::c_void,
1429            lep: *mut ::core::ffi::c_void,
1430            timeout_ms: u32,
1431            iface: *const u8,
1432        ) -> i8 {
1433            <$ty as ::nros_platform_api::PlatformUdpMulticast>::mcast_open(
1434                sock, endpoint, lep, timeout_ms, iface,
1435            )
1436        }
1437        #[unsafe(no_mangle)]
1438        pub extern "C" fn nros_platform_udp_mcast_listen(
1439            sock: *mut ::core::ffi::c_void,
1440            endpoint: *const ::core::ffi::c_void,
1441            timeout_ms: u32,
1442            iface: *const u8,
1443            join: *const u8,
1444        ) -> i8 {
1445            <$ty as ::nros_platform_api::PlatformUdpMulticast>::mcast_listen(
1446                sock, endpoint, timeout_ms, iface, join,
1447            )
1448        }
1449        #[unsafe(no_mangle)]
1450        pub extern "C" fn nros_platform_udp_mcast_close(
1451            sockrecv: *mut ::core::ffi::c_void,
1452            socksend: *mut ::core::ffi::c_void,
1453            rep: *const ::core::ffi::c_void,
1454            lep: *const ::core::ffi::c_void,
1455        ) {
1456            <$ty as ::nros_platform_api::PlatformUdpMulticast>::mcast_close(
1457                sockrecv, socksend, rep, lep,
1458            )
1459        }
1460        #[unsafe(no_mangle)]
1461        pub extern "C" fn nros_platform_udp_mcast_read(
1462            sock: *const ::core::ffi::c_void,
1463            buf: *mut u8,
1464            len: usize,
1465            lep: *const ::core::ffi::c_void,
1466            addr: *mut ::core::ffi::c_void,
1467        ) -> usize {
1468            <$ty as ::nros_platform_api::PlatformUdpMulticast>::mcast_read(
1469                sock, buf, len, lep, addr,
1470            )
1471        }
1472        #[unsafe(no_mangle)]
1473        pub extern "C" fn nros_platform_udp_mcast_read_exact(
1474            sock: *const ::core::ffi::c_void,
1475            buf: *mut u8,
1476            len: usize,
1477            lep: *const ::core::ffi::c_void,
1478            addr: *mut ::core::ffi::c_void,
1479        ) -> usize {
1480            <$ty as ::nros_platform_api::PlatformUdpMulticast>::mcast_read_exact(
1481                sock, buf, len, lep, addr,
1482            )
1483        }
1484        #[unsafe(no_mangle)]
1485        pub extern "C" fn nros_platform_udp_mcast_send(
1486            sock: *const ::core::ffi::c_void,
1487            buf: *const u8,
1488            len: usize,
1489            endpoint: *const ::core::ffi::c_void,
1490        ) -> usize {
1491            <$ty as ::nros_platform_api::PlatformUdpMulticast>::mcast_send(sock, buf, len, endpoint)
1492        }
1493
1494        // ---- Socket helpers ----
1495        #[unsafe(no_mangle)]
1496        pub extern "C" fn nros_platform_socket_set_non_blocking(
1497            sock: *const ::core::ffi::c_void,
1498        ) -> i8 {
1499            <$ty as ::nros_platform_api::PlatformSocketHelpers>::set_non_blocking(sock)
1500        }
1501        #[unsafe(no_mangle)]
1502        pub extern "C" fn nros_platform_socket_accept(
1503            sock_in: *const ::core::ffi::c_void,
1504            sock_out: *mut ::core::ffi::c_void,
1505        ) -> i8 {
1506            <$ty as ::nros_platform_api::PlatformSocketHelpers>::accept(sock_in, sock_out)
1507        }
1508        #[unsafe(no_mangle)]
1509        pub extern "C" fn nros_platform_socket_close(sock: *mut ::core::ffi::c_void) {
1510            <$ty as ::nros_platform_api::PlatformSocketHelpers>::close(sock)
1511        }
1512        #[unsafe(no_mangle)]
1513        pub extern "C" fn nros_platform_socket_wait_event(
1514            peers: *mut ::core::ffi::c_void,
1515            mutex: *mut ::core::ffi::c_void,
1516        ) -> i8 {
1517            <$ty as ::nros_platform_api::PlatformSocketHelpers>::wait_event(peers, mutex)
1518        }
1519
1520        // ---- Network poll ----
1521        #[unsafe(no_mangle)]
1522        pub extern "C" fn nros_platform_network_poll() {
1523            <$ty as ::nros_platform_api::PlatformNetworkPoll>::network_poll()
1524        }
1525    };
1526}
1527
1528/// Emit the five `nros_platform_can_*` symbols declared in
1529/// `<nros/platform_can.h>` by delegating to the
1530/// `PlatformCan` implementation on `$ty`. The typed header pointers are
1531/// passed to the trait as `c_void` pointers, unchanged.
1532#[macro_export]
1533macro_rules! nros_platform_export_can {
1534    ($ty:ty) => {
1535        #[unsafe(no_mangle)]
1536        pub extern "C" fn nros_platform_can_open(
1537            can: *mut $crate::nros_platform_can_t,
1538            device: *const ::core::ffi::c_char,
1539            want_fd: u8,
1540        ) -> i8 {
1541            <$ty as ::nros_platform_api::PlatformCan>::open(can.cast(), device, want_fd)
1542        }
1543        #[unsafe(no_mangle)]
1544        pub extern "C" fn nros_platform_can_send(
1545            can: *mut $crate::nros_platform_can_t,
1546            frame: *const $crate::nros_platform_can_frame_t,
1547            timeout_us: u32,
1548        ) -> i8 {
1549            <$ty as ::nros_platform_api::PlatformCan>::send(can.cast(), frame.cast(), timeout_us)
1550        }
1551        #[unsafe(no_mangle)]
1552        pub extern "C" fn nros_platform_can_fd_active(
1553            can: *const $crate::nros_platform_can_t,
1554        ) -> u8 {
1555            <$ty as ::nros_platform_api::PlatformCan>::fd_active(can.cast())
1556        }
1557        #[unsafe(no_mangle)]
1558        pub extern "C" fn nros_platform_can_recv(
1559            can: *mut $crate::nros_platform_can_t,
1560            frame: *mut $crate::nros_platform_can_frame_t,
1561            timeout_us: u32,
1562        ) -> i8 {
1563            <$ty as ::nros_platform_api::PlatformCan>::recv(can.cast(), frame.cast(), timeout_us)
1564        }
1565        #[unsafe(no_mangle)]
1566        pub extern "C" fn nros_platform_can_close(can: *mut $crate::nros_platform_can_t) {
1567            <$ty as ::nros_platform_api::PlatformCan>::close(can.cast())
1568        }
1569    };
1570}
1571
1572// ============================================================================
1573// Test-only self-export
1574// ----------------------------------------------------------------------------
1575// `cargo test -p nros-platform-cffi` builds a test binary that links the
1576// rlib. The `unsafe extern "C"` declarations above would fail to link
1577// without definitions; we satisfy them by invoking the macro on a dummy
1578// `TestPlatform` ZST defined here. This doubles as a smoke test that
1579// every macro arm expands and that the trait dispatch resolves.
1580//
1581// Real platform crates supply their own definitions via the same macro
1582// and never compile this module (it is gated on `cfg(test)`).
1583// ============================================================================
1584
1585#[cfg(all(test, not(feature = "c-stub-test"), not(feature = "posix-c-port")))]
1586mod test_self_export {
1587    use core::ffi::c_void;
1588    use nros_platform_api::{
1589        PlatformAlloc, PlatformClock, PlatformRandom, PlatformSleep, PlatformThreading,
1590        PlatformTime, PlatformYield,
1591    };
1592
1593    pub struct TestPlatform;
1594
1595    impl PlatformClock for TestPlatform {
1596        fn clock_ns() -> u64 {
1597            0
1598        }
1599        fn clock_resolution_ns() -> u64 {
1600            1
1601        }
1602    }
1603    impl PlatformAlloc for TestPlatform {
1604        fn alloc(_: usize) -> *mut c_void {
1605            core::ptr::null_mut()
1606        }
1607        fn realloc(_: *mut c_void, _: usize) -> *mut c_void {
1608            core::ptr::null_mut()
1609        }
1610        fn dealloc(_: *mut c_void) {}
1611    }
1612    impl PlatformSleep for TestPlatform {
1613        fn sleep_us(_: usize) {}
1614        fn sleep_ms(_: usize) {}
1615        fn sleep_s(_: usize) {}
1616    }
1617    impl PlatformYield for TestPlatform {
1618        fn yield_now() {}
1619    }
1620    impl PlatformRandom for TestPlatform {
1621        fn random_u8() -> u8 {
1622            0
1623        }
1624        fn random_u16() -> u16 {
1625            0
1626        }
1627        fn random_u32() -> u32 {
1628            0
1629        }
1630        fn random_u64() -> u64 {
1631            0
1632        }
1633        fn random_fill(_: *mut c_void, _: usize) {}
1634    }
1635    impl PlatformTime for TestPlatform {
1636        fn time_now_ns() -> u64 {
1637            0
1638        }
1639        fn wall_clock_state() -> nros_platform_api::WallClockState {
1640            nros_platform_api::WallClockState::UNSYNCED_PLATFORM
1641        }
1642    }
1643    impl PlatformThreading for TestPlatform {
1644        fn task_init(
1645            _: *mut c_void,
1646            _: *mut c_void,
1647            _: Option<unsafe extern "C" fn(*mut c_void) -> *mut c_void>,
1648            _: *mut c_void,
1649        ) -> i8 {
1650            -1
1651        }
1652        fn task_join(_: *mut c_void) -> i8 {
1653            -1
1654        }
1655        fn task_detach(_: *mut c_void) -> i8 {
1656            -1
1657        }
1658        fn task_cancel(_: *mut c_void) -> i8 {
1659            -1
1660        }
1661        fn task_exit() {}
1662        fn task_free(_: *mut *mut c_void) {}
1663        fn mutex_init(_: *mut c_void) -> i8 {
1664            0
1665        }
1666        fn mutex_drop(_: *mut c_void) -> i8 {
1667            0
1668        }
1669        fn mutex_lock(_: *mut c_void) -> i8 {
1670            0
1671        }
1672        fn mutex_try_lock(_: *mut c_void) -> i8 {
1673            0
1674        }
1675        fn mutex_unlock(_: *mut c_void) -> i8 {
1676            0
1677        }
1678        fn mutex_rec_init(_: *mut c_void) -> i8 {
1679            0
1680        }
1681        fn mutex_rec_drop(_: *mut c_void) -> i8 {
1682            0
1683        }
1684        fn mutex_rec_lock(_: *mut c_void) -> i8 {
1685            0
1686        }
1687        fn mutex_rec_try_lock(_: *mut c_void) -> i8 {
1688            0
1689        }
1690        fn mutex_rec_unlock(_: *mut c_void) -> i8 {
1691            0
1692        }
1693        fn condvar_init(_: *mut c_void) -> i8 {
1694            0
1695        }
1696        fn condvar_drop(_: *mut c_void) -> i8 {
1697            0
1698        }
1699        fn condvar_signal(_: *mut c_void) -> i8 {
1700            0
1701        }
1702        fn condvar_signal_all(_: *mut c_void) -> i8 {
1703            0
1704        }
1705        fn condvar_wait_until(_: *mut c_void, _: *mut c_void, _: u64) -> i8 {
1706            0
1707        }
1708    }
1709    impl ::nros_platform_api::PlatformCriticalSection for TestPlatform {
1710        fn acquire() -> u32 {
1711            0
1712        }
1713        fn release(_: u32) {}
1714    }
1715
1716    /// Pointer-sized newtype wrapping `*mut c_void` so the
1717    /// PlatformTimer Send + Sync + 'static bound is satisfied.
1718    /// The transmute inside `nros_platform_export_timer!` rests on
1719    /// this being `#[repr(transparent)]` over a pointer.
1720    #[repr(transparent)]
1721    #[derive(Clone, Copy)]
1722    pub struct TestTimerHandle(pub *mut c_void);
1723    unsafe impl Send for TestTimerHandle {}
1724    unsafe impl Sync for TestTimerHandle {}
1725
1726    impl ::nros_platform_api::PlatformTimer for TestPlatform {
1727        type TimerHandle = TestTimerHandle;
1728        // create_periodic / create_oneshot / destroy / cancel inherit
1729        // the trait's default impls (return TimerError::Unsupported /
1730        // no-op destroy / false cancel) — fine for export-emission
1731        // verification.
1732    }
1733
1734    crate::nros_platform_export!(TestPlatform);
1735    crate::nros_platform_export_timer!(TestPlatform);
1736
1737    #[test]
1738    fn macro_expansion_dispatches() {
1739        // Touch every group through the FFI surface to confirm the
1740        // generated symbols are reachable and dispatch resolves.
1741        assert_eq!(super::CffiPlatform::clock_ns(), 0);
1742        assert_eq!(
1743            <super::CffiPlatform as ::nros_platform_api::PlatformAlloc>::alloc(0),
1744            core::ptr::null_mut(),
1745        );
1746        <super::CffiPlatform as ::nros_platform_api::PlatformYield>::yield_now();
1747    }
1748
1749    #[test]
1750    fn timer_macro_emits() {
1751        // Default impl returns Unsupported → null handle.
1752        let h = unsafe {
1753            super::nros_platform_timer_create_periodic(
1754                1000,
1755                Some(noop_callback),
1756                core::ptr::null_mut(),
1757            )
1758        };
1759        assert!(h.is_null(), "default Unsupported impl must surface as NULL");
1760    }
1761
1762    // bindgen wraps C function-pointer parameters in `Option`, and the
1763    // pointee is `unsafe extern "C"` — issue #545.
1764    unsafe extern "C" fn noop_callback(_: *mut c_void) {}
1765}