Skip to main content

nros/
sizes.rs

1//! Single source of truth for FFI opaque-storage sizes.
2//!
3//! Each `export_size!` invocation produces two artefacts:
4//!
5//! * `pub const FOO_SIZE: usize = core::mem::size_of::<T>();` — a normal
6//!   Rust const suitable for in-crate `const _: () = assert!(...)` checks and
7//!   direct use by `no_std` consumers.
8//! * `pub static __NROS_SIZE_FOO: [u8; FOO_SIZE] = [0; FOO_SIZE];` — an
9//!   array-sized static whose *symbol storage size* in the compiled rlib
10//!   equals `FOO_SIZE`. `nros-c`/`nros-cpp` build scripts read the sizes out
11//!   via [`nros_sizes_build::extract_sizes`](../../../nros-sizes-build/index.html)
12//!   to derive opaque-storage macros for the generated C/C++ headers.
13//!
14//! Feature gating follows the rest of the crate: the statics only exist when
15//! an RMW backend (`rmw-zenoh` / `rmw-xrce` / `rmw-cyclonedds` / `rmw-cffi`) is
16//! active, which is exactly the condition under which the `Rmw*` type
17//! aliases resolve. Workspace-level `cargo check` without any RMW feature
18//! sees this module as empty.
19
20#[cfg(feature = "rmw-cffi")]
21mod rmw_sizes {
22    use crate::internals::{
23        RmwPublisher, RmwServiceClient, RmwServiceServer, RmwSession, RmwSubscriber,
24    };
25
26    // Phase 77.25: per-name v0-mangled markers so the probe works
27    // under fat LTO. Each call to `export_size!(NAME = Ty)` expands to
28    // a distinct generic fn `__nros_size_NAME<const N: usize>` plus a
29    // monomorphised fn-pointer static. The monomorphisation's v0
30    // mangled symbol name contains both the name ("NAME") *and* the
31    // const-generic value (the size) — e.g. demangles as
32    // `nros::sizes::rmw_sizes::__nros_size_PUBLISHER_SIZE::<48>`.
33    // Symbol names survive LTO because the linker still needs them,
34    // even when the object file is LLVM bitcode and `object::parse`
35    // can't read symbol byte sizes. The original `__NROS_SIZE_<NAME>`
36    // static kept for backwards-compat is also emitted for consumers
37    // that still walk the legacy path.
38    #[doc(hidden)]
39    pub mod _size_markers {}
40
41    macro_rules! export_size {
42        ($vis:vis $name:ident = $ty:ty) => {
43            $vis const $name: usize = core::mem::size_of::<$ty>();
44            paste::paste! {
45                #[cfg_attr(feature = "ffi-size-markers", used)]
46                #[unsafe(no_mangle)]
47                #[doc(hidden)]
48                pub static [<__NROS_SIZE_ $name>]: [u8; $name] = [0u8; $name];
49
50                #[doc(hidden)]
51                #[allow(non_snake_case)]
52                #[inline(never)]
53                pub fn [<__nros_size_ $name>]<const N: usize>() -> usize { N }
54
55                #[cfg_attr(feature = "ffi-size-markers", used)]
56                #[doc(hidden)]
57                pub static [<__NROS_SIZE_FN_ $name>]: fn() -> usize =
58                    [<__nros_size_ $name>]::<{ $name }>;
59            }
60        };
61    }
62
63    export_size!(pub SESSION_SIZE        = RmwSession);
64    export_size!(pub PUBLISHER_SIZE      = RmwPublisher);
65    export_size!(pub SUBSCRIBER_SIZE     = RmwSubscriber);
66    export_size!(pub SERVICE_CLIENT_SIZE = RmwServiceClient);
67    export_size!(pub SERVICE_SERVER_SIZE = RmwServiceServer);
68
69    // Phase 122.3.c.3 — L1 polling-mode Raw* handles. Defaults to
70    // `DEFAULT_RX_BUF_SIZE` on each const-generic slot, which is
71    // exactly the value `nros-c::config::MESSAGE_BUFFER_SIZE` resolves
72    // to (both derive from `NROS_SUBSCRIPTION_BUFFER_SIZE` via
73    // `nros-node`'s build.rs). nros-c's build.rs reads these probe
74    // values and emits the matching `*_OPAQUE_U64S` macros into the
75    // per-build variant header so C struct `_opaque` storage agrees
76    // with the Rust struct layout. Without this probe, cbindgen
77    // ships a `_OPAQUE_U64S = 1` placeholder which silently
78    // truncates the C-side `_opaque` slot.
79    export_size!(pub RAW_SUBSCRIPTION_SIZE   = nros_node::RawSubscription);
80    export_size!(pub RAW_SERVICE_SERVER_SIZE = nros_node::RawServiceServer);
81    export_size!(pub RAW_SERVICE_CLIENT_SIZE = nros_node::RawServiceClient);
82
83    // Phase 122.3.c.6 — typeless action `*Core` types are the raw
84    // L1 polling-mode entities (typed `ActionServer<A>` / `ActionClient<A>`
85    // wrap them with serdes glue). Default const generics resolve to
86    // `DEFAULT_RX_BUF_SIZE` (= `MESSAGE_BUFFER_SIZE` in nros-c) and
87    // `MAX_GOALS = 4`, matching the L2 callback path.
88    export_size!(pub RAW_ACTION_SERVER_SIZE = nros_node::ActionServerCore);
89    export_size!(pub RAW_ACTION_CLIENT_SIZE = nros_node::ActionClientCore);
90
91    // phase-271 — the C/C++ `_opaque` executor buffer holds the `Executor<'static>`
92    // header AND the per-entry storage backing carved from the same buffer, so it
93    // must be sized for the combined `#[repr(C)]` layout, not bare `Executor`.
94    export_size!(pub EXECUTOR_SIZE       = nros_node::ExecutorInlineStorage);
95
96    // issue 0961 — the STACK requirement is a different number from the one
97    // above, and reusing that one would overstate it. `EXECUTOR_SIZE` is the
98    // executor value PLUS its carved backing, which is what the caller's
99    // `_opaque` buffer must hold; the backing lives wherever the caller put
100    // that buffer (`.bss` for a static holder) and never lands on the stack.
101    // What lands on the stack is the bare value: `open_in` builds one in its
102    // frame and returns it, and `nros_cpp_init` holds the returned value
103    // before writing it into the caller's storage — the same value, moved
104    // twice, which is why the check derived from this is `2 x`.
105    //
106    // On a 320 KiB part the overstatement would be a build error refusing an
107    // image that fits, so the two numbers stay separate rather than one being
108    // reused for both jobs.
109    export_size!(pub EXECUTOR_VALUE_SIZE = nros_node::Executor<'static>);
110    export_size!(pub GUARD_CONDITION_SIZE = nros_node::GuardCondition);
111    export_size!(pub LIFECYCLE_CTX_SIZE  = nros_node::lifecycle::LifecyclePollingNodeCtx);
112    // Phase 91.C: nros-c's `ActionServerInternal` embeds this nros-node
113    // type as a typed field. cbindgen (which can't recurse into deps)
114    // emits the field as `ActionServerRawHandle handle;` referencing a
115    // type it cannot define. nros-c's build.rs reads this size and emits
116    // an opaque type-compatible declaration into nros_config_generated.h
117    // so the cbindgen output is self-contained.
118    export_size!(pub ACTION_SERVER_RAW_HANDLE_SIZE = nros_node::ActionServerRawHandle);
119
120    // Layout-mirror struct for `nros_c::action::ActionServerInternal`.
121    // ActionServerInternal lives in the `nros-c` crate (it embeds C-API
122    // pointer types like `*mut nros_action_server_t`), so it can't be
123    // referenced from `nros` directly. This mirror has the same `#[repr(C)]`
124    // field shape — `*mut c_void` and `unsafe extern "C" fn(*mut c_void, ...)`
125    // pointer slots — and therefore the same byte size, since fn-pointer
126    // size is independent of parameter types. nros-c asserts at compile
127    // time that `size_of::<ActionServerInternal>() ==
128    // size_of::<ActionServerInternalLayout>()`.
129    use core::ffi::c_void;
130    type CGoalCallbackLayout =
131        unsafe extern "C" fn(*mut c_void, *const c_void, *const u8, usize, *mut c_void) -> i32;
132    type CCancelCallbackLayout =
133        Option<unsafe extern "C" fn(*const c_void, i32, *mut c_void) -> i32>;
134    type CAcceptedCallbackLayout =
135        Option<unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void)>;
136
137    #[repr(C)]
138    #[doc(hidden)]
139    pub struct ActionServerInternalLayout {
140        pub handle: nros_node::ActionServerRawHandle,
141        pub executor_ptr: *mut c_void,
142        pub c_goal_callback: CGoalCallbackLayout,
143        pub c_cancel_callback: CCancelCallbackLayout,
144        pub c_accepted_callback: CAcceptedCallbackLayout,
145        pub c_context: *mut c_void,
146        pub server_ptr: *mut c_void,
147    }
148    export_size!(pub ACTION_SERVER_INTERNAL_SIZE = ActionServerInternalLayout);
149
150    // Layout-mirrors for nros-cpp's `CppActionServer` and `CppActionClient`.
151    //
152    // Same approach as `ActionServerInternalLayout` above: nros-cpp's
153    // wrapper structs live in a downstream crate but their byte sizes can
154    // be reconstructed from the field shape. This eliminates the
155    // hand-math in `nros-cpp/build.rs` (was Phase 87.11).
156    //
157    // The C++-side `nros::ActionServer<A>` / `nros::ActionClient<A>`
158    // classes hold opaque storage sized to these probe values. nros-cpp
159    // asserts `size_of::<CppActionServer>() == size_of::<CppActionServerLayout>()`
160    // (and the same for CppActionClient) so any field-shape drift in the
161    // real wrapper trips the build immediately.
162
163    type CppGoalCallbackLayout =
164        unsafe extern "C" fn(*const [u8; 16], *const u8, usize, *mut c_void) -> i32;
165    type CppCancelCallbackLayout = unsafe extern "C" fn(*const [u8; 16], *mut c_void) -> i32;
166    // issue 0796 — the C++ callback tier's accepted-goal hook (`CppAcceptedCallback`).
167    type CppAcceptedCallbackLayout = unsafe extern "C" fn(*const [u8; 16], *mut c_void);
168
169    // Byte-shape mirror of one of `nros-cpp`'s `nros_cpp_qos_t` policy enums
170    // (`nros_cpp_qos_reliability_t` et al). These are `#[repr(C)]` fieldless
171    // enums, so their width follows the *target C ABI*: `c_int` (4 bytes) on
172    // x86_64, but **1 byte on ARM EABI** (`armv7a-nuttx-eabihf` defaults to
173    // `-fshort-enums`). Mirroring them as `c_int` (the pre-fix shape) over-sized
174    // the qos block by 12 bytes on ARM and tripped the `CppActionServer`
175    // layout assert. A `#[repr(C)]` enum here tracks the same short-enum width
176    // on every target. Variant count is irrelevant to width while ≤ 255 (all
177    // four real enums have ≤ 4 variants), so one placeholder mirrors all four.
178    #[repr(C)]
179    #[doc(hidden)]
180    pub enum CppQosEnumLayout {
181        A = 0,
182        B = 1,
183    }
184
185    // Phase 193.4b: byte-shape mirror of `nros-cpp`'s `nros_cpp_qos_t`
186    // (4 C-ABI enums + `c_int` depth + 3×u32 + u8). The action server now
187    // stores the create-time QoS until registration; the real
188    // `CppActionServer` field-shape assert keeps this in sync.
189    #[repr(C)]
190    #[doc(hidden)]
191    pub struct CppQosLayout {
192        pub reliability: CppQosEnumLayout,
193        pub durability: CppQosEnumLayout,
194        pub history: CppQosEnumLayout,
195        pub liveliness_kind: CppQosEnumLayout,
196        pub depth: core::ffi::c_int,
197        pub deadline_ms: u32,
198        pub lifespan_ms: u32,
199        pub liveliness_lease_ms: u32,
200        pub avoid_ros_namespace_conventions: u8,
201    }
202
203    // Phase 87.6 thin-wrapper: `action_name` / `type_name` / `type_hash`
204    // buffers moved to the C++ `nros::ActionServer<A>` class.
205    // Phase 104.C.9.b: `node_id` field added so action create→register
206    // can route through the per-Node session.
207    // Phase 193.4b: `qos` field added so create-time QoS reaches the three
208    // underlying service servers at register time.
209    #[repr(C)]
210    #[doc(hidden)]
211    pub struct CppActionServerLayout {
212        pub handle: Option<nros_node::ActionServerRawHandle>,
213        pub goal_cb: Option<CppGoalCallbackLayout>,
214        pub cancel_cb: Option<CppCancelCallbackLayout>,
215        pub accepted_cb: Option<CppAcceptedCallbackLayout>,
216        pub cb_ctx: *mut c_void,
217        pub node_id: u8,
218        pub _reserved: [u8; 7],
219        pub qos: CppQosLayout,
220    }
221    export_size!(pub CPP_ACTION_SERVER_SIZE = CppActionServerLayout);
222
223    type CppActionGoalResponseCb = Option<unsafe extern "C" fn(bool, *const [u8; 16], *mut c_void)>;
224    type CppActionFeedbackCb =
225        Option<unsafe extern "C" fn(*const [u8; 16], *const u8, usize, *mut c_void)>;
226    type CppActionResultCb =
227        Option<unsafe extern "C" fn(*const [u8; 16], i32, *const u8, usize, *mut c_void)>;
228
229    #[repr(C)]
230    #[doc(hidden)]
231    pub struct CppActionClientCallbacksLayout {
232        pub goal_response: CppActionGoalResponseCb,
233        pub feedback: CppActionFeedbackCb,
234        pub result: CppActionResultCb,
235        pub context: *mut c_void,
236    }
237
238    // Phase 87.6 thin-wrapper: `action_name` buffer moved to the C++
239    // `nros::ActionClient<A>` class.
240    #[repr(C)]
241    #[doc(hidden)]
242    pub struct CppActionClientLayout {
243        pub callbacks: CppActionClientCallbacksLayout,
244        pub arena_entry_index: i32,
245        pub executor_ptr: *mut c_void,
246    }
247    export_size!(pub CPP_ACTION_CLIENT_SIZE = CppActionClientLayout);
248}
249
250#[cfg(feature = "rmw-cffi")]
251pub use rmw_sizes::*;