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