nros_rmw_cffi/lib.rs
1//! C function table adapter for nros RMW backends.
2//!
3//! This crate provides a vtable-based bridge so that backends written in C,
4//! C++, Zig, Ada, or any language with a C-compatible ABI can implement the
5//! nros `Session` / `Publisher` / `Subscription` / service traits without
6//! writing Rust code.
7//!
8//! # Usage (C backend implementor)
9//!
10//! 1. Include `<nros/rmw_vtable.h>`
11//! 2. Implement all function pointers in `nros_rmw_vtable_t`
12//! 3. Call `nros_rmw_cffi_register_named("<name>", &my_vtable)` before creating sessions
13//!
14//! # Usage (Rust consumer)
15//!
16//! Enable the `rmw-cffi` feature on `nros` and use `Executor<CffiSession>`.
17
18#![no_std]
19
20#[cfg(feature = "alloc")]
21extern crate alloc;
22
23#[cfg(feature = "std")]
24extern crate std;
25
26use core::{
27 cell::{Cell, UnsafeCell},
28 ffi::c_void,
29 sync::atomic::Ordering,
30};
31
32// RFC-0054 (phase-299 W1.3) — committed bindgen output from
33// `packages/core/nros-rmw-abi/include/nros/*.h`. This module is the ONLY
34// definition of the RMW ABI types (`nros_rmw_*_t`); the `NrosRmw*` names
35// below are compat aliases over the generated items.
36// (bindgen emits the vtable fn-pointer types inline, which trips
37// clippy::type_complexity under `-D warnings`; allowed here rather than
38// editing the generated file.)
39#[allow(clippy::type_complexity)]
40pub mod generated;
41pub use generated::*;
42
43use nros_rmw::{
44 ClientTrait, GraphEndpointInfo, GraphEntityKind, MessageInfo, Publisher, QoSDurabilityPolicy,
45 QoSHistoryPolicy, QoSLivelinessPolicy, QoSProfile, QoSReliabilityPolicy,
46 REQUEST_WRITER_GUID_SIZE, RequestId, ServiceInfo, ServiceRequest, ServiceRequestInfo,
47 ServiceTrait, Session, TopicInfo, TransportError,
48};
49
50// Phase 115.L.0 — generic Rust→C-vtable adapter. Lives behind the
51// `alloc` feature because each entity handle is boxed for stable
52// address mgmt; every nros backend already requires alloc.
53#[cfg(feature = "alloc")]
54pub mod rust_adapter;
55
56#[cfg(feature = "alloc")]
57pub use rust_adapter::{RustBackend, RustBackendAdapter};
58
59// Issue 1940 — per-entity wake registration, both sides of the vtable.
60mod entity_wake;
61use entity_wake::{WakerSlot, runtime_entity_wake};
62
63// Issue 2410 — the one spelling of "a status on a path with no error channel".
64mod status_report;
65use status_report::{StatusSite, status_ok};
66
67// Phase 249 P4b.1 — `.init_array` ctor self-registration
68// (`nros_rmw_register_backend!` macro lives here).
69pub mod section;
70
71// ============================================================================
72// Phase 102.1 / RFC-0054 — `rmw_ret_t` named return codes
73// ============================================================================
74//
75// The constants live in `generated` (from `<nros/rmw_ret.h>`); only the
76// compat alias and the re-typed `OK` shadow live here.
77
78/// Compat alias for the generated `rmw_ret_t` typedef.
79/// Zero on success; negative on error.
80pub type NrosRmwRet = rmw_ret_t;
81
82/// `$NROS_RMW_TRACE_OPEN` is set — read with the C library's `getenv`, so the
83/// open trace below needs no `std` (phase-359 W10 stage B).
84#[cfg(target_os = "linux")]
85fn trace_open_enabled() -> bool {
86 unsafe extern "C" {
87 fn getenv(name: *const core::ffi::c_char) -> *const core::ffi::c_char;
88 }
89 // SAFETY: the name is a NUL-terminated literal; only nullness is read.
90 unsafe { !getenv(c"NROS_RMW_TRACE_OPEN".as_ptr()).is_null() }
91}
92
93// Anchor every C-stub-transport symbol so they survive
94// `--gc-sections` when integration tests link against
95// libnros_rmw_cffi. Only compiled when the c-stub-test feature
96// is on; otherwise no C anchor + no toolchain dep.
97#[cfg(feature = "c-stub-test")]
98unsafe extern "C" {
99 fn nros_c_stub_make_ops(out: *mut core::ffi::c_void);
100 fn nros_c_stub_reset_counters();
101 fn nros_c_stub_get_open_calls() -> u32;
102 fn nros_c_stub_get_close_calls() -> u32;
103 fn nros_c_stub_get_write_calls() -> u32;
104 fn nros_c_stub_get_read_calls() -> u32;
105}
106#[cfg(feature = "c-stub-test")]
107#[doc(hidden)]
108pub fn _c_stub_transport_vtable_anchor() -> [*const core::ffi::c_void; 6] {
109 [
110 nros_c_stub_make_ops as *const _,
111 nros_c_stub_reset_counters as *const _,
112 nros_c_stub_get_open_calls as *const _,
113 nros_c_stub_get_close_calls as *const _,
114 nros_c_stub_get_write_calls as *const _,
115 nros_c_stub_get_read_calls as *const _,
116 ]
117}
118/// Map a `TransportError` to the corresponding `rmw_ret_t` code.
119///
120/// By-reference because `TransportError` carries a `String` on its
121/// dynamic-diagnostic variant and is not `Copy`. The string itself is
122/// dropped at the boundary — embedded RMW callers cannot afford a
123/// thread-local error buffer.
124pub fn ret_from_error(err: &TransportError) -> NrosRmwRet {
125 match err {
126 TransportError::Timeout => NROS_RMW_RET_TIMEOUT,
127 TransportError::WouldBlock => NROS_RMW_RET_WOULD_BLOCK,
128 TransportError::TooLarge => NROS_RMW_RET_MESSAGE_TOO_LARGE,
129 TransportError::BufferTooSmall => NROS_RMW_RET_BUFFER_TOO_SMALL,
130 TransportError::MessageTooLarge => NROS_RMW_RET_MESSAGE_TOO_LARGE,
131 TransportError::InvalidArgument => NROS_RMW_RET_INVALID_ARGUMENT,
132 // Issue 0468 — InvalidConfig used to borrow INVALID_ARGUMENT, so a
133 // capacity the BUILD cannot honour arrived looking like a caller
134 // passing something wrong. It has its own code now.
135 TransportError::InvalidConfig => NROS_RMW_RET_INVALID_CONFIG,
136 TransportError::Unsupported => NROS_RMW_RET_UNSUPPORTED,
137 TransportError::BadAlloc => NROS_RMW_RET_BAD_ALLOC,
138 TransportError::IncompatibleQos(_) => NROS_RMW_RET_INCOMPATIBLE_QOS,
139 TransportError::TopicNameInvalid => NROS_RMW_RET_TOPIC_NAME_INVALID,
140 TransportError::NodeNameNonExistent => NROS_RMW_RET_NODE_NAME_NON_EXISTENT,
141 TransportError::LoanNotSupported => NROS_RMW_RET_LOAN_NOT_SUPPORTED,
142 TransportError::NoData => NROS_RMW_RET_NO_DATA,
143 TransportError::IncompatibleAbi => NROS_RMW_RET_INCOMPATIBLE_ABI,
144 TransportError::SessionLost => NROS_RMW_RET_SESSION_LOST,
145 // Phase 155.B.3 — distinguish wire-level connection failure
146 // from generic backend error so the FreeRTOS / RV64 C+C++
147 // `init -> -X` logs identify the actual class. zenoh-pico's
148 // `ZpicoError::Session` (zpico_open returned -3) and
149 // `ZpicoError::Generic` (zpico_init returned -1) both flow
150 // through `ZpicoError → ConnectionFailed`; the cmake-built
151 // FreeRTOS C/C++ tests will now surface NOT_FOUND (the
152 // user-side mapping in `rclc_support_init`) instead of the
153 // generic RCL_RET_ERROR catch-all.
154 TransportError::ConnectionFailed | TransportError::Disconnected => {
155 NROS_RMW_RET_CONNECTION_FAILED
156 }
157 // Everything else collapses to NROS_RMW_RET_ERROR. Backends
158 // that want fine-grained reporting should adopt the named
159 // variants above (Phase 102.2 sweep).
160 _ => NROS_RMW_RET_ERROR,
161 }
162}
163
164/// Map a `rmw_ret_t` returned by a C-side vtable function back to
165/// a `TransportError` for the Rust caller. Inverse of `ret_from_error`
166/// — used when `nros-rmw-cffi`'s `CffiSession` etc. receive a code
167/// from the registered C backend.
168///
169/// `NROS_RMW_RET_OK` is mapped to `TransportError::Backend("ok")` as a
170/// programming-error sentinel; callers should branch on the success
171/// path before calling this. Unknown negative codes collapse to the
172/// generic `TransportError::Backend("unknown rmw_ret_t")` so a future
173/// constant added to the C header degrades gracefully on the Rust side.
174pub fn error_from_ret(ret: NrosRmwRet) -> TransportError {
175 match ret {
176 NROS_RMW_RET_OK => {
177 TransportError::Backend("ok (logic error: positive ret_t at error site)")
178 }
179 NROS_RMW_RET_ERROR => TransportError::Backend("rmw_ret error"),
180 NROS_RMW_RET_TIMEOUT => TransportError::Timeout,
181 NROS_RMW_RET_BAD_ALLOC => TransportError::BadAlloc,
182 NROS_RMW_RET_INVALID_ARGUMENT => TransportError::InvalidArgument,
183 NROS_RMW_RET_INVALID_CONFIG => TransportError::InvalidConfig,
184 NROS_RMW_RET_UNSUPPORTED => TransportError::Unsupported,
185 // phase-417 G7 — `NONE`, and that is the honest answer rather than a
186 // default: `rmw_ret_t` is one integer, so a C backend's refusal
187 // crosses this boundary with no policy attached. `policy_name()`
188 // then reports `None` and the diagnostic says the backend named no
189 // policy, instead of naming one nobody identified.
190 NROS_RMW_RET_INCOMPATIBLE_QOS => {
191 TransportError::IncompatibleQos(nros_rmw::QoSPolicyMask::NONE)
192 }
193 NROS_RMW_RET_TOPIC_NAME_INVALID => TransportError::TopicNameInvalid,
194 NROS_RMW_RET_NODE_NAME_NON_EXISTENT => TransportError::NodeNameNonExistent,
195 NROS_RMW_RET_LOAN_NOT_SUPPORTED => TransportError::LoanNotSupported,
196 NROS_RMW_RET_NO_DATA => TransportError::NoData,
197 NROS_RMW_RET_WOULD_BLOCK => TransportError::WouldBlock,
198 NROS_RMW_RET_BUFFER_TOO_SMALL => TransportError::BufferTooSmall,
199 NROS_RMW_RET_MESSAGE_TOO_LARGE => TransportError::MessageTooLarge,
200 NROS_RMW_RET_INCOMPATIBLE_ABI => TransportError::IncompatibleAbi,
201 // Phase 155.B.3 — inverse of `ret_from_error`'s
202 // `ConnectionFailed | Disconnected → CONNECTION_FAILED`
203 // mapping. Decodes the new vtable-level code back to the
204 // `TransportError::ConnectionFailed` variant; downstream
205 // `transport_error_to_ret` in nros-c surfaces it as
206 // `RCLC_RET_NOT_FOUND` (-4) to the user.
207 NROS_RMW_RET_CONNECTION_FAILED => TransportError::ConnectionFailed,
208 NROS_RMW_RET_SESSION_LOST => TransportError::SessionLost,
209 _ => TransportError::Backend("unknown rmw_ret_t"),
210 }
211}
212
213// ============================================================================
214// Phase 102.3 / RFC-0054 — typed entity structs (defined in `generated`)
215// ============================================================================
216//
217// The `nros_rmw_*_t` structs live in `generated` (from
218// `<nros/rmw_entity.h>`); the `NrosRmw*` names are compat aliases.
219
220// The trait-level infinite spelling and the header's sentinel are the
221// same value by contract; a header edit that drifts one fails here.
222const _: () = assert!(nros_rmw::DURATION_INFINITE_MS as i64 == NROS_RMW_DURATION_INFINITE_MS);
223
224// The trait's gid width and the ABI header's are the same number by contract,
225// which is the whole point of the phase-467 RMW gap-closure design study's
226// Q1(a) — `Publisher::get_gid` hands its bytes straight into `rmw_gid_t::data`
227// and back, so a header edit that drifts one fails here rather than
228// truncating an identifier at the seam.
229const _: () = assert!(nros_rmw::PUBLISHER_GID_SIZE == RMW_GID_STORAGE_SIZE as usize);
230
231/// Compat alias for the generated `rmw_qos_profile_t`.
232pub type NrosRmwQos = rmw_qos_profile_t;
233/// Compat alias for the generated `rmw_gid_t`.
234pub type NrosRmwGid = rmw_gid_t;
235/// Compat alias for the generated `rmw_session_t`.
236pub type NrosRmwSession = rmw_session_t;
237/// Session creation options; NULL means every default.
238pub type NrosRmwSessionOptions = rmw_session_options_t;
239/// A graph node. The first argument of the four `create_*`
240/// slots, in place of the fabricated per-call session view they used to take.
241pub type NrosRmwNode = rmw_node_t;
242/// Compat alias for the generated `rmw_publisher_t`.
243pub type NrosRmwPublisher = rmw_publisher_t;
244/// Compat alias for the generated `rmw_subscription_t`.
245pub type NrosRmwSubscription = rmw_subscription_t;
246
247/// A vtable with every slot NULL — the base for struct-update syntax.
248///
249/// A vtable literal must name EVERY field, and this crate's
250/// tests build 26 of them. Adding a slot therefore meant adding one `None,`
251/// line to each, twenty-six times: tedious, and a place to miss one. The
252/// compiler catches a miss, but only after the diff has grown by the slot count
253/// times twenty-six. With this, a test names the slots it actually scripts and
254/// ends with `..EMPTY_VTABLE`, so a new slot costs one line in the header and
255/// nothing here.
256///
257/// Deliberately a `const` and not a `Default` impl: `Default` would make an
258/// all-NULL vtable constructible by accident, and an all-NULL vtable is exactly
259/// what `nros_rmw_cffi_register_named` must REFUSE. A const used
260/// explicitly as a literal's base cannot be reached that way.
261pub const EMPTY_VTABLE: NrosRmwVtable = NrosRmwVtable {
262 create_session: None,
263 destroy_session: None,
264 drive_io: None,
265 create_publisher: None,
266 destroy_publisher: None,
267 publish: None,
268 create_subscription: None,
269 destroy_subscription: None,
270 take: None,
271 has_data: None,
272 create_service: None,
273 destroy_service: None,
274 take_request: None,
275 has_request: None,
276 send_response: None,
277 create_client: None,
278 destroy_client: None,
279 send_request: None,
280 take_response: None,
281 subscription_event_init: None,
282 subscription_take_event: None,
283 publisher_take_event: None,
284 publisher_event_init: None,
285 publisher_assert_liveliness: None,
286 next_deadline_ms: None,
287 set_wake_callback: None,
288 borrow_loaned_message: None,
289 publish_loaned_message: None,
290 return_loaned_message_from_publisher: None,
291 take_loaned_message: None,
292 return_loaned_message_from_subscription: None,
293 service_server_is_available: None,
294 take_sequence: None,
295 publish_streamed: None,
296 ping_session: None,
297 subscription_supports_in_place: None,
298 process_raw_in_place: None,
299 get_implementation_identifier: None,
300 get_serialization_format: None,
301 feature_supported: None,
302 get_gid_for_publisher: None,
303 publisher_count_matched_subscriptions: None,
304 subscription_count_matched_publishers: None,
305 publisher_get_actual_qos: None,
306 subscription_get_actual_qos: None,
307 client_request_publisher_get_actual_qos: None,
308 client_response_subscription_get_actual_qos: None,
309 service_request_subscription_get_actual_qos: None,
310 service_response_publisher_get_actual_qos: None,
311 publisher_wait_for_all_acked: None,
312 take_with_info: None,
313 take_loaned_message_with_info: None,
314 get_node_names: None,
315 get_topic_names_and_types: None,
316 get_service_names_and_types: None,
317 get_publisher_names_and_types_by_node: None,
318 get_subscriber_names_and_types_by_node: None,
319 get_service_names_and_types_by_node: None,
320 get_client_names_and_types_by_node: None,
321 get_publishers_info_by_topic: None,
322 get_subscriptions_info_by_topic: None,
323 count_publishers: None,
324 count_subscribers: None,
325 node_get_graph_guard_condition: None,
326 create_node: None,
327 destroy_node: None,
328 set_log_severity: None,
329 supported_qos_policies: None,
330 subscription_set_on_new_message_callback: None,
331 service_set_on_new_request_callback: None,
332 client_set_on_new_response_callback: None,
333 count_clients: None,
334 count_services: None,
335 get_gid_for_client: None,
336 event_type_is_supported: None,
337 take_request_with_info: None,
338 take_response_with_info: None,
339 readiness_source: None,
340};
341
342/// Compat alias for the generated `rmw_service_t`.
343pub type NrosRmwService = rmw_service_t;
344/// Compat alias for the generated `rmw_client_t`.
345pub type NrosRmwClient = rmw_client_t;
346/// Compat alias for the generated `nros_rmw_vtable_t`.
347pub type NrosRmwVtable = nros_rmw_vtable_t;
348
349// The generated struct intentionally derives only Copy/Clone/Debug;
350// consumers (and the hand-written predecessor) compare QoS profiles.
351impl PartialEq for rmw_qos_profile_t {
352 fn eq(&self, other: &Self) -> bool {
353 self.reliability == other.reliability
354 && self.durability == other.durability
355 && self.history == other.history
356 && self.liveliness_kind == other.liveliness_kind
357 && self.depth == other.depth
358 && self.deadline_ms == other.deadline_ms
359 && self.lifespan_ms == other.lifespan_ms
360 && self.liveliness_lease_ms == other.liveliness_lease_ms
361 && self.avoid_ros_namespace_conventions == other.avoid_ros_namespace_conventions
362 }
363}
364impl Eq for rmw_qos_profile_t {}
365
366// The QoS profile constants below are `#define` struct-literal macros in the
367// C header; bindgen does not translate function-like/struct-literal macros,
368// so the Rust-side literals stay here (built from the generated types).
369//
370// Phase 376 W5/B2 — these used BARE INTEGERS with the policy name in a
371// trailing comment (`reliability: 1, // RELIABLE`). When the values took
372// upstream's numbering, every one of them kept compiling and started meaning a
373// different policy: `history: 0` went from KEEP_LAST to SYSTEM_DEFAULT and
374// `reliability: 0` from BEST_EFFORT to SYSTEM_DEFAULT. A comment is not a
375// binding. They name the generated constant now, so the next renumbering is a
376// compile error or nothing at all.
377//
378// issue 1256 / phase-454 W1 — and the DEPTHS now name the SSoT for the same
379// reason the policies name the generated enums. They were bare integers
380// (`depth: 10`, `depth: 5`, `depth: 1000`) with the upstream profile in a doc
381// comment above, which is the shape the paragraph above is about, one field
382// over. `QoSProfile::QOS_PROFILE_*` is the tree's one statement of what
383// upstream's profiles are (`nros-rmw/src/traits.rs`, gated field-by-field
384// against `docs/reference/rmw-qos-profiles.txt`), so these read it.
385
386/// The SSoT's depth, narrowed to the width the C ABI carries.
387///
388/// `as u16` would be a silent truncation, and `PARAMETERS` sits at 1000 — one
389/// decimal place from a value this ABI cannot hold. Const-evaluated, so a table
390/// depth past the ABI's reach is a COMPILE error at the profile that states it
391/// rather than a subscription silently created at `depth % 65536`. The same
392/// refusal `NrosRmwQos::try_from` makes at runtime (issue 0241), made where the
393/// value is a constant and the check therefore costs nothing.
394const fn abi_depth(depth: u32) -> u16 {
395 assert!(
396 depth <= u16::MAX as u32,
397 "a QoS profile states a history depth the RMW C ABI's u16 cannot carry",
398 );
399 depth as u16
400}
401
402/// Standard `rmw_qos_profile_default`-equivalent.
403pub const NROS_RMW_QOS_PROFILE_DEFAULT: NrosRmwQos = NrosRmwQos {
404 reliability: generated::NROS_RMW_RELIABILITY_RELIABLE as u8,
405 durability: generated::NROS_RMW_DURABILITY_VOLATILE as u8,
406 history: generated::NROS_RMW_HISTORY_KEEP_LAST as u8,
407 // SYSTEM_DEFAULT, not AUTOMATIC: upstream's `rmw_qos_profile_default`
408 // and `_sensor_data` both leave liveliness at the sentinel. Issue 0829
409 // corrected this on SYSTEM_DEFAULT and left the siblings; phase-428 W10.
410 liveliness_kind: rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_SYSTEM_DEFAULT as u8,
411 depth: abi_depth(nros_rmw::QoSProfile::QOS_PROFILE_DEFAULT.depth),
412 _reserved0: 0,
413 deadline_ms: 0,
414 lifespan_ms: 0,
415 liveliness_lease_ms: 0,
416 avoid_ros_namespace_conventions: 0,
417 _reserved1: [0; 3],
418};
419
420/// Standard `rmw_qos_profile_sensor_data`-equivalent.
421pub const NROS_RMW_QOS_PROFILE_SENSOR_DATA: NrosRmwQos = NrosRmwQos {
422 reliability: generated::NROS_RMW_RELIABILITY_BEST_EFFORT as u8,
423 durability: generated::NROS_RMW_DURABILITY_VOLATILE as u8,
424 history: generated::NROS_RMW_HISTORY_KEEP_LAST as u8,
425 // SYSTEM_DEFAULT, not AUTOMATIC: upstream's `rmw_qos_profile_default`
426 // and `_sensor_data` both leave liveliness at the sentinel. Issue 0829
427 // corrected this on SYSTEM_DEFAULT and left the siblings; phase-428 W10.
428 liveliness_kind: rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_SYSTEM_DEFAULT as u8,
429 depth: abi_depth(nros_rmw::QoSProfile::QOS_PROFILE_SENSOR_DATA.depth),
430 _reserved0: 0,
431 deadline_ms: 0,
432 lifespan_ms: 0,
433 liveliness_lease_ms: 0,
434 avoid_ros_namespace_conventions: 0,
435 _reserved1: [0; 3],
436};
437
438/// Standard `rmw_qos_profile_services_default`-equivalent.
439///
440/// Stated independently rather than aliased to `_DEFAULT`. Upstream states it
441/// as its own initialiser, and an alias makes a future divergence
442/// unrepresentable -- the two profiles happen to agree today, which is not the
443/// same as being the same profile.
444pub const NROS_RMW_QOS_PROFILE_SERVICES_DEFAULT: NrosRmwQos = NrosRmwQos {
445 ..NROS_RMW_QOS_PROFILE_DEFAULT
446};
447
448/// Standard `rmw_qos_profile_parameters`-equivalent.
449pub const NROS_RMW_QOS_PROFILE_PARAMETERS: NrosRmwQos = NrosRmwQos {
450 depth: abi_depth(nros_rmw::QoSProfile::QOS_PROFILE_PARAMETERS.depth),
451 ..NROS_RMW_QOS_PROFILE_DEFAULT
452};
453
454/// Standard `rmw_qos_profile_system_default`-equivalent — **all sentinel**.
455///
456/// This once aliased `_DEFAULT`, which said the
457/// constant carried no meaning of its own: `SYSTEM_DEFAULT` became a
458/// byte-for-byte synonym for a concrete reliable / volatile / keep-last(10)
459/// profile. Upstream's `rmw_qos_profile_system_default` names no concrete
460/// policy at all, and the RMW resolves the absence — differently per backend
461/// (`rmw_cyclonedds_cpp` → depth 1, `rmw_zenoh_cpp` → depth 42), which is why
462/// no baked number here could be right.
463///
464/// Every field is now zero, so this is also what a `memset` of the struct
465/// gives: the ABI stops having two answers for the same bytes. Mirrors
466/// `NROS_RMW_QOS_PROFILE_SYSTEM_DEFAULT` in `nros/rmw_entity.h`.
467pub const NROS_RMW_QOS_PROFILE_SYSTEM_DEFAULT: NrosRmwQos = NrosRmwQos {
468 reliability: generated::NROS_RMW_RELIABILITY_SYSTEM_DEFAULT as u8,
469 durability: generated::NROS_RMW_DURABILITY_SYSTEM_DEFAULT as u8,
470 history: generated::NROS_RMW_HISTORY_SYSTEM_DEFAULT as u8,
471 liveliness_kind: generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_SYSTEM_DEFAULT as u8,
472 depth: abi_depth(nros_rmw::QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT.depth),
473 _reserved0: 0,
474 deadline_ms: 0,
475 lifespan_ms: 0,
476 liveliness_lease_ms: 0,
477 avoid_ros_namespace_conventions: 0,
478 _reserved1: [0; 3],
479};
480
481// Phase-301 (issue 0241) — the QoS lowering is FALLIBLE: a depth the
482// C ABI's u16 cannot represent is a create-time error, never a silent
483// saturate. The duration fields are u32 ms on both sides (0 = unset,
484// `NROS_RMW_DURATION_INFINITE_MS` = explicit infinite) and pass
485// through unchanged; finer-grained callers lower via
486// `nros_rmw::duration_to_qos_ms` (sub-ms CEILs to 1 ms, past-u32
487// errors).
488impl TryFrom<QoSProfile> for NrosRmwQos {
489 type Error = TransportError;
490
491 fn try_from(qos: QoSProfile) -> Result<Self, TransportError> {
492 if qos.depth > u16::MAX as u32 {
493 return Err(TransportError::InvalidArgument);
494 }
495 Ok(Self {
496 // issue 0829 — the sentinel LOWERS; it is not resolved here.
497 // `NrosRmwQos` is what a C backend receives, and resolving the
498 // absence is that backend's job (cyclone answers depth 1, xrce
499 // leaves it for the Agent). Folding it to a concrete value on this
500 // side would hand every C backend the same answer and make the
501 // per-backend resolution unreachable.
502 reliability: match qos.reliability {
503 QoSReliabilityPolicy::SystemDefault => {
504 generated::NROS_RMW_RELIABILITY_SYSTEM_DEFAULT as u8
505 }
506 QoSReliabilityPolicy::BestEffort => {
507 generated::NROS_RMW_RELIABILITY_BEST_EFFORT as u8
508 }
509 QoSReliabilityPolicy::Reliable => generated::NROS_RMW_RELIABILITY_RELIABLE as u8,
510 // A read-back sentinel crossing back DOWN. `validate_against`
511 // refuses it as a request, so the only profile that reaches
512 // here carrying it is one the runtime built for a read-back
513 // OUT-parameter — which is exactly where it has to be legal.
514 QoSReliabilityPolicy::Unknown => generated::NROS_RMW_RELIABILITY_UNKNOWN as u8,
515 // issue 1973 — lowers faithfully; `CffiSession`'s create paths
516 // resolve it BEFORE this lowering, so a backend's create slot
517 // never receives it.
518 QoSReliabilityPolicy::BestAvailable => {
519 generated::NROS_RMW_RELIABILITY_BEST_AVAILABLE as u8
520 }
521 },
522 durability: match qos.durability {
523 QoSDurabilityPolicy::SystemDefault => {
524 generated::NROS_RMW_DURABILITY_SYSTEM_DEFAULT as u8
525 }
526 QoSDurabilityPolicy::Volatile => generated::NROS_RMW_DURABILITY_VOLATILE as u8,
527 QoSDurabilityPolicy::TransientLocal => {
528 generated::NROS_RMW_DURABILITY_TRANSIENT_LOCAL as u8
529 }
530 QoSDurabilityPolicy::Unknown => generated::NROS_RMW_DURABILITY_UNKNOWN as u8,
531 QoSDurabilityPolicy::BestAvailable => {
532 generated::NROS_RMW_DURABILITY_BEST_AVAILABLE as u8
533 }
534 },
535 history: match qos.history {
536 QoSHistoryPolicy::SystemDefault => generated::NROS_RMW_HISTORY_SYSTEM_DEFAULT as u8,
537 QoSHistoryPolicy::KeepLast => generated::NROS_RMW_HISTORY_KEEP_LAST as u8,
538 QoSHistoryPolicy::KeepAll => generated::NROS_RMW_HISTORY_KEEP_ALL as u8,
539 QoSHistoryPolicy::Unknown => generated::NROS_RMW_HISTORY_UNKNOWN as u8,
540 },
541 liveliness_kind: qos.liveliness_kind as u8,
542 depth: qos.depth as u16,
543 _reserved0: 0,
544 deadline_ms: qos.deadline_ms,
545 lifespan_ms: qos.lifespan_ms,
546 liveliness_lease_ms: qos.liveliness_lease_ms,
547 avoid_ros_namespace_conventions: qos.avoid_ros_namespace_conventions as u8,
548 _reserved1: [0; 3],
549 })
550 }
551}
552
553/// The inverse of [`TryFrom<QoSProfile> for NrosRmwQos`] — what a C backend
554/// ANSWERED, back in the vocabulary a Rust caller reasons in.
555///
556/// Infallible on purpose, and the reason is the `_ =>` arms: this reads a
557/// value a BACKEND wrote, and a backend that writes a discriminant this ABI
558/// does not define has told us nothing about that policy. `Unknown` is exactly
559/// that statement, so an unrecognised value degrades to "I cannot say" rather
560/// than to a confident wrong policy or to an error that would discard the four
561/// fields that WERE readable. `depth` widens (`u16` -> `u32`) and cannot lose.
562pub fn qos_from_c(q: &NrosRmwQos) -> QoSProfile {
563 QoSProfile {
564 reliability: match q.reliability as i32 {
565 NROS_RMW_RELIABILITY_SYSTEM_DEFAULT => QoSReliabilityPolicy::SystemDefault,
566 NROS_RMW_RELIABILITY_RELIABLE => QoSReliabilityPolicy::Reliable,
567 NROS_RMW_RELIABILITY_BEST_EFFORT => QoSReliabilityPolicy::BestEffort,
568 generated::NROS_RMW_RELIABILITY_BEST_AVAILABLE => QoSReliabilityPolicy::BestAvailable,
569 _ => QoSReliabilityPolicy::Unknown,
570 },
571 durability: match q.durability as i32 {
572 generated::NROS_RMW_DURABILITY_SYSTEM_DEFAULT => QoSDurabilityPolicy::SystemDefault,
573 generated::NROS_RMW_DURABILITY_VOLATILE => QoSDurabilityPolicy::Volatile,
574 generated::NROS_RMW_DURABILITY_TRANSIENT_LOCAL => QoSDurabilityPolicy::TransientLocal,
575 generated::NROS_RMW_DURABILITY_BEST_AVAILABLE => QoSDurabilityPolicy::BestAvailable,
576 _ => QoSDurabilityPolicy::Unknown,
577 },
578 history: match q.history as i32 {
579 generated::NROS_RMW_HISTORY_SYSTEM_DEFAULT => QoSHistoryPolicy::SystemDefault,
580 generated::NROS_RMW_HISTORY_KEEP_LAST => QoSHistoryPolicy::KeepLast,
581 generated::NROS_RMW_HISTORY_KEEP_ALL => QoSHistoryPolicy::KeepAll,
582 _ => QoSHistoryPolicy::Unknown,
583 },
584 liveliness_kind: match u32::from(q.liveliness_kind) {
585 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_SYSTEM_DEFAULT => {
586 QoSLivelinessPolicy::None
587 }
588 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_AUTOMATIC => {
589 QoSLivelinessPolicy::Automatic
590 }
591 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_MANUAL_BY_NODE => {
592 QoSLivelinessPolicy::ManualByNode
593 }
594 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_MANUAL_BY_TOPIC => {
595 QoSLivelinessPolicy::ManualByTopic
596 }
597 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_BEST_AVAILABLE => {
598 QoSLivelinessPolicy::BestAvailable
599 }
600 _ => QoSLivelinessPolicy::Unknown,
601 },
602 depth: u32::from(q.depth),
603 deadline_ms: q.deadline_ms,
604 lifespan_ms: q.lifespan_ms,
605 liveliness_lease_ms: q.liveliness_lease_ms,
606 avoid_ros_namespace_conventions: q.avoid_ros_namespace_conventions != 0,
607 // Not a DDS policy and not on the C QoS struct — a publisher-side
608 // transport hint (issue 0145). Nothing negotiates it, so a read-back
609 // has nothing to say about it and `false` is the struct's own default,
610 // not an answer.
611 tx_express: false,
612 }
613}
614
615// ============================================================================
616// Phase 108 / RFC-0054 — status-event types (defined in `generated`)
617// ============================================================================
618//
619// `rmw_event_type_t` is a module-consts alias (bindgen
620// `--default-enum-style=moduleconsts`), not a Rust enum, so the retired
621// `From` impls between it and `nros_rmw::EventKind` become plain functions.
622
623/// Compat alias for the generated `rmw_event_type_t::Type`
624/// (C-`unsigned`-sized event-kind discriminant).
625pub type NrosRmwEventKind = rmw_event_type_t::Type;
626/// Compat alias for the generated `rmw_liveliness_changed_status_t`.
627pub type NrosRmwLivelinessChangedStatus = rmw_liveliness_changed_status_t;
628/// Compat alias for the generated `rmw_count_status_t`.
629pub type NrosRmwCountStatus = rmw_count_status_t;
630/// Compat alias for the generated `rmw_event_payload_t` union.
631pub type NrosRmwEventPayload = rmw_event_payload_t;
632/// Compat alias for the generated `rmw_status_event_callback_t`
633/// (nullable — `Option`-wrapped fn pointer, per C ABI).
634pub type NrosRmwEventCallback = rmw_status_event_callback_t;
635
636/// Convert a trait-level [`nros_rmw::EventKind`] to the C ABI discriminant.
637/// Replaces the retired `From<nros_rmw::EventKind> for NrosRmwEventKind`.
638pub fn event_kind_to_c(k: nros_rmw::EventKind) -> NrosRmwEventKind {
639 use nros_rmw::EventKind as K;
640 use rmw_event_type_t as C;
641 match k {
642 K::LivelinessChanged => C::NROS_RMW_EVENT_LIVELINESS_CHANGED,
643 K::RequestedDeadlineMissed => C::NROS_RMW_EVENT_REQUESTED_DEADLINE_MISSED,
644 K::MessageLost => C::NROS_RMW_EVENT_MESSAGE_LOST,
645 K::LivelinessLost => C::NROS_RMW_EVENT_LIVELINESS_LOST,
646 K::OfferedDeadlineMissed => C::NROS_RMW_EVENT_OFFERED_DEADLINE_MISSED,
647 K::PublicationMatched => C::NROS_RMW_EVENT_PUBLICATION_MATCHED,
648 K::SubscriptionMatched => C::NROS_RMW_EVENT_SUBSCRIPTION_MATCHED,
649 K::PublisherIncompatibleType => C::NROS_RMW_EVENT_PUBLISHER_INCOMPATIBLE_TYPE,
650 K::SubscriptionIncompatibleType => C::NROS_RMW_EVENT_SUBSCRIPTION_INCOMPATIBLE_TYPE,
651 // unreachable for now (#[non_exhaustive])
652 _ => C::NROS_RMW_EVENT_MESSAGE_LOST,
653 }
654}
655
656/// Convert a C ABI event-kind discriminant to the trait-level
657/// [`nros_rmw::EventKind`]. Replaces the retired
658/// `From<NrosRmwEventKind> for nros_rmw::EventKind`. Unknown values map to
659/// `MessageLost`, mirroring the forward direction's fallback.
660pub fn event_kind_from_c(k: NrosRmwEventKind) -> nros_rmw::EventKind {
661 use nros_rmw::EventKind as K;
662 use rmw_event_type_t as C;
663 match k {
664 C::NROS_RMW_EVENT_LIVELINESS_CHANGED => K::LivelinessChanged,
665 C::NROS_RMW_EVENT_REQUESTED_DEADLINE_MISSED => K::RequestedDeadlineMissed,
666 C::NROS_RMW_EVENT_MESSAGE_LOST => K::MessageLost,
667 C::NROS_RMW_EVENT_LIVELINESS_LOST => K::LivelinessLost,
668 C::NROS_RMW_EVENT_OFFERED_DEADLINE_MISSED => K::OfferedDeadlineMissed,
669 C::NROS_RMW_EVENT_PUBLICATION_MATCHED => K::PublicationMatched,
670 C::NROS_RMW_EVENT_SUBSCRIPTION_MATCHED => K::SubscriptionMatched,
671 C::NROS_RMW_EVENT_PUBLISHER_INCOMPATIBLE_TYPE => K::PublisherIncompatibleType,
672 C::NROS_RMW_EVENT_SUBSCRIPTION_INCOMPATIBLE_TYPE => K::SubscriptionIncompatibleType,
673 _ => K::MessageLost,
674 }
675}
676
677// ============================================================================
678// Issue 1164 — the runtime is the caller of `*_take_event`
679// ============================================================================
680//
681// The status-event surface has two halves in the C ABI and a backend fills
682// exactly one of them (`rmw_vtable.h`, "how the three upstream parts map
683// here"):
684//
685// * `*_event_init` — the backend has a safe context and will CALL you.
686// `rust_adapter` fills this for every Rust backend, so zenoh arrives here.
687// * `*_take_event` — the backend has NOWHERE safe to deliver from, so it
688// buffers nothing and lets the caller drain its counters. cyclonedds fills
689// this one, and `subscriber.cpp` says what it expects of us in as many
690// words: "A caller polls them the way it already polls `has_data`."
691//
692// Nothing polled them. Both cyclonedds slots were implemented, read real
693// `dds_get_*_status` counters, and had no caller anywhere outside the
694// backend's own C++ test — so a Cyclone application could not observe a status
695// event through either half (issue 1164).
696//
697// This is that caller. It deliberately does NOT add a second user-facing
698// shape: `Subscription::register_event_callback` stays the one way to ask for
699// an event, and when the backend leaves `*_event_init` NULL the registration
700// is recorded HERE and satisfied by polling `*_take_event` from the entity's
701// ordinary data path. That is exactly how zenoh already behaves one layer
702// down — its shim fires registered callbacks from `has_data` / `take_serialized`
703// and from `publish_raw` — so an application sees the same API and the same
704// delivery points on either backend.
705//
706// **Deadline caveat.** `deadline_ms` is not forwarded on the poll path: there
707// is no slot to forward it to. A backend reached this way derives the deadline
708// from the entity's QoS (`qos.deadline_ms` at create time), so
709// `on_requested_deadline_missed(d)` observes the QoS deadline, not `d`. Ask
710// for the deadline in the QoS profile when the backend is a polled one.
711
712/// One status-event callback the runtime holds on the entity's behalf,
713/// because the backend filled `*_take_event` instead of `*_event_init`.
714///
715/// `cb` is the C callback `*_event_init` would have received, unwrapped —
716/// a NULL one is refused at registration. Non-`Option` so the fn pointer's
717/// niche makes `Option<PolledEventReg>` 16 bytes rather than 24: issue 1972
718/// grew the per-entity registry to five kinds, and the entity struct is
719/// budgeted against `PUBSUB_STRUCT` in every image's executor arena.
720/// `user_ctx` is owned by whoever registered (`nros-node` keeps the boxed
721/// closure alive for the entity's lifetime).
722#[derive(Clone, Copy)]
723struct PolledEventReg {
724 cb: unsafe extern "C" fn(NrosRmwEventKind, *const NrosRmwEventPayload, *mut c_void),
725 user_ctx: *mut c_void,
726}
727
728/// Subscription-side event kinds, in registry-slot order.
729const SUB_EVENT_KINDS: [nros_rmw::EventKind; 5] = [
730 nros_rmw::EventKind::LivelinessChanged,
731 nros_rmw::EventKind::RequestedDeadlineMissed,
732 nros_rmw::EventKind::MessageLost,
733 // Issue 1972.
734 nros_rmw::EventKind::SubscriptionMatched,
735 nros_rmw::EventKind::SubscriptionIncompatibleType,
736];
737
738/// Publisher-side event kinds, in registry-slot order.
739const PUB_EVENT_KINDS: [nros_rmw::EventKind; 4] = [
740 nros_rmw::EventKind::LivelinessLost,
741 nros_rmw::EventKind::OfferedDeadlineMissed,
742 // Issue 1972.
743 nros_rmw::EventKind::PublicationMatched,
744 nros_rmw::EventKind::PublisherIncompatibleType,
745];
746
747/// Registry slot for a subscription-side kind. `None` for a publisher-side
748/// kind, which is a caller error rather than an unsupported capability — the
749/// backends answer it `INVALID_ARGUMENT` for the same reason.
750fn sub_event_slot(kind: nros_rmw::EventKind) -> Option<usize> {
751 SUB_EVENT_KINDS.iter().position(|k| *k == kind)
752}
753
754/// Registry slot for a publisher-side kind. See [`sub_event_slot`].
755fn pub_event_slot(kind: nros_rmw::EventKind) -> Option<usize> {
756 PUB_EVENT_KINDS.iter().position(|k| *k == kind)
757}
758
759/// THE one answer to "can this backend carry event `kind`?",
760/// for every caller behind the C ABI: the per-entity
761/// `supports_event` of [`CffiPublisher`] and [`CffiSubscription`] both ask
762/// it, so the per-entity answer can never claim a kind the backend-level
763/// `event_type_is_supported` slot denies.
764///
765/// A kind is supported when the backend has an event PATH for its side
766/// (`*_event_init` callback or `*_take_event` poll) AND, where
767/// the backend fills `event_type_is_supported`, that slot says yes. A NULL
768/// `event_type_is_supported` falls back to the path alone — slot
769/// granularity, which was the whole answer before the slot existed and is
770/// still the honest one for a backend that states nothing per kind.
771pub fn backend_event_type_is_supported(vtable: &NrosRmwVtable, kind: nros_rmw::EventKind) -> bool {
772 let has_path = if sub_event_slot(kind).is_some() {
773 vtable.subscription_event_init.is_some() || vtable.subscription_take_event.is_some()
774 } else if pub_event_slot(kind).is_some() {
775 vtable.publisher_event_init.is_some() || vtable.publisher_take_event.is_some()
776 } else {
777 false
778 };
779 if !has_path {
780 return false;
781 }
782 match vtable.event_type_is_supported {
783 // SAFETY: a plain value argument; the slot takes no pointers.
784 Some(f) => unsafe { f(event_kind_to_c(kind)) },
785 None => true,
786 }
787}
788
789/// A payload union with no member selected yet. The backend writes one of the
790/// two members before setting `taken`; we never read it unless it did.
791fn empty_event_payload() -> NrosRmwEventPayload {
792 NrosRmwEventPayload {
793 count: NrosRmwCountStatus {
794 total_count: 0,
795 total_count_change: 0,
796 },
797 }
798}
799
800// ============================================================================
801// Registration
802// ============================================================================
803//
804// Phase 104.B.2 — named registry replaces the singleton vtable.
805// Backends register under a stable identifier (`"zenoh"`, `"dds"`,
806// `"xrce"`, future `"uorb"`, `"cyclonedds"`); consumers look up
807// vtables by name via `nros_rmw_cffi_lookup`. Multiple backends can
808// coexist in the same process (bridge nodes).
809//
810// Capacity comes from the `NROS_RMW_MAX_BACKENDS` build-time env
811// var (default 8). See `build.rs`.
812//
813// Implementation: a fixed-size `[BackendSlot; MAX_BACKENDS]`
814// guarded by an atomic length counter. No alloc; `no_std`
815// compatible. Slot scan is O(N) for lookup but N is tiny (8 by
816// default). Each slot owns its name buffer; `name_ptr` returned
817// to consumers points into the slot and stays valid for the
818// program's lifetime.
819
820/// Compile-time max number of concurrently registered backends.
821/// Set via `NROS_RMW_MAX_BACKENDS` env var at build time
822/// (`build.rs`). Default 8.
823pub const MAX_BACKENDS: usize = parse_max_backends(env!("NROS_RMW_MAX_BACKENDS"));
824
825/// How many of [`MAX_BACKENDS`] the image DECLARED: its own
826/// backends, before the recorder's slot (`recorder-slot`) is added beside
827/// them. Equal to `MAX_BACKENDS` in an image that links no recorder.
828pub const DECLARED_BACKENDS: usize = parse_max_backends(env!("NROS_RMW_DECLARED_BACKENDS"));
829
830/// Whether this registry reserves a slot for the recording
831/// backend, i.e. whether `nros-rmw-metadata` is linked.
832pub const RECORDER_SLOT: bool = cfg!(feature = "recorder-slot");
833
834const fn parse_max_backends(s: &str) -> usize {
835 parse_env_usize(s, "NROS_RMW_MAX_BACKENDS must be a decimal integer")
836}
837
838/// Const decimal parser for build.rs-emitted envs (`MAX_BACKENDS`,
839/// `NROS_RMW_SUBSCRIBER_SLOTS`).
840pub(crate) const fn parse_env_usize(s: &str, msg: &str) -> usize {
841 let bytes = s.as_bytes();
842 let mut i = 0usize;
843 let mut acc: usize = 0;
844 while i < bytes.len() {
845 let d = bytes[i];
846 if !d.is_ascii_digit() {
847 let _ = msg;
848 panic!("nros-rmw-cffi: build-time env must be a decimal integer");
849 }
850 acc = acc * 10 + (d - b'0') as usize;
851 i += 1;
852 }
853 acc
854}
855
856/// Maximum length of a backend name. Names are short ASCII
857/// identifiers (`"zenoh"`, `"cyclonedds"`); 32 bytes is generous.
858const BACKEND_NAME_MAX: usize = 32;
859
860#[repr(C)]
861struct BackendSlot {
862 /// Null-terminated UTF-8 backend name. Zero-initialized when
863 /// unused (`name[0] == 0`).
864 name: [u8; BACKEND_NAME_MAX],
865 vtable: *const NrosRmwVtable,
866}
867
868impl BackendSlot {
869 const fn empty() -> Self {
870 Self {
871 name: [0u8; BACKEND_NAME_MAX],
872 vtable: core::ptr::null(),
873 }
874 }
875
876 #[inline]
877 fn is_empty(&self) -> bool {
878 self.name[0] == 0
879 }
880
881 #[inline]
882 fn name_matches(&self, candidate: &[u8]) -> bool {
883 if self.is_empty() {
884 return false;
885 }
886 // Compare up to the first NUL or candidate length.
887 let mut i = 0usize;
888 while i < self.name.len() && i < candidate.len() {
889 if self.name[i] == 0 {
890 return false; // slot name shorter than candidate
891 }
892 if self.name[i] != candidate[i] {
893 return false;
894 }
895 i += 1;
896 }
897 // candidate fully consumed; slot must be NUL at i (same length)
898 i == candidate.len() && (i == self.name.len() || self.name[i] == 0)
899 }
900}
901
902// SAFETY: `BackendSlot::vtable` is a `*const` pointer used in a
903// `'static` context; once written it's never freed and the registry
904// is guarded by an atomic length counter for publication. Marker
905// trait implementations are required so the static array is
906// `Sync` across threads.
907unsafe impl Sync for BackendSlot {}
908
909/// Fixed-size registry. `slots[0..len]` are live; `slots[len..]`
910/// are zero-initialized. `len` is the publication fence.
911///
912/// `slots` lives in an `UnsafeCell` because we mutate through
913/// `&'static REGISTRY`. Safety invariants:
914/// * Slot writes happen only inside `nros_rmw_cffi_register_named`,
915/// which is documented "call before `Executor::open`" — backend
916/// ctors fire pre-main, manual calls precede session creation.
917/// * Slot reads via `nros_rmw_cffi_lookup` and `get_vtable` happen
918/// after `Executor::open`, well after registration completes.
919/// * The atomic `len` provides the release-acquire fence so any
920/// reader that sees `len = N` also sees the populated slot
921/// contents for indices `< N`.
922#[doc(hidden)]
923pub struct Registry {
924 slots: core::cell::UnsafeCell<[BackendSlot; MAX_BACKENDS]>,
925 len: portable_atomic::AtomicUsize,
926}
927
928impl Registry {
929 #[doc(hidden)]
930 pub const fn new() -> Self {
931 let slots = {
932 #[allow(clippy::declare_interior_mutable_const)]
933 const E: BackendSlot = BackendSlot::empty();
934 [E; MAX_BACKENDS]
935 };
936 Self {
937 slots: core::cell::UnsafeCell::new(slots),
938 len: portable_atomic::AtomicUsize::new(0),
939 }
940 }
941
942 /// Borrow slot `i` immutably. Caller must guarantee
943 /// `i < self.len.load(Acquire)`.
944 #[inline]
945 unsafe fn slot(&self, i: usize) -> &BackendSlot {
946 // SAFETY: registry protocol guarantees slot stability once
947 // published via the atomic len fence.
948 unsafe { &(*self.slots.get())[i] }
949 }
950
951 /// Borrow slot `i` mutably. Caller must guarantee exclusive
952 /// access — either pre-publication (idx > current `len`) or
953 /// during an idempotent overwrite of an already-registered name.
954 #[inline]
955 #[allow(clippy::mut_from_ref)]
956 unsafe fn slot_mut(&self, i: usize) -> &mut BackendSlot {
957 // SAFETY: see Registry doc — writer-side discipline.
958 unsafe { &mut (*self.slots.get())[i] }
959 }
960}
961
962// SAFETY: see `Registry` doc-comment on the mutation protocol.
963unsafe impl Sync for Registry {}
964
965// Phase 241.D3-rev — `REGISTRY` is DEFINED once in this rlib (plain
966// `#[no_mangle]`). The single-runtime model puts exactly one Rust staticlib in any
967// link (the umbrella `nros-c` / `nros-cpp` bundles the backend as an rlib), so the
968// cffi rlib appears once and one strong definition is correct everywhere: pure-Rust
969// firmware, the NuttX build-std ELF, and the umbrella C/C++ staticlib alike. This
970// supersedes the slice-4 `external-registry`/provider split, which existed only
971// because the C/C++ link used to carry multiple Rust staticlibs.
972#[unsafe(no_mangle)]
973static REGISTRY: Registry = Registry::new();
974
975/// The single process-wide backend registry.
976#[inline]
977fn registry() -> &'static Registry {
978 ®ISTRY
979}
980
981// ============================================================================
982// Rust-adapter MessageInfo side channel
983// ============================================================================
984//
985// The stable C subscriber ABI returns only a `(payload, len)` pair from
986// `take_serialized`. Rust backends can produce `MessageInfo`, so the generic
987// Rust->C adapter stores that metadata keyed by the backend handle pointer
988// immediately before returning the payload length. The Rust CFFI subscriber
989// consumes it after the vtable call. Pure C/C++ backends never write this table
990// and keep the documented `None` metadata behavior.
991
992/// Issue 0271 — build-time configurable via `NROS_RMW_MESSAGE_INFO_SLOTS`
993/// (default 64). Under-sizing costs metadata, not correctness: a subscriber
994/// that finds no free slot reads back `None` for `MessageInfo`, which is the
995/// documented behaviour for backends that never populate the table at all.
996const MESSAGE_INFO_SLOTS: usize = crate::parse_env_usize(
997 env!("NROS_RMW_MESSAGE_INFO_SLOTS"),
998 "NROS_RMW_MESSAGE_INFO_SLOTS must be a decimal integer",
999);
1000
1001struct MessageInfoSlot {
1002 key: portable_atomic::AtomicUsize,
1003 valid: portable_atomic::AtomicBool,
1004 /// Issue 1942 — for a SERVICE key, which [`ServiceRequestInfo`] fields
1005 /// `info` carries (`SERVICE_INFO_HAS_*`). Zero for a subscription. Sits in
1006 /// the padding `valid` already leaves before `info`, so the slot — whose
1007 /// width is issue 0271's footprint concern — does not grow.
1008 service_presence: portable_atomic::AtomicU8,
1009 info: UnsafeCell<MessageInfo>,
1010 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1011 validate_requested: portable_atomic::AtomicBool,
1012 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1013 integrity_valid: portable_atomic::AtomicBool,
1014 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1015 integrity: UnsafeCell<nros_rmw::IntegrityStatus>,
1016}
1017
1018impl MessageInfoSlot {
1019 const fn empty() -> Self {
1020 Self {
1021 key: portable_atomic::AtomicUsize::new(0),
1022 valid: portable_atomic::AtomicBool::new(false),
1023 service_presence: portable_atomic::AtomicU8::new(0),
1024 info: UnsafeCell::new(MessageInfo::new()),
1025 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1026 validate_requested: portable_atomic::AtomicBool::new(false),
1027 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1028 integrity_valid: portable_atomic::AtomicBool::new(false),
1029 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1030 integrity: UnsafeCell::new(nros_rmw::IntegrityStatus {
1031 gap: 0,
1032 duplicate: false,
1033 crc_valid: None,
1034 }),
1035 }
1036 }
1037}
1038
1039// SAFETY: each slot is published by `key` and `valid` atomics. Writers store
1040// `info` before setting `valid = true` with Release ordering; readers take
1041// `valid` with AcqRel before copying the `MessageInfo`.
1042unsafe impl Sync for MessageInfoSlot {}
1043
1044// issue 0739 — deliberately NOT annotated with a `// nros-pool:` formula.
1045// `MessageInfoSlot`'s width depends on cfg (`alloc` + `safety-e2e` add three
1046// more fields), so any constant here would be right for one build and wrong for
1047// the rest. Issue 0271 measured 3,584 bytes at 64 slots in ITS configuration;
1048// stating that as the cost would be the fabrication the inventory exists to
1049// avoid. The knob still appears in the table with its default — the table says
1050// "no byte figure", which is true, rather than implying it is free.
1051static MESSAGE_INFO_TABLE: [MessageInfoSlot; MESSAGE_INFO_SLOTS] = {
1052 #[allow(clippy::declare_interior_mutable_const)]
1053 const E: MessageInfoSlot = MessageInfoSlot::empty();
1054 [E; MESSAGE_INFO_SLOTS]
1055};
1056
1057fn lookup_message_info_slot(key: usize) -> Option<&'static MessageInfoSlot> {
1058 if key == 0 {
1059 return None;
1060 }
1061 MESSAGE_INFO_TABLE
1062 .iter()
1063 .find(|slot| slot.key.load(Ordering::Acquire) == key)
1064}
1065
1066#[cfg(feature = "alloc")]
1067fn get_or_insert_message_info_slot(key: usize) -> Option<&'static MessageInfoSlot> {
1068 if key == 0 {
1069 return None;
1070 }
1071 for slot in &MESSAGE_INFO_TABLE {
1072 let current = slot.key.load(Ordering::Acquire);
1073 if current == key {
1074 return Some(slot);
1075 }
1076 if current == 0
1077 && slot
1078 .key
1079 .compare_exchange(0, key, Ordering::AcqRel, Ordering::Acquire)
1080 .is_ok()
1081 {
1082 return Some(slot);
1083 }
1084 }
1085 None
1086}
1087
1088#[cfg(feature = "alloc")]
1089pub(crate) fn store_cffi_message_info(key: usize, info: Option<MessageInfo>) {
1090 let Some(slot) = get_or_insert_message_info_slot(key) else {
1091 return;
1092 };
1093 match info {
1094 Some(info) => {
1095 // SAFETY: this slot is keyed to one subscriber backend handle. The
1096 // executor owns each subscriber mutably while receiving, so writes
1097 // for the same key are serialized.
1098 unsafe {
1099 *slot.info.get() = info;
1100 }
1101 slot.valid.store(true, Ordering::Release);
1102 }
1103 None => slot.valid.store(false, Ordering::Release),
1104 }
1105}
1106
1107fn take_cffi_message_info(key: usize) -> Option<MessageInfo> {
1108 let slot = lookup_message_info_slot(key)?;
1109 if !slot.valid.swap(false, Ordering::AcqRel) {
1110 return None;
1111 }
1112 // SAFETY: `valid.swap(false)` gives this reader exclusive consumption of the
1113 // last stored `MessageInfo` for this key.
1114 Some(unsafe { *slot.info.get() })
1115}
1116
1117// Issue 1942 — the SERVICE half of the side channel.
1118//
1119// The C `take_request` slot carries only the reply-correlation token, so a
1120// Rust backend's per-request [`ServiceRequestInfo`] crosses the adapter the way
1121// its subscription `MessageInfo` does: stored by the adapter, keyed by the
1122// service's backend handle, right before the take returns, and taken by
1123// `CffiService` right after. It reuses the subscription table rather than
1124// adding a second pool (and a second knob): the keys are handle pointers, so a
1125// service and a subscription never share one, and
1126// `NROS_RMW_MESSAGE_INFO_SLOTS` now bounds both — a slot found full costs
1127// metadata (`NOT_REPORTED`), never correctness, as before.
1128//
1129// Encoding, lossless: the timestamps go in their `MessageInfo` namesakes, the
1130// client sequence number in `publication_sequence_number`, the 16-byte writer
1131// GUID in the first 16 bytes of `publisher_gid`, and which fields are PRESENT
1132// in `service_presence`, so an absent field reads back `None` and never as a
1133// zero.
1134
1135const SERVICE_INFO_HAS_SOURCE: u8 = 1 << 0;
1136const SERVICE_INFO_HAS_RECEIVED: u8 = 1 << 1;
1137const SERVICE_INFO_HAS_REQUEST_ID: u8 = 1 << 2;
1138
1139#[cfg(feature = "alloc")]
1140pub(crate) fn store_cffi_service_info(key: usize, info: ServiceRequestInfo) {
1141 if !info.is_reported() {
1142 // Nothing to say: invalidate what an earlier request left, and do not
1143 // claim a slot for a backend that never reports.
1144 if let Some(slot) = lookup_message_info_slot(key) {
1145 slot.valid.store(false, Ordering::Release);
1146 }
1147 return;
1148 }
1149 let Some(slot) = get_or_insert_message_info_slot(key) else {
1150 return;
1151 };
1152 let mut packed = MessageInfo::new();
1153 let mut presence = 0u8;
1154 if let Some(ts) = info.source_timestamp {
1155 packed.set_source_timestamp(ts);
1156 presence |= SERVICE_INFO_HAS_SOURCE;
1157 }
1158 if let Some(ts) = info.received_timestamp {
1159 packed.set_received_timestamp(ts);
1160 presence |= SERVICE_INFO_HAS_RECEIVED;
1161 }
1162 if let Some(id) = info.request_id {
1163 packed.set_publication_sequence_number(id.sequence_number);
1164 packed.set_publisher_gid(nros_rmw::pad_publisher_gid(&id.writer_guid));
1165 presence |= SERVICE_INFO_HAS_REQUEST_ID;
1166 }
1167 // SAFETY: keyed to one service backend handle, which the executor owns
1168 // mutably while taking — the same serialisation `store_cffi_message_info`
1169 // relies on.
1170 unsafe {
1171 *slot.info.get() = packed;
1172 }
1173 slot.service_presence.store(presence, Ordering::Relaxed);
1174 slot.valid.store(true, Ordering::Release);
1175}
1176
1177fn take_cffi_service_info(key: usize) -> ServiceRequestInfo {
1178 let Some(slot) = lookup_message_info_slot(key) else {
1179 return ServiceRequestInfo::NOT_REPORTED;
1180 };
1181 if !slot.valid.swap(false, Ordering::AcqRel) {
1182 return ServiceRequestInfo::NOT_REPORTED;
1183 }
1184 let presence = slot.service_presence.load(Ordering::Relaxed);
1185 // SAFETY: `valid.swap(false)` gives this reader exclusive consumption.
1186 let packed = unsafe { *slot.info.get() };
1187 let mut writer_guid = [0u8; REQUEST_WRITER_GUID_SIZE];
1188 writer_guid.copy_from_slice(&packed.publisher_gid()[..REQUEST_WRITER_GUID_SIZE]);
1189 ServiceRequestInfo {
1190 source_timestamp: (presence & SERVICE_INFO_HAS_SOURCE != 0)
1191 .then(|| packed.source_timestamp()),
1192 received_timestamp: (presence & SERVICE_INFO_HAS_RECEIVED != 0)
1193 .then(|| packed.received_timestamp()),
1194 request_id: (presence & SERVICE_INFO_HAS_REQUEST_ID != 0).then(|| RequestId {
1195 writer_guid,
1196 sequence_number: packed.publication_sequence_number(),
1197 }),
1198 }
1199}
1200
1201#[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1202fn request_cffi_integrity_status(key: usize) {
1203 let Some(slot) = get_or_insert_message_info_slot(key) else {
1204 return;
1205 };
1206 slot.integrity_valid.store(false, Ordering::Release);
1207 slot.validate_requested.store(true, Ordering::Release);
1208}
1209
1210#[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1211pub(crate) fn take_cffi_integrity_request(key: usize) -> bool {
1212 lookup_message_info_slot(key)
1213 .map(|slot| slot.validate_requested.swap(false, Ordering::AcqRel))
1214 .unwrap_or(false)
1215}
1216
1217#[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1218pub(crate) fn store_cffi_integrity_status(key: usize, status: nros_rmw::IntegrityStatus) {
1219 let Some(slot) = get_or_insert_message_info_slot(key) else {
1220 return;
1221 };
1222 // SAFETY: integrity status follows the same per-subscriber handoff as
1223 // `info`; the CFFI subscriber owns receive calls mutably for this key.
1224 unsafe {
1225 *slot.integrity.get() = status;
1226 }
1227 slot.integrity_valid.store(true, Ordering::Release);
1228}
1229
1230#[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1231fn take_cffi_integrity_status(key: usize) -> Option<nros_rmw::IntegrityStatus> {
1232 let slot = lookup_message_info_slot(key)?;
1233 if !slot.integrity_valid.swap(false, Ordering::AcqRel) {
1234 return None;
1235 }
1236 Some(unsafe { *slot.integrity.get() })
1237}
1238
1239fn clear_cffi_message_info(key: usize) {
1240 let Some(slot) = lookup_message_info_slot(key) else {
1241 return;
1242 };
1243 slot.valid.store(false, Ordering::Release);
1244 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
1245 {
1246 slot.validate_requested.store(false, Ordering::Release);
1247 slot.integrity_valid.store(false, Ordering::Release);
1248 }
1249 slot.key.store(0, Ordering::Release);
1250}
1251
1252/// Issue 0332 — a vtable slot the runtime `.expect()`s on the hot path is
1253/// mandatory: a `None` there is a panic mid-spin, on a no_std target, the worst
1254/// place to discover an incomplete backend. Returns the name of the first
1255/// missing slot so registration can reject such a vtable loudly and early.
1256///
1257/// Issue 0349 — the list is CORE TRANSPORT only. It originally also required
1258/// `publisher_event_init`, `subscription_event_init` and
1259/// `publisher_assert_liveliness` (then `register_*_event` / ~~`assert_publisher_liveliness`~~),
1260/// which refused the **xrce backend outright**:
1261/// its vtable NULLs all three deliberately, alongside ~14 other optional
1262/// capability slots this list correctly never required, so
1263/// `nros_rmw_xrce_register()` returned INVALID_ARGUMENT and xrce could not
1264/// register at all.
1265///
1266/// Those three are QoS-event and liveliness CAPABILITIES, not transport — and
1267/// the slots are `Option<fn>` precisely because C nullability encodes "not
1268/// provided" (RFC-0054). Requiring a slot whose type says it is optional was
1269/// the contradiction. ~~`assert_publisher_liveliness`~~' own dispatch site had
1270/// documented "NULL function pointer = backend doesn't support manual
1271/// liveliness" the whole time, while the code `.expect()`ed it.
1272///
1273/// The three now report `TransportError::Unsupported` when used and absent.
1274/// That is the refinement this function's doc used to defer — the difference
1275/// between an optional slot and a missing required one is that the optional one
1276/// has a typed error at the point of use, which is exactly what makes dropping
1277/// it from this list safe.
1278fn first_missing_vtable_slot(v: &NrosRmwVtable) -> Option<&'static str> {
1279 macro_rules! require {
1280 ($($slot:ident),+ $(,)?) => {
1281 $( if v.$slot.is_none() { return Some(stringify!($slot)); } )+
1282 };
1283 }
1284 require!(
1285 create_session,
1286 destroy_session,
1287 create_publisher,
1288 destroy_publisher,
1289 create_subscription,
1290 destroy_subscription,
1291 publish,
1292 drive_io,
1293 has_data,
1294 take,
1295 create_service,
1296 destroy_service,
1297 create_client,
1298 destroy_client,
1299 send_response,
1300 has_request,
1301 take_request,
1302 );
1303 // NOT required (issue 0349) — optional capabilities with a typed
1304 // `Unsupported` error at the point of use, exactly like the ~14 other
1305 // nullable slots (`borrow_loaned_message`, `take_loaned_message`, `next_deadline_ms`,
1306 // `service_server_is_available`, …) this list has always allowed to be NULL:
1307 // publisher_event_init, subscription_event_init,
1308 // assert_publisher_liveliness
1309 None
1310}
1311
1312/// Register a backend under a stable name. Multiple backends can
1313/// coexist; consumers select via [`nros_rmw_cffi_lookup`] or the
1314/// higher-level `Executor::node_builder(...).rmw(...)` path.
1315///
1316/// Names must be UTF-8, NUL-terminated, ≤ 31 bytes (excluding NUL).
1317/// Reserved names today: `"zenoh"`, `"dds"`, `"xrce"`,
1318/// `"cyclonedds"`, future `"uorb"`. (`"default"` was the implicit name of
1319/// the unnamed single-argument form, since deleted.)
1320///
1321/// Returns:
1322/// * `NROS_RMW_RET_OK` on success.
1323/// * `NROS_RMW_RET_INVALID_ARGUMENT` if `name` / `vtable` is
1324/// NULL, the name is empty, or exceeds 31 bytes.
1325/// * `NROS_RMW_RET_ERROR` if the registry is full
1326/// (`MAX_BACKENDS` reached without a matching entry).
1327///
1328/// Duplicate registration of the same name overwrites the
1329/// previous vtable (idempotent for ctor-fires-twice cases).
1330///
1331/// # Safety
1332///
1333/// * `name` must be a valid NUL-terminated UTF-8 string.
1334/// * `vtable` must remain valid for the program's lifetime.
1335#[unsafe(no_mangle)]
1336pub unsafe extern "C" fn nros_rmw_cffi_register_named(
1337 name: *const core::ffi::c_char,
1338 vtable: *const NrosRmwVtable,
1339) -> NrosRmwRet {
1340 if name.is_null() || vtable.is_null() {
1341 return NROS_RMW_RET_INVALID_ARGUMENT;
1342 }
1343
1344 // Issue 0332 — reject an incomplete vtable at registration rather than
1345 // panicking mid-spin. SAFETY: `vtable` is non-null (checked) and the caller
1346 // guarantees it is valid for the program's lifetime (see `# Safety`).
1347 if let Some(missing) = first_missing_vtable_slot(unsafe { &*vtable }) {
1348 let _ = missing; // named for debuggers; INVALID_ARGUMENT is the ABI signal
1349 return NROS_RMW_RET_INVALID_ARGUMENT;
1350 }
1351
1352 let name_u8 = name.cast::<u8>();
1353
1354 // Length-check the input. We scan up to BACKEND_NAME_MAX + 1
1355 // bytes; anything longer is rejected.
1356 let mut len = 0usize;
1357 while len < BACKEND_NAME_MAX {
1358 let b = unsafe { *name_u8.add(len) };
1359 if b == 0 {
1360 break;
1361 }
1362 len += 1;
1363 }
1364 if len == 0 {
1365 return NROS_RMW_RET_INVALID_ARGUMENT;
1366 }
1367 // Must have found a NUL within BACKEND_NAME_MAX.
1368 if unsafe { *name_u8.add(len) } != 0 {
1369 return NROS_RMW_RET_INVALID_ARGUMENT;
1370 }
1371
1372 let name_bytes = unsafe { core::slice::from_raw_parts(name_u8, len) };
1373
1374 // First pass: look for existing entry with same name → overwrite.
1375 let current_len = registry().len.load(Ordering::Acquire);
1376 for i in 0..current_len {
1377 // SAFETY: i < current_len, indices in bounds.
1378 let slot = unsafe { registry().slot(i) };
1379 if slot.name_matches(name_bytes) {
1380 // SAFETY: writer-side idempotent overwrite. The slot is
1381 // already published; concurrent readers will see either
1382 // the old or new vtable consistently, both valid.
1383 unsafe {
1384 let slot_mut = registry().slot_mut(i);
1385 slot_mut.vtable = vtable;
1386 }
1387 core::sync::atomic::fence(Ordering::Release);
1388 return NROS_RMW_RET_OK;
1389 }
1390 }
1391
1392 // No existing entry; append. Reserve a slot via atomic increment.
1393 let idx = registry().len.fetch_add(1, Ordering::AcqRel);
1394 if idx >= MAX_BACKENDS {
1395 // Roll back the increment so subsequent registers don't see a
1396 // stale `len > MAX_BACKENDS`. (Race window negligible — once
1397 // we hit capacity, no further append succeeds.)
1398 registry().len.store(MAX_BACKENDS, Ordering::Release);
1399 return NROS_RMW_RET_ERROR;
1400 }
1401
1402 // SAFETY: idx < MAX_BACKENDS, mutating an as-yet-unpublished slot.
1403 unsafe {
1404 let slot = registry().slot_mut(idx);
1405 slot.name[..len].copy_from_slice(name_bytes);
1406 slot.name[len] = 0;
1407 slot.vtable = vtable;
1408 }
1409 // Release-fence so concurrent lookups see both the name and the
1410 // vtable consistently with the updated `len`.
1411 core::sync::atomic::fence(Ordering::Release);
1412 NROS_RMW_RET_OK
1413}
1414
1415/// Look up a backend's vtable by name. Returns NULL if no backend
1416/// is registered under `name`.
1417///
1418/// # Safety
1419///
1420/// * `name` must be a valid NUL-terminated UTF-8 string.
1421#[unsafe(no_mangle)]
1422pub unsafe extern "C" fn nros_rmw_cffi_lookup(
1423 name: *const core::ffi::c_char,
1424) -> *const NrosRmwVtable {
1425 if name.is_null() {
1426 return core::ptr::null();
1427 }
1428 let name_u8 = name.cast::<u8>();
1429 let mut len = 0usize;
1430 while len < BACKEND_NAME_MAX {
1431 if unsafe { *name_u8.add(len) } == 0 {
1432 break;
1433 }
1434 len += 1;
1435 }
1436 if len == 0 || len == BACKEND_NAME_MAX {
1437 return core::ptr::null();
1438 }
1439 let name_bytes = unsafe { core::slice::from_raw_parts(name_u8, len) };
1440
1441 let current_len = registry().len.load(Ordering::Acquire);
1442 for i in 0..current_len {
1443 // SAFETY: i < current_len, indices in bounds; publication
1444 // fence via the atomic-len Acquire load.
1445 let slot = unsafe { registry().slot(i) };
1446 if slot.name_matches(name_bytes) {
1447 return slot.vtable;
1448 }
1449 }
1450 core::ptr::null()
1451}
1452
1453/// Diagnostic helper — fills `buf` with pointers to up to `cap`
1454/// registered backend names. Returns the number of names available
1455/// (may exceed `cap`). Pointer-valid for the program's lifetime.
1456///
1457/// # Safety
1458///
1459/// * `buf` must either be NULL (when `cap == 0`) or point at writable
1460/// memory of at least `cap * sizeof(*const c_char)` bytes.
1461#[unsafe(no_mangle)]
1462pub unsafe extern "C" fn nros_rmw_cffi_registered_names(
1463 buf: *mut *const core::ffi::c_char,
1464 cap: usize,
1465) -> usize {
1466 let n = registry().len.load(Ordering::Acquire);
1467 if !buf.is_null() && cap > 0 {
1468 let limit = n.min(cap);
1469 for i in 0..limit {
1470 // SAFETY: i < limit <= cap, buf capacity guaranteed by caller.
1471 let slot = unsafe { registry().slot(i) };
1472 unsafe {
1473 buf.add(i)
1474 .write(slot.name.as_ptr() as *const core::ffi::c_char)
1475 };
1476 }
1477 }
1478 n
1479}
1480
1481/// The name `vtable` was registered under — the first registry slot holding
1482/// that table — or NULL when it was never registered. The NULL-slot fallback
1483/// for `get_implementation_identifier` (`CffiSession::implementation_identifier_cstr`).
1484///
1485/// Matched by ADDRESS: the registry stores the caller's `&'static` table, so
1486/// a session opened through any registry path holds the same pointer.
1487fn registered_name_of(vtable: &'static NrosRmwVtable) -> *const core::ffi::c_char {
1488 let want = vtable as *const NrosRmwVtable;
1489 let n = registry().len.load(Ordering::Acquire);
1490 for i in 0..n {
1491 // SAFETY: i < n; the len-Acquire load orders the slot read.
1492 let slot = unsafe { registry().slot(i) };
1493 if core::ptr::eq(slot.vtable, want) {
1494 return slot.name.as_ptr().cast();
1495 }
1496 }
1497 core::ptr::null()
1498}
1499
1500/// Registry-presence probe. Returns `true` iff at
1501/// least one backend is registered. Used by `Executor::open` to
1502/// detect "user forgot to register a backend before opening the
1503/// session" and fail with a meaningful error.
1504#[inline]
1505pub fn backend_registered() -> bool {
1506 registry().len.load(Ordering::Acquire) > 0
1507}
1508
1509/// Phase 104.B — internal access to the registry for the Rust-side
1510/// adapter. `nros-node`'s ~~`register_active_backend`~~ removal already
1511/// switched to `backend_registered()` for the presence check; this
1512/// returns the vtable for any single-backend fast-path callers.
1513fn default_vtable() -> Option<&'static NrosRmwVtable> {
1514 let n = registry().len.load(Ordering::Acquire);
1515 if n == 0 {
1516 return None;
1517 }
1518 // SAFETY: index 0 < n, registry's len-Acquire fence orders the
1519 // slot read.
1520 let slot = unsafe { registry().slot(0) };
1521 if slot.vtable.is_null() {
1522 return None;
1523 }
1524 Some(unsafe { &*slot.vtable })
1525}
1526
1527/// Outcome of `resolve_backend`.
1528pub enum BackendResolution {
1529 /// Exactly one matching backend; use its vtable.
1530 Single(&'static NrosRmwVtable),
1531 /// No backend linked into the binary. Maps to
1532 /// [`NROS_RMW_RET_NO_BACKEND`].
1533 NoBackend,
1534 /// More than one backend linked and no selector given. Maps to
1535 /// [`NROS_RMW_RET_AMBIGUOUS_BACKEND`].
1536 Ambiguous,
1537 /// Selector did not match any registered backend. Maps to
1538 /// [`NROS_RMW_RET_UNKNOWN_BACKEND`].
1539 Unknown,
1540}
1541
1542/// Selection policy for the single-backend
1543/// `Executor::open` / `nros::init` path.
1544///
1545/// Algorithm:
1546///
1547/// 1. If `selector` is `Some(name)` (typically from `$NROS_RMW`),
1548/// look it up in the registry. Hit → [`BackendResolution::Single`];
1549/// miss → [`BackendResolution::Unknown`].
1550/// 2. Otherwise, if exactly one backend is registered, return it.
1551/// 3. Otherwise, if zero, [`BackendResolution::NoBackend`]; if more
1552/// than one, [`BackendResolution::Ambiguous`].
1553///
1554/// Callers convert the resolution to a [`NrosRmwRet`] via
1555/// [`backend_resolution_to_ret`].
1556///
1557/// Bridge consumers (`Executor::open_multi`) bypass this function and
1558/// call `nros_rmw_cffi_lookup` per spec instead.
1559pub fn resolve_backend(selector: Option<&[u8]>) -> BackendResolution {
1560 let n = registry().len.load(Ordering::Acquire);
1561 if let Some(name) = selector {
1562 let mut i = 0usize;
1563 while i < n {
1564 // SAFETY: i < n, registry len-Acquire fence orders the read.
1565 let slot = unsafe { registry().slot(i) };
1566 if slot.name_matches(name) {
1567 if slot.vtable.is_null() {
1568 return BackendResolution::Unknown;
1569 }
1570 return BackendResolution::Single(unsafe { &*slot.vtable });
1571 }
1572 i += 1;
1573 }
1574 return BackendResolution::Unknown;
1575 }
1576 match n {
1577 0 => BackendResolution::NoBackend,
1578 1 => default_vtable()
1579 .map(BackendResolution::Single)
1580 .unwrap_or(BackendResolution::NoBackend),
1581 _ => BackendResolution::Ambiguous,
1582 }
1583}
1584
1585/// Map a [`BackendResolution`] to its canonical
1586/// [`NrosRmwRet`]. [`BackendResolution::Single`] is *not* an error and
1587/// returns [`NROS_RMW_RET_OK`]; callers needing the vtable should
1588/// pattern-match on the resolution itself.
1589pub fn backend_resolution_to_ret(res: &BackendResolution) -> NrosRmwRet {
1590 match res {
1591 BackendResolution::Single(_) => NROS_RMW_RET_OK,
1592 BackendResolution::NoBackend => NROS_RMW_RET_NO_BACKEND,
1593 BackendResolution::Ambiguous => NROS_RMW_RET_AMBIGUOUS_BACKEND,
1594 BackendResolution::Unknown => NROS_RMW_RET_UNKNOWN_BACKEND,
1595 }
1596}
1597
1598// issue 0331 — `nros_rmw_cffi_set_custom_transport` takes the GENERATED
1599// `nros_transport_ops_t`, not the hand-written `nros_rmw::NrosTransportOps`.
1600//
1601// Under RFC-0054 the C header is the ABI SSoT and Rust consumes the committed
1602// bindgen output. The export used to take the hand-written Rust mirror while
1603// `rmw_transport.h` declared the generated type, so the two could drift and a
1604// C caller's struct layout was only accidentally correct.
1605//
1606// The two are still bridged by a `transmute_copy`, because
1607// `nros_rmw::set_custom_transport` takes the Rust type — but the bridge is
1608// guarded at COMPILE TIME here, so a drift that used to be silent is a build
1609// failure.
1610const _: () = {
1611 // RFC-0054: the header is the single source of truth.
1612 assert!(
1613 core::mem::size_of::<generated::nros_transport_ops_t>()
1614 == core::mem::size_of::<nros_rmw::NrosTransportOps>(),
1615 "nros_transport_ops_t and NrosTransportOps must have identical size: \
1616 the C header is the source of truth; regenerate with scripts/gen-abi-bindings.sh"
1617 );
1618 assert!(
1619 core::mem::align_of::<generated::nros_transport_ops_t>()
1620 == core::mem::align_of::<nros_rmw::NrosTransportOps>(),
1621 "nros_transport_ops_t and NrosTransportOps must have identical alignment"
1622 );
1623};
1624
1625/// C entry point for installing a custom transport.
1626///
1627/// Mirrors the Rust-side `nros_rmw::set_custom_transport(Some(...))`
1628/// (or `None` when `ops == NULL`) but returns the canonical
1629/// `rmw_ret_t` codes so non-Rust consumers don't have to
1630/// reach into nros-c's higher-level error enum.
1631///
1632/// The struct's contents are copied internally; the caller may
1633/// stack-allocate. Pass `NULL` to clear the slot.
1634///
1635/// # Safety
1636///
1637/// `ops` must either be `NULL` or point at a valid
1638/// `nros_transport_ops_t` whose four fn pointers stay live for the
1639/// lifetime of the registration (i.e. until a subsequent
1640/// `nros_rmw_cffi_set_custom_transport(NULL)` or a replacement
1641/// install).
1642#[unsafe(no_mangle)]
1643pub unsafe extern "C" fn nros_rmw_cffi_set_custom_transport(
1644 ops: *const generated::nros_transport_ops_t,
1645) -> NrosRmwRet {
1646 if ops.is_null() {
1647 // Clear: ignore any error (None is always accepted).
1648 let _ = unsafe { nros_rmw::set_custom_transport(None) };
1649 return NROS_RMW_RET_OK;
1650 }
1651 // SAFETY: caller guarantees `ops` is valid for one read.
1652 let src = unsafe { &*ops };
1653
1654 // issue 0331 — the generated type's fn-pointer slots are `Option<fn>`
1655 // (C nullability); `NrosTransportOps`' are plain `fn`. The two are
1656 // layout-identical via the null-pointer optimization, so a NULL slot
1657 // transmutes into a `fn` that is UB the moment the runtime calls it.
1658 // Taking the hand-written Rust type at this boundary made that
1659 // unrepresentable-looking but not unreachable — a C caller could always
1660 // pass NULL. Reject it here, before the copy.
1661 if src.open.is_none() || src.close.is_none() || src.write.is_none() || src.read.is_none() {
1662 return NROS_RMW_RET_INVALID_ARGUMENT;
1663 }
1664
1665 // SAFETY: layout equivalence of the two representations is asserted
1666 // above, and every fn slot is non-NULL per the check just made, so this
1667 // reinterpretation can neither silently mismatch nor produce a null `fn`.
1668 let copy: nros_rmw::NrosTransportOps = unsafe { core::mem::transmute_copy(src) };
1669 match unsafe { nros_rmw::set_custom_transport(Some(copy)) } {
1670 Ok(()) => NROS_RMW_RET_OK,
1671 Err(e) => ret_from_error(&e),
1672 }
1673}
1674
1675/// The UNNAMED open's answer to "which backend?" — issue 1050 defect (3).
1676///
1677/// This used to be `default_vtable()`, i.e. **registry slot 0**, described as a
1678/// single-backend fast path. It is not a fast path when two backends are
1679/// registered: it is a silent choice, and on a hosted target nobody makes it.
1680/// A Rust backend compiled into `libnros_cpp.a` registers from its
1681/// `.init_array` ctor, before `main`, and therefore before the image's own
1682/// generated `nros_app_register_backends()` runs — so slot 0 goes to whichever
1683/// backend the ARCHIVE happens to carry, not to the one the image declared. A
1684/// PX4 module declaring `BACKENDS uorb` opened zenoh that way.
1685///
1686/// `resolve_backend(None)` is the policy phase-128.A.3 already wrote for this
1687/// exact question, and `Executor::open_in` has consulted it since. It did not
1688/// reach here, so the tree carried TWO answers to one question and only one of
1689/// them refused an ambiguous registry — which is why the C++ surface was safe
1690/// and the C surface (`nros::internals::open_session` → [`CffiRmw::open`]) was
1691/// not. There is one answer now.
1692///
1693/// `InvalidConfig`, not `InvalidArgument`, for the ambiguous case: nothing has
1694/// been connected at this point, and reporting an unresolvable selection as a
1695/// transport failure is what sent issue 1050 looking for a missing router. The
1696/// empty-registry case keeps `InvalidArgument`, which is what it always
1697/// answered.
1698fn get_vtable() -> Result<&'static NrosRmwVtable, TransportError> {
1699 match resolve_backend(None) {
1700 BackendResolution::Single(vtable) => Ok(vtable),
1701 BackendResolution::Ambiguous => {
1702 nros_log::log_error!(
1703 nros_log::get_logger("nros_rmw_cffi"),
1704 "more than one RMW backend is registered and this open named \
1705 none; select one (hosted: $NROS_RMW=<name>; embedded: the \
1706 baked NROS_ENTRY_RMW rung), or open per-backend sessions"
1707 );
1708 Err(TransportError::InvalidConfig)
1709 }
1710 // `Unknown` is unreachable for a `None` selector; it collapses with
1711 // `NoBackend` rather than growing an arm that cannot be observed.
1712 BackendResolution::NoBackend | BackendResolution::Unknown => {
1713 Err(TransportError::InvalidArgument)
1714 }
1715 }
1716}
1717
1718// ============================================================================
1719// Helper: null-terminated string on the stack
1720// ============================================================================
1721
1722/// Write a Rust `&str` as a null-terminated byte sequence into a fixed buffer.
1723/// Returns a pointer to the buffer start (as C `char*`, matching the
1724/// generated ABI's string parameters).
1725fn to_c_str<const N: usize>(s: &str, buf: &mut [u8; N]) -> *const core::ffi::c_char {
1726 let len = s.len().min(N - 1);
1727 buf[..len].copy_from_slice(&s.as_bytes()[..len]);
1728 buf[len] = 0;
1729 buf.as_ptr().cast()
1730}
1731
1732/// Inverse of [`to_c_str`] — read a null-terminated byte buffer back
1733/// as a `&str`, stopping at the first NUL byte. Used by the
1734/// `topic_name()` / `type_name()` / `node_name()` accessors on the
1735/// `Cffi*` types so callers can introspect without round-tripping
1736/// through the vtable. Phase 102.5.
1737fn cstr_buf_to_str<const N: usize>(buf: &[u8; N]) -> &str {
1738 let len = buf.iter().position(|&b| b == 0).unwrap_or(N);
1739 // The buffers are written via `to_c_str` from a `&str`, so the
1740 // bytes between [..len] are guaranteed valid UTF-8. `from_utf8`
1741 // handles the (impossible) corruption case by returning empty.
1742 core::str::from_utf8(&buf[..len]).unwrap_or("")
1743}
1744
1745// ============================================================================
1746// Node table (phase-376 W5/B1)
1747// ============================================================================
1748//
1749// A SIDE table, not a field on `CffiSession`, for the same reason
1750// `MESSAGE_INFO_TABLE` above is one: the session's size is an ABI surface. It
1751// is what every C and C++ `_opaque` buffer is sized from, through a build-time
1752// probe that has to agree across every coordinate, and the guards that catch a
1753// disagreement are compile-time asserts in `nros-c` (issue 0472). Per-node
1754// bookkeeping is runtime state, not part of the session's shape — putting four
1755// name buffers inside the session grew `_opaque` by ~544 bytes in every C
1756// consumer and tripped those guards, which is the machinery working correctly
1757// and saying "this does not belong here".
1758
1759/// Distinct `(session, name, namespace)` triples the shim tracks. Raise with
1760/// `NROS_RMW_MAX_NODES`; the default mirrors the executor's `MAX_NODES`.
1761pub const MAX_NODES: usize = parse_env_usize(
1762 env!("NROS_RMW_MAX_NODES"),
1763 "NROS_RMW_MAX_NODES must be a decimal integer",
1764);
1765
1766struct NodeSlot {
1767 /// The owning session's `backend_data`, or 0 when free.
1768 session_key: portable_atomic::AtomicUsize,
1769 name: UnsafeCell<[u8; NODE_NAME_BUF_LEN]>,
1770 namespace_: UnsafeCell<[u8; NODE_NAME_BUF_LEN]>,
1771 backend_data: UnsafeCell<*mut c_void>,
1772}
1773
1774impl NodeSlot {
1775 const fn empty() -> Self {
1776 Self {
1777 session_key: portable_atomic::AtomicUsize::new(0),
1778 name: UnsafeCell::new([0u8; NODE_NAME_BUF_LEN]),
1779 namespace_: UnsafeCell::new([0u8; NODE_NAME_BUF_LEN]),
1780 backend_data: UnsafeCell::new(core::ptr::null_mut()),
1781 }
1782 }
1783}
1784
1785// SAFETY: a slot is claimed by a CAS on `session_key` from 0, and only the
1786// claiming thread writes its cells before any other reader can match it (a
1787// reader matches on `session_key` AND the names, which are written first).
1788// Entity creation is a setup-time operation on the executor thread.
1789unsafe impl Sync for NodeSlot {}
1790
1791static NODE_TABLE: [NodeSlot; MAX_NODES] = {
1792 #[allow(clippy::declare_interior_mutable_const)]
1793 const E: NodeSlot = NodeSlot::empty();
1794 [E; MAX_NODES]
1795};
1796
1797/// Release every node this session claimed. Called from `destroy_session`: a
1798/// static table that is never reclaimed would let a long-running image that
1799/// opens and closes sessions exhaust it.
1800/// Hand this session's node slots back, telling the backend first.
1801///
1802/// Issue 0800 — `create_node` was dispatched and `destroy_node` never was, so a
1803/// backend that allocated state in the create leaked it on every session close:
1804/// the shim forgot the node and the backend was never told it was gone. Nothing
1805/// caught it because `destroy_node` had no producer AND no consumer, which is
1806/// the state that reads as "optional slot" and is indistinguishable from
1807/// "nobody wired the other half".
1808///
1809/// Order matters: the nodes go before `destroy_session`, because a backend's
1810/// node state hangs off its session state.
1811fn release_session_nodes(
1812 session_key: usize,
1813 vtable: &'static NrosRmwVtable,
1814 session_view: &mut NrosRmwSession,
1815) {
1816 if session_key == 0 {
1817 return;
1818 }
1819 for slot in NODE_TABLE.iter() {
1820 if slot.session_key.load(Ordering::Acquire) != session_key {
1821 continue;
1822 }
1823 // SAFETY: written once by the claiming thread before the slot became
1824 // findable, and this session owns it.
1825 let backend_data = unsafe { *slot.backend_data.get() };
1826 if let Some(destroy) = vtable.destroy_node
1827 && !backend_data.is_null()
1828 {
1829 let mut view = node_view_of(slot, session_view);
1830 // SAFETY: `view` describes a node this session created through
1831 // `create_node`, and the session is still open.
1832 let ret = unsafe { destroy(&mut view) };
1833 if ret != NROS_RMW_RET_OK {
1834 nros_log::log_error!(
1835 nros_log::get_logger("nros_rmw_cffi"),
1836 "destroy_node failed with {}; the backend may still hold node state",
1837 ret
1838 );
1839 }
1840 }
1841 // SAFETY: same slot ownership as above; cleared before the slot is
1842 // published as free so a re-claim cannot see a stale pointer.
1843 unsafe { *slot.backend_data.get() = core::ptr::null_mut() };
1844 slot.session_key.store(0, Ordering::Release);
1845 }
1846}
1847
1848fn slot_str(cell: &UnsafeCell<[u8; NODE_NAME_BUF_LEN]>) -> &str {
1849 // SAFETY: cells are written once by the thread that claimed the slot,
1850 // before `session_key` makes it findable.
1851 cstr_buf_to_str(unsafe { &*cell.get() })
1852}
1853
1854fn find_node_slot(key: usize, name: &str, namespace: &str) -> Option<&'static NodeSlot> {
1855 NODE_TABLE.iter().find(|slot| {
1856 slot.session_key.load(Ordering::Acquire) == key
1857 && slot_str(&slot.name) == name
1858 && slot_str(&slot.namespace_) == namespace
1859 })
1860}
1861
1862fn claim_node_slot(key: usize, name: &str, namespace: &str) -> Option<&'static NodeSlot> {
1863 for slot in NODE_TABLE.iter() {
1864 if slot
1865 .session_key
1866 .compare_exchange(0, key, Ordering::AcqRel, Ordering::Acquire)
1867 .is_ok()
1868 {
1869 // SAFETY: the CAS above makes this thread the slot's owner, and a
1870 // reader cannot match it until the names are in place.
1871 unsafe {
1872 let _ = to_c_str(name, &mut *slot.name.get());
1873 let _ = to_c_str(namespace, &mut *slot.namespace_.get());
1874 *slot.backend_data.get() = core::ptr::null_mut();
1875 }
1876 return Some(slot);
1877 }
1878 }
1879 None
1880}
1881
1882fn node_view_of(slot: &'static NodeSlot, session_view: &mut NrosRmwSession) -> NrosRmwNode {
1883 NrosRmwNode {
1884 name: slot.name.get().cast(),
1885 namespace_: slot.namespace_.get().cast(),
1886 session: session_view as *mut NrosRmwSession,
1887 _reserved: [0u8; 8],
1888 // SAFETY: written once by the claiming thread before use.
1889 backend_data: unsafe { *slot.backend_data.get() },
1890 }
1891}
1892
1893// ============================================================================
1894// CffiSession
1895// ============================================================================
1896//
1897// Storage discipline:
1898// * Each Cffi* struct owns null-terminated name buffers as inline
1899// arrays. The C-side typed entity struct is rebuilt fresh on every
1900// FFI call via `make_*_view`, so move-invalidation of pointers
1901// into the buffer is impossible — the pointer always points to the
1902// *current* address of the buffer, computed at call time.
1903// * The backend writes `backend_data` (and `can_loan_messages` for
1904// pub/sub entities)
1905// into the FFI view; we copy the writes back into the Cffi*
1906// struct's fields after the call.
1907// * Strings ARE immutable for the entity's lifetime, so backends that
1908// stash the topic_name pointer for diagnostics see stable storage
1909// *as long as the Cffi* struct is not moved.* The Phase 102.4
1910// contract is "do not move a Cffi* struct after construction" —
1911// nano-ros embeds them inside the executor arena, which doesn't
1912// relocate.
1913
1914const NAME_BUF_LEN: usize = 256;
1915/// Node name / namespace storage. 64, not `NAME_BUF_LEN`: the executor bounds
1916/// both at `heapless::String<64>`, so a name that reached us through it cannot
1917/// be longer, and four nodes of two 256-byte buffers would put 2 KiB of mostly
1918/// zeroes in every session on an MCU.
1919const NODE_NAME_BUF_LEN: usize = 64;
1920/// Per-string bound for a marshalled session property. 256 so a TLS
1921/// certificate PATH fits; a longer KEY is refused rather than truncated. On an
1922/// `alloc` build the strings go to one heap block sized by the data (issue
1923/// 2401), so a VALUE has no bound there (a whole document, phase-514 W3b);
1924/// without `alloc` this is the size of each stack buffer, and a longer value
1925/// is refused.
1926const SESSION_PROPERTY_BUF_LEN: usize = 256;
1927/// `usize` spelling of the header's `RMW_SESSION_MAX_PROPERTIES` (RFC-0054:
1928/// the header is the SSoT; bindgen emits it as `i32`).
1929const MAX_SESSION_PROPERTIES: usize = generated::RMW_SESSION_MAX_PROPERTIES as usize;
1930
1931const HASH_BUF_LEN: usize = 128;
1932
1933/// The refusals every property-carrying open makes, before anything is copied
1934/// (issue 2401 moved them out of the copy loop so both marshalling arms share
1935/// one spelling). Refused, never truncated, all `InvalidArgument`: more than
1936/// `RMW_SESSION_MAX_PROPERTIES` entries, an empty key or value, a key of
1937/// `SESSION_PROPERTY_BUF_LEN` bytes or more, and, on a build without `alloc`,
1938/// a value that long. `to_c_str` truncates, which for a name is a
1939/// wrong-but-visible entity and for a TLS certificate path is a session that
1940/// fails somewhere unrelated.
1941fn check_session_properties(properties: &[(&str, &str)]) -> Result<(), TransportError> {
1942 if properties.len() > MAX_SESSION_PROPERTIES {
1943 return Err(TransportError::InvalidArgument);
1944 }
1945 for (key, value) in properties {
1946 if key.is_empty() || value.is_empty() || key.len() >= SESSION_PROPERTY_BUF_LEN {
1947 return Err(TransportError::InvalidArgument);
1948 }
1949 // A value too long for a stack buffer is a whole configuration
1950 // document the backend parses itself (RFC-0109 D6, phase-514 W3b); it
1951 // fits only where the strings go to the heap.
1952 if cfg!(not(feature = "alloc")) && value.len() >= SESSION_PROPERTY_BUF_LEN {
1953 return Err(TransportError::InvalidArgument);
1954 }
1955 }
1956 Ok(())
1957}
1958
1959/// Copy `properties` (already checked) into ONE heap block, each string
1960/// followed by its NUL, and point `entries` at them. The block is sized by the
1961/// data: two short properties cost a few dozen bytes, not 8 KiB. Exhaustion is
1962/// `BadAlloc` (issue 1551: a fallible reservation, never the aborting one).
1963/// The caller keeps the returned block alive across `create_session`.
1964#[cfg(feature = "alloc")]
1965fn marshal_on_heap(
1966 properties: &[(&str, &str)],
1967 entries: &mut [rmw_session_property_t; MAX_SESSION_PROPERTIES],
1968) -> Result<alloc::vec::Vec<u8>, TransportError> {
1969 let total: usize = properties.iter().map(|(k, v)| k.len() + v.len() + 2).sum();
1970 let mut block = alloc::vec::Vec::new();
1971 block
1972 .try_reserve_exact(total)
1973 .map_err(|_| TransportError::BadAlloc)?;
1974 for (key, value) in properties {
1975 block.extend_from_slice(key.as_bytes());
1976 block.push(0);
1977 block.extend_from_slice(value.as_bytes());
1978 block.push(0);
1979 }
1980 // Pointers are taken only after the last push, from the finished block,
1981 // by walking the same lengths again (no offset table on the stack). It
1982 // was reserved exactly, so it never moved anyway.
1983 let mut at = 0usize;
1984 for ((key, value), entry) in properties.iter().zip(entries.iter_mut()) {
1985 let key_ptr = block[at..].as_ptr();
1986 at += key.len() + 1;
1987 let value_ptr = block[at..].as_ptr();
1988 at += value.len() + 1;
1989 *entry = rmw_session_property_t {
1990 key: key_ptr.cast(),
1991 value: value_ptr.cast(),
1992 };
1993 }
1994 Ok(block)
1995}
1996
1997/// Copy `properties` (already checked, so every string fits with its NUL)
1998/// into the caller's stack buffers and point `entries` at them. The no-`alloc`
1999/// arm: there is no heap to size by the data, so the buffers are the bound.
2000#[cfg(not(feature = "alloc"))]
2001fn marshal_on_stack(
2002 properties: &[(&str, &str)],
2003 bufs: &mut [[[u8; SESSION_PROPERTY_BUF_LEN]; 2]; MAX_SESSION_PROPERTIES],
2004 entries: &mut [rmw_session_property_t; MAX_SESSION_PROPERTIES],
2005) {
2006 for (((key, value), [kb, vb]), entry) in properties
2007 .iter()
2008 .zip(bufs.iter_mut())
2009 .zip(entries.iter_mut())
2010 {
2011 kb[..key.len()].copy_from_slice(key.as_bytes());
2012 kb[key.len()] = 0;
2013 vb[..value.len()].copy_from_slice(value.as_bytes());
2014 vb[value.len()] = 0;
2015 *entry = rmw_session_property_t {
2016 key: kb.as_ptr().cast(),
2017 value: vb.as_ptr().cast(),
2018 };
2019 }
2020}
2021
2022/// Session backed by a C vtable.
2023pub struct CffiSession {
2024 vtable: &'static NrosRmwVtable,
2025 /// Borrowed-pointer storage for `node_name`. Outlives the session.
2026 node_name_buf: [u8; NAME_BUF_LEN],
2027 /// Borrowed-pointer storage for `namespace_`, filled at open from
2028 /// `RmwConfig::namespace` — issue 1444.
2029 ///
2030 /// It read "empty for now … reserved for future use" for as long as the
2031 /// field existed, and that comment WAS the bug: `rmw_vtable.h` promises a
2032 /// backend an `rmw_session_t` "with `node_name` / `namespace_` already
2033 /// filled", `Executor::open` had been filling `RmwConfig { namespace, .. }`
2034 /// all along, and only this seam dropped it — so every namespaced image
2035 /// advertised its SESSION node at the root while its per-node entities went
2036 /// where they belonged, and `ros2 node list` printed both without either
2037 /// looking wrong.
2038 ///
2039 /// EMPTY is passed through, not defaulted: the backend already reads an
2040 /// empty namespace as the root (`shim/session.rs`, "Treat empty namespace
2041 /// as root"), and a second default here would be a second place for the two
2042 /// to disagree.
2043 namespace_buf: [u8; NAME_BUF_LEN],
2044 /// Backend-private state, written by `vtable.create_session`.
2045 backend_data: *mut c_void,
2046 /// The domain this session was opened on. Kept because the entity paths
2047 /// need it and could not otherwise recover it: `create_session` consumed
2048 /// it and nothing stored it, so a caller with no support context silently
2049 /// fell back to domain 0 while the session itself was on another domain
2050 /// (issue 0801).
2051 domain_id: u32,
2052 /// What the REGISTERED backend said it honours, read once at open through
2053 /// `vtable.supported_qos_policies` (issue 1329).
2054 ///
2055 /// Cached rather than asked per create for two reasons, and the second is
2056 /// the load-bearing one: `Session::supported_qos_policies` takes `&self`
2057 /// while reaching the slot needs a `&mut` session view, and an answer that
2058 /// changed between two `create_publisher` calls would make one entity's
2059 /// refusal and another's acceptance depend on when they ran. The slot's
2060 /// contract is per session, so once per session is when to ask.
2061 qos_policies: nros_rmw::QoSPolicyMask,
2062}
2063
2064/// phase-381 W5/W6 — the C graph visitor, turned back into a Rust closure call.
2065///
2066/// `ctx` is a `*mut &mut dyn FnMut(...)`, which is how the borrowed closure
2067/// crosses the C boundary. The strings are BORROWED for this call only, which
2068/// is the contract on both sides.
2069///
2070/// A name that is not valid UTF-8 is SKIPPED rather than lossily converted: a
2071/// mangled node name is a different, plausible node.
2072///
2073/// # Safety
2074/// Called only by a backend slot this crate handed `ctx` to.
2075unsafe extern "C" fn node_visit_trampoline(
2076 ctx: *mut core::ffi::c_void,
2077 node_name: *const core::ffi::c_char,
2078 node_namespace: *const core::ffi::c_char,
2079 enclave: *const core::ffi::c_char,
2080) -> bool {
2081 if ctx.is_null() || node_name.is_null() || node_namespace.is_null() {
2082 return true; // skip this entry, keep enumerating
2083 }
2084 let cb = unsafe { &mut *(ctx as *mut &mut dyn FnMut(&str, &str, Option<&str>) -> bool) };
2085 let (Ok(name), Ok(ns)) = (
2086 unsafe { core::ffi::CStr::from_ptr(node_name) }.to_str(),
2087 unsafe { core::ffi::CStr::from_ptr(node_namespace) }.to_str(),
2088 ) else {
2089 return true;
2090 };
2091 let enc = if enclave.is_null() {
2092 None
2093 } else {
2094 unsafe { core::ffi::CStr::from_ptr(enclave) }.to_str().ok()
2095 };
2096 cb(name, ns, enc)
2097}
2098
2099/// Longest node name / namespace / topic this seam passes to a backend slot.
2100///
2101/// A longer one is REFUSED (`BufferTooSmall`), not truncated: a truncated node
2102/// name is a different, plausible node, and this seam's whole job is answering
2103/// "which node".
2104const GRAPH_NAME_CAP: usize = 256;
2105
2106/// phase-381 — the C endpoint-info visitor, back into a Rust closure call.
2107///
2108/// Mirrors [`names_and_types_visit_trampoline`]. `qos_profile` is deliberately
2109/// dropped: `GraphEndpointInfo` carries no `qos` field, because no backend can
2110/// fill it with a GRANTED profile today and reporting the requested one would
2111/// be the plausible wrong answer the slot exists to avoid.
2112///
2113/// # Safety
2114/// Called only by a backend slot this crate handed `ctx` to.
2115unsafe extern "C" fn endpoint_info_visit_trampoline(
2116 ctx: *mut core::ffi::c_void,
2117 info: *const generated::rmw_topic_endpoint_info_t,
2118) -> bool {
2119 if ctx.is_null() || info.is_null() {
2120 return true; // skip this entry, keep enumerating
2121 }
2122 let info = unsafe { &*info };
2123 let cb = unsafe { &mut *(ctx as *mut &mut dyn FnMut(&GraphEndpointInfo<'_>) -> bool) };
2124
2125 // Each borrowed string is skipped rather than lossily converted, for the
2126 // same reason as the names-and-types side.
2127 let cstr = |p: *const core::ffi::c_char| -> Option<&str> {
2128 if p.is_null() {
2129 None
2130 } else {
2131 unsafe { core::ffi::CStr::from_ptr(p) }.to_str().ok()
2132 }
2133 };
2134 let (Some(node_name), Some(node_namespace), Some(topic_type)) = (
2135 cstr(info.node_name),
2136 cstr(info.node_namespace),
2137 cstr(info.topic_type),
2138 ) else {
2139 return true;
2140 };
2141
2142 let view = GraphEndpointInfo {
2143 node_name,
2144 node_namespace,
2145 topic_type,
2146 is_publisher: info.endpoint_type == generated::rmw_endpoint_type_t::RMW_ENDPOINT_PUBLISHER,
2147 endpoint_gid: info.endpoint_gid.data,
2148 // issue 1973 — what the backend matched this endpoint on; the
2149 // best-available resolution folds it.
2150 qos: qos_from_c(&info.qos_profile),
2151 };
2152 cb(&view)
2153}
2154
2155/// phase-381 — the C names-and-types visitor, back into a Rust closure call.
2156///
2157/// # Safety
2158/// Called only by a backend slot this crate handed `ctx` to.
2159unsafe extern "C" fn names_and_types_visit_trampoline(
2160 ctx: *mut core::ffi::c_void,
2161 name: *const core::ffi::c_char,
2162 types: *const *const core::ffi::c_char,
2163 types_count: usize,
2164) -> bool {
2165 if ctx.is_null() || name.is_null() {
2166 return true; // skip this entry, keep enumerating
2167 }
2168 let cb = unsafe { &mut *(ctx as *mut &mut dyn FnMut(&str, &[&str]) -> bool) };
2169 let Ok(name) = (unsafe { core::ffi::CStr::from_ptr(name) }).to_str() else {
2170 return true;
2171 };
2172 // Bounded on the stack: the C side owns the array for this call only, and a
2173 // type that is not valid UTF-8 is SKIPPED rather than lossily converted — a
2174 // mangled type name is a different, plausible type.
2175 const TYPES_MAX: usize = 8;
2176 let mut buf: [&str; TYPES_MAX] = [""; TYPES_MAX];
2177 let mut n = 0usize;
2178 if !types.is_null() {
2179 for i in 0..types_count.min(TYPES_MAX) {
2180 let p = unsafe { *types.add(i) };
2181 if p.is_null() {
2182 continue;
2183 }
2184 if let Ok(t) = (unsafe { core::ffi::CStr::from_ptr(p) }).to_str() {
2185 buf[n] = t;
2186 n += 1;
2187 }
2188 }
2189 }
2190 cb(name, &buf[..n])
2191}
2192
2193/// Shared body for `count_publishers` / `count_subscribers`, and (issue
2194/// 1978) `count_clients` / `count_services`, whose name is a service name.
2195fn count_on_topic(
2196 view: &NrosRmwSession,
2197 f: unsafe extern "C" fn(
2198 *const NrosRmwSession,
2199 *const core::ffi::c_char,
2200 *mut usize,
2201 ) -> NrosRmwRet,
2202 topic_name: &str,
2203) -> Result<usize, TransportError> {
2204 // NUL-terminate on the stack; the C side borrows for the call only.
2205 const NAME_MAX: usize = 256;
2206 if topic_name.len() >= NAME_MAX {
2207 return Err(TransportError::InvalidArgument);
2208 }
2209 let mut buf = [0u8; NAME_MAX];
2210 buf[..topic_name.len()].copy_from_slice(topic_name.as_bytes());
2211 let mut out: usize = 0;
2212 let rc = unsafe {
2213 f(
2214 view as *const NrosRmwSession,
2215 buf.as_ptr() as *const core::ffi::c_char,
2216 &mut out,
2217 )
2218 };
2219 if rc == NROS_RMW_RET_OK {
2220 Ok(out)
2221 } else {
2222 Err(error_from_ret(rc))
2223 }
2224}
2225
2226impl CffiSession {
2227 /// Domain this session was opened on. Authoritative: it is the value the
2228 /// backend actually got, not a re-derivation that can disagree with it.
2229 pub fn domain_id(&self) -> u32 {
2230 self.domain_id
2231 }
2232
2233 /// The serialization format THIS session's
2234 /// backend speaks, as a NUL-terminated C string with `'static` lifetime,
2235 /// or NULL when the backend does not declare one.
2236 ///
2237 /// **Not** `<Self as Session>::SERIALIZATION_FORMAT`. That const is the
2238 /// trait default, `"cdr"`, and it is a lie for this type specifically:
2239 /// `CffiSession` is the one session that does not know its own backend at
2240 /// compile time — the vtable arrives at run time through
2241 /// `nros_rmw_cffi_register_named`, and an image may register several. The
2242 /// per-session answer therefore has to come from the vtable, which is the
2243 /// whole reason the slot got a body.
2244 ///
2245 /// A NULL slot answers NULL rather than `"cdr"`: a backend that declines
2246 /// to say what it speaks has not said `"cdr"`, and guessing on its behalf
2247 /// is the mistake `get_implementation_identifier`'s doc once made, since
2248 /// corrected. Every in-tree backend fills the slot, so NULL means a foreign
2249 /// vtable or one older than the slot.
2250 pub fn serialization_format_cstr(&self) -> *const core::ffi::c_char {
2251 match self.vtable.get_serialization_format {
2252 // SAFETY: the slot is a non-NULL fn pointer a registered backend
2253 // installed; it takes no arguments and returns static storage.
2254 Some(f) => unsafe { f() },
2255 None => core::ptr::null(),
2256 }
2257 }
2258
2259 /// [`serialization_format_cstr`](Self::serialization_format_cstr) as a
2260 /// Rust string. `None` for a NULL slot or a non-UTF-8 answer.
2261 pub fn serialization_format(&self) -> Option<&'static str> {
2262 let ptr = self.serialization_format_cstr();
2263 if ptr.is_null() {
2264 return None;
2265 }
2266 // SAFETY: a backend's format name is a `'static` NUL-terminated string
2267 // literal — the slot's contract, and what every in-tree body returns.
2268 unsafe { core::ffi::CStr::from_ptr(ptr) }.to_str().ok()
2269 }
2270
2271 /// The backend's name — `rmw_get_implementation_identifier()`, per session
2272 /// — as a NUL-terminated C string with `'static` lifetime, or NULL.
2273 ///
2274 /// The vtable's `get_implementation_identifier` slot when the backend
2275 /// fills it; otherwise the name this session's vtable was REGISTERED under
2276 /// (`nros_rmw_cffi_register_named`), which is the slot's documented
2277 /// NULL-slot fallback. That fallback is a fact the registry holds, not a
2278 /// guess on the backend's behalf — unlike a format, a backend's name is
2279 /// exactly what registering it stated. NULL only for a vtable that never
2280 /// went through the registry (a test opening one directly).
2281 pub fn implementation_identifier_cstr(&self) -> *const core::ffi::c_char {
2282 match self.vtable.get_implementation_identifier {
2283 // SAFETY: a non-NULL fn pointer a registered backend installed; it
2284 // takes no arguments and returns static storage.
2285 Some(f) => unsafe { f() },
2286 None => registered_name_of(self.vtable),
2287 }
2288 }
2289
2290 /// [`implementation_identifier_cstr`](Self::implementation_identifier_cstr)
2291 /// as a Rust string. `None` for no answer or a non-UTF-8 one.
2292 pub fn implementation_identifier(&self) -> Option<&'static str> {
2293 let ptr = self.implementation_identifier_cstr();
2294 if ptr.is_null() {
2295 return None;
2296 }
2297 // SAFETY: a static NUL-terminated string — a backend literal or a
2298 // registry slot's name, which is never freed or rewritten in place
2299 // (a re-registration under the same name keeps the name bytes).
2300 unsafe { core::ffi::CStr::from_ptr(ptr) }.to_str().ok()
2301 }
2302
2303 fn make_view(&mut self) -> NrosRmwSession {
2304 NrosRmwSession {
2305 node_name: self.node_name_buf.as_ptr().cast(),
2306 namespace_: self.namespace_buf.as_ptr().cast(),
2307 _reserved: [0u8; 8],
2308 backend_data: self.backend_data,
2309 }
2310 }
2311
2312 /// Phase 376 W5/B1 — find or create the node an entity belongs to, and
2313 /// return a view a `create_*` slot can take.
2314 ///
2315 /// This replaces `entity_view`, which fabricated a per-call
2316 /// `NrosRmwSession` whose `node_name` carried the entity's owning node.
2317 /// That worked and cost no ABI change, which is why phase-268 chose it —
2318 /// but it meant a backend learned about a node by reading a STRING off a
2319 /// session it was also using for transport state, and had to re-derive the
2320 /// set of nodes itself. zenoh does precisely that, linear-scanning declared
2321 /// liveliness tokens to answer "have I seen this node before".
2322 ///
2323 /// Now the runtime owns that question: `create_node` fires once per
2324 /// distinct `(name, namespace)`, which is only true because
2325 /// `Executor::create_node` deduplicates too (W5/B1.a).
2326 ///
2327 /// The returned `rmw_node_t` borrows `session_view` and the table's name
2328 /// cells, so the caller keeps `session_view` alive across the slot call —
2329 /// the same discipline `entity_view` documented, moved one level up.
2330 fn node_slot(
2331 &mut self,
2332 node_name: Option<&str>,
2333 namespace: &str,
2334 session_view: &mut NrosRmwSession,
2335 ) -> Result<NrosRmwNode, TransportError> {
2336 let key = self.backend_data as usize;
2337 if key == 0 {
2338 return Err(TransportError::InvalidArgument);
2339 }
2340
2341 // No node identity on the entity (direct-RMW / single-node path): fall
2342 // back to the session's own open-time name, which is what phase-268's
2343 // fallback did and keeps a one-node image working unchanged.
2344 let mut scratch = [0u8; NODE_NAME_BUF_LEN];
2345 let name: &str = match node_name {
2346 Some(n) if !n.is_empty() => n,
2347 _ => {
2348 let owned = self.node_name();
2349 let len = owned.len().min(NODE_NAME_BUF_LEN - 1);
2350 scratch[..len].copy_from_slice(&owned.as_bytes()[..len]);
2351 cstr_buf_to_str(&scratch)
2352 }
2353 };
2354
2355 // Truncating would MERGE two distinct nodes into one record and then
2356 // declare the wrong identity on the graph, so it is refused. The
2357 // executor bounds both at 64, so a name that arrived through it fits.
2358 if name.len() >= NODE_NAME_BUF_LEN || namespace.len() >= NODE_NAME_BUF_LEN {
2359 return Err(TransportError::InvalidArgument);
2360 }
2361
2362 if let Some(slot) = find_node_slot(key, name, namespace) {
2363 return Ok(node_view_of(slot, session_view));
2364 }
2365
2366 let slot = claim_node_slot(key, name, namespace).ok_or(TransportError::ConnectionFailed)?;
2367
2368 // A backend with no `create_node` keeps working: the node is then a
2369 // pure identity carrier with a NULL `backend_data`, which is what every
2370 // backend that has not implemented the slot already sees.
2371 if let Some(create) = self.vtable.create_node {
2372 let mut view = node_view_of(slot, session_view);
2373 let ret = unsafe {
2374 create(
2375 session_view as *mut NrosRmwSession,
2376 view.name,
2377 view.namespace_,
2378 &mut view,
2379 )
2380 };
2381 if ret != NROS_RMW_RET_OK {
2382 slot.session_key.store(0, Ordering::Release);
2383 return Err(error_from_ret(ret));
2384 }
2385 // SAFETY: this thread claimed the slot above and nothing else
2386 // writes it.
2387 unsafe { *slot.backend_data.get() = view.backend_data };
2388 }
2389 Ok(node_view_of(slot, session_view))
2390 }
2391
2392 /// Node name passed at session-open time.
2393 pub fn node_name(&self) -> &str {
2394 cstr_buf_to_str(&self.node_name_buf)
2395 }
2396
2397 /// Node namespace passed at session-open time.
2398 ///
2399 /// The sibling of [`node_name`](Self::node_name), and its absence was part
2400 /// of why the buffer stayed empty unnoticed: `node_name_buf` had a reader
2401 /// and `namespace_buf` had only the borrowed pointer a backend follows, so
2402 /// nothing in Rust could ask what the session's namespace was.
2403 ///
2404 /// `""` means the image declares none, which every backend reads as the
2405 /// root. It is NOT normalised here — see `namespace_buf`.
2406 pub fn namespace(&self) -> &str {
2407 cstr_buf_to_str(&self.namespace_buf)
2408 }
2409
2410 /// Open a new session via the **default** registered vtable
2411 /// (first entry in the registry — the RMW_IMPLEMENTATION-style
2412 /// fast path for single-backend builds).
2413 ///
2414 /// For explicit backend selection in multi-backend (bridge)
2415 /// binaries, use [`open_named`](Self::open_named).
2416 pub fn open(
2417 locator: &str,
2418 mode: u8,
2419 domain_id: u32,
2420 node_name: &str,
2421 namespace: &str,
2422 ) -> Result<Self, TransportError> {
2423 let vtable = get_vtable()?;
2424 Self::open_with_vtable(
2425 vtable,
2426 locator,
2427 mode,
2428 domain_id,
2429 node_name,
2430 namespace,
2431 core::ptr::null(),
2432 )
2433 }
2434
2435 /// Open a session carrying backend-specific configuration
2436 /// properties (`RmwConfig::properties` across the C seam).
2437 ///
2438 /// This is the rung that was missing. `RmwConfig` has carried
2439 /// `properties` since it existed and every Rust backend reads them, but
2440 /// nothing between the runtime and the vtable passed them on: this
2441 /// function's non-properties sibling handed `create_session` a NULL
2442 /// options pointer, and the Rust-backend adapter on the far side built
2443 /// `properties: &[]` unconditionally. So the only way to set a zenoh
2444 /// `listen` endpoint, a TLS certificate or a scouting timeout was to build
2445 /// an `RmwConfig` by hand in hosted Rust — a C or C++ image could state
2446 /// none of it, on any platform.
2447 ///
2448 /// Refused, never truncated: more than `RMW_SESSION_MAX_PROPERTIES`
2449 /// entries, an empty key or value, a key longer than
2450 /// `SESSION_PROPERTY_BUF_LEN`, or (without `alloc`) a value that long.
2451 /// All are `TransportError::InvalidArgument`; an exhausted heap on an
2452 /// `alloc` build is `TransportError::BadAlloc`.
2453 pub fn open_with_properties(
2454 locator: &str,
2455 mode: u8,
2456 domain_id: u32,
2457 node_name: &str,
2458 namespace: &str,
2459 properties: &[(&str, &str)],
2460 ) -> Result<Self, TransportError> {
2461 let vtable = get_vtable()?;
2462 if properties.is_empty() {
2463 return Self::open_with_vtable(
2464 vtable,
2465 locator,
2466 mode,
2467 domain_id,
2468 node_name,
2469 namespace,
2470 core::ptr::null(),
2471 );
2472 }
2473 Self::open_marshalling_properties(
2474 vtable, locator, mode, domain_id, node_name, namespace, properties,
2475 )
2476 }
2477
2478 /// The property-carrying half of [`open_with_properties`], kept in its own
2479 /// never-inlined frame so only a call that has properties to carry pays
2480 /// for marshalling them. An MCU image that configures nothing pays nothing.
2481 ///
2482 /// Issue 2401: `create_session` takes every property at once, as an array
2483 /// of NUL-terminated strings borrowed for the call (`rmw_entity.h`), so
2484 /// all `2 x n` C strings must exist together; the seam cannot hand them
2485 /// over one at a time. Where to put them is therefore the whole question:
2486 ///
2487 /// - **`alloc` build** ([`marshal_on_heap`]): one allocation, packed and
2488 /// sized by the data actually stated, freed when the open returns. The
2489 /// stack holds only the entry array. This used to be
2490 /// `RMW_SESSION_MAX_PROPERTIES x 2 x SESSION_PROPERTY_BUF_LEN` = 8 KiB
2491 /// of stack whatever the data, which made it the largest frame on every
2492 /// RTOS's open path (8,472 B on Cortex-M7).
2493 /// - **no `alloc`** ([`marshal_on_stack`]): the fixed stack buffers, as
2494 /// before. There is no heap to ask, and a shared static would need a
2495 /// lock every concurrent open could contend on, plus 8 KiB of `.bss` in
2496 /// every image whether it opens with properties or not.
2497 ///
2498 /// The refusals are the same on both: see [`check_session_properties`].
2499 #[inline(never)]
2500 fn open_marshalling_properties(
2501 vtable: &'static NrosRmwVtable,
2502 locator: &str,
2503 mode: u8,
2504 domain_id: u32,
2505 node_name: &str,
2506 namespace: &str,
2507 properties: &[(&str, &str)],
2508 ) -> Result<Self, TransportError> {
2509 check_session_properties(properties)?;
2510 let mut entries = [rmw_session_property_t {
2511 key: core::ptr::null(),
2512 value: core::ptr::null(),
2513 }; MAX_SESSION_PROPERTIES];
2514 #[cfg(feature = "alloc")]
2515 let _strings = marshal_on_heap(properties, &mut entries)?;
2516 #[cfg(not(feature = "alloc"))]
2517 let mut bufs = [[[0u8; SESSION_PROPERTY_BUF_LEN]; 2]; MAX_SESSION_PROPERTIES];
2518 #[cfg(not(feature = "alloc"))]
2519 marshal_on_stack(properties, &mut bufs, &mut entries);
2520 let options = NrosRmwSessionOptions {
2521 localhost_only: 0,
2522 _reserved: [0u8; 7],
2523 enclave: core::ptr::null(),
2524 properties: entries.as_ptr(),
2525 property_count: properties.len(),
2526 };
2527 // `_strings` / `bufs` outlive this call, which is all the ABI asks:
2528 // the strings are borrowed for the duration of `create_session`.
2529 Self::open_with_vtable(
2530 vtable, locator, mode, domain_id, node_name, namespace, &options,
2531 )
2532 }
2533
2534 /// Open a new session against a named backend.
2535 /// Resolves `rmw_name` against the registry,
2536 /// returns `Err(TransportError::InvalidArgument)` if no backend
2537 /// is registered under that name.
2538 pub fn open_named(
2539 rmw_name: &str,
2540 locator: &str,
2541 mode: u8,
2542 domain_id: u32,
2543 node_name: &str,
2544 namespace: &str,
2545 ) -> Result<Self, TransportError> {
2546 // C-string-marshal `rmw_name` on the stack — registry lookup
2547 // expects NUL-terminated UTF-8.
2548 let mut name_buf = [0u8; BACKEND_NAME_MAX];
2549 if rmw_name.len() >= BACKEND_NAME_MAX {
2550 return Err(TransportError::InvalidArgument);
2551 }
2552 name_buf[..rmw_name.len()].copy_from_slice(rmw_name.as_bytes());
2553 // name_buf[rmw_name.len()] is already 0.
2554 let raw = unsafe { nros_rmw_cffi_lookup(name_buf.as_ptr() as *const _) };
2555 if raw.is_null() {
2556 return Err(TransportError::InvalidArgument);
2557 }
2558 // SAFETY: registry-issued pointer; valid for the program's lifetime.
2559 let vtable = unsafe { &*raw };
2560 Self::open_with_vtable(
2561 vtable,
2562 locator,
2563 mode,
2564 domain_id,
2565 node_name,
2566 namespace,
2567 core::ptr::null(),
2568 )
2569 }
2570
2571 /// [`open_named`](Self::open_named) carrying backend-specific
2572 /// configuration properties — see [`open_with_properties`](Self::open_with_properties).
2573 pub fn open_named_with_properties(
2574 rmw_name: &str,
2575 locator: &str,
2576 mode: u8,
2577 domain_id: u32,
2578 node_name: &str,
2579 namespace: &str,
2580 properties: &[(&str, &str)],
2581 ) -> Result<Self, TransportError> {
2582 let mut name_buf = [0u8; BACKEND_NAME_MAX];
2583 if rmw_name.len() >= BACKEND_NAME_MAX {
2584 return Err(TransportError::InvalidArgument);
2585 }
2586 name_buf[..rmw_name.len()].copy_from_slice(rmw_name.as_bytes());
2587 let raw = unsafe { nros_rmw_cffi_lookup(name_buf.as_ptr() as *const _) };
2588 if raw.is_null() {
2589 return Err(TransportError::InvalidArgument);
2590 }
2591 // SAFETY: registry-issued pointer; valid for the program's lifetime.
2592 let vtable = unsafe { &*raw };
2593 if properties.is_empty() {
2594 return Self::open_with_vtable(
2595 vtable,
2596 locator,
2597 mode,
2598 domain_id,
2599 node_name,
2600 namespace,
2601 core::ptr::null(),
2602 );
2603 }
2604 Self::open_marshalling_properties(
2605 vtable, locator, mode, domain_id, node_name, namespace, properties,
2606 )
2607 }
2608
2609 fn open_with_vtable(
2610 vtable: &'static NrosRmwVtable,
2611 locator: &str,
2612 mode: u8,
2613 domain_id: u32,
2614 node_name: &str,
2615 namespace: &str,
2616 options: *const NrosRmwSessionOptions,
2617 ) -> Result<Self, TransportError> {
2618 let mut loc_buf = [0u8; NAME_BUF_LEN];
2619 let loc_ptr = to_c_str(locator, &mut loc_buf);
2620
2621 let mut session = Self {
2622 vtable,
2623 node_name_buf: [0u8; NAME_BUF_LEN],
2624 namespace_buf: [0u8; NAME_BUF_LEN],
2625 backend_data: core::ptr::null_mut(),
2626 domain_id,
2627 qos_policies: nros_rmw::QoSPolicyMask::NONE,
2628 };
2629 let _ = to_c_str(node_name, &mut session.node_name_buf);
2630 // Issue 1444 — the other half of what `rmw_vtable.h` promises
2631 // `create_session`. Written BEFORE `view` borrows the buffer, and
2632 // passed through as given: an empty namespace is the root at the
2633 // backend, so normalising it here would be a second default.
2634 let _ = to_c_str(namespace, &mut session.namespace_buf);
2635
2636 let mut view = NrosRmwSession {
2637 node_name: session.node_name_buf.as_ptr().cast(),
2638 namespace_: session.namespace_buf.as_ptr().cast(),
2639 _reserved: [0u8; 8],
2640 backend_data: core::ptr::null_mut(),
2641 };
2642 let ret = unsafe {
2643 (vtable.create_session.expect("rmw vtable: create_session"))(
2644 loc_ptr,
2645 mode,
2646 domain_id,
2647 session.node_name_buf.as_ptr().cast(),
2648 // issue 0808 — NULL is "every default"; phase-206 W3 made this
2649 // a real argument. A caller reaches the backend's own
2650 // configuration through this struct rather than through a
2651 // locator it would have to parse
2652 // ([`open_with_properties`](Self::open_with_properties)).
2653 options,
2654 &mut view,
2655 )
2656 };
2657 // Phase 156.4 — diagnostic for bridge runtime
2658 // ConnectionFailed investigation. Logs the raw ret +
2659 // post-open backend_data state so callers see which of
2660 // the two failure paths fired. Gated on env var so
2661 // production traffic stays quiet.
2662 // issue 0589 — `nros_log`, never std stdio (fatal on Zephyr
2663 // native_sim). The env gate stays: it decides whether to FORMAT, which
2664 // is the cost worth avoiding on a hot open path; the level would only
2665 // decide whether to emit.
2666 // phase-359 W10 stage B — through the C library, so the trace works on
2667 // every hosted build and no longer needs this crate's `std`.
2668 #[cfg(target_os = "linux")]
2669 if trace_open_enabled() {
2670 nros_log::log_info!(
2671 nros_log::get_logger("nros_rmw_cffi"),
2672 "open: locator={locator:?} mode={mode} ret={ret} backend_data={:p}",
2673 view.backend_data
2674 );
2675 }
2676 if ret != NROS_RMW_RET_OK {
2677 return Err(error_from_ret(ret));
2678 }
2679 if view.backend_data.is_null() {
2680 return Err(TransportError::ConnectionFailed);
2681 }
2682 session.backend_data = view.backend_data;
2683 session.qos_policies = read_supported_qos_policies(vtable, &mut view);
2684 Ok(session)
2685 }
2686}
2687
2688/// Ask the registered backend which QoS policies it honours (issue 1329).
2689///
2690/// A NULL slot, a non-OK return, or a mask carrying bits this build has no
2691/// name for all resolve to what the backend has actually established, which is
2692/// nothing above the bits it named. See the slot's header block for why the
2693/// absence is `NONE` and not the union it replaced.
2694fn read_supported_qos_policies(
2695 vtable: &'static NrosRmwVtable,
2696 view: &mut NrosRmwSession,
2697) -> nros_rmw::QoSPolicyMask {
2698 let Some(ask) = vtable.supported_qos_policies else {
2699 // Once per session, not per entity: the creates that follow each fail
2700 // with `IncompatibleQos` naming their own policy, and a line per
2701 // entity would bury the one line that says why.
2702 nros_log::log_warn!(
2703 nros_log::get_logger("nros_rmw_cffi"),
2704 "the registered backend fills no `supported_qos_policies` slot, so it has \
2705 declared no QoS policy it honours. Every entity stating a policy will be \
2706 refused with IncompatibleQos. Fill the slot in the backend's vtable."
2707 );
2708 return nros_rmw::QoSPolicyMask::NONE;
2709 };
2710 let mut mask: u32 = 0;
2711 // SAFETY: `view` describes the session just created, and the slot is one
2712 // the registered backend installed.
2713 let rc = unsafe { ask(view as *const NrosRmwSession, &mut mask) };
2714 if rc != NROS_RMW_RET_OK {
2715 nros_log::log_warn!(
2716 nros_log::get_logger("nros_rmw_cffi"),
2717 "the backend's `supported_qos_policies` returned {rc}; treating it as \
2718 'honours nothing'."
2719 );
2720 return nros_rmw::QoSPolicyMask::NONE;
2721 }
2722 // A bit outside the vocabulary this build knows is dropped rather than
2723 // trusted: it can only come from a backend built against a LATER header,
2724 // and admitting an unknown policy is the over-claim this slot exists to
2725 // end.
2726 nros_rmw::QoSPolicyMask(mask & QOS_POLICY_ALL)
2727}
2728
2729/// The C `NROS_RMW_QOS_POLICY_*` macros and `nros_rmw::QoSPolicyMask` are one
2730/// vocabulary written twice — the hand-mirror class (issue 0160), and this one
2731/// decides whether an application's entity is created at all. A backend
2732/// setting bit 7 and the runtime reading bit 7 as a different policy is a
2733/// wrong ACCEPTANCE, which is silent, so the agreement is asserted at compile
2734/// time here rather than trusted.
2735///
2736/// `check-qos-mask-derivation` checks the same pair without a build, for the
2737/// fast lane; this is the one that cannot be skipped by a target that does not
2738/// run gates.
2739const _: () = {
2740 use nros_rmw::QoSPolicyMask as M;
2741 assert!(NROS_RMW_QOS_POLICY_RELIABILITY as u32 == M::RELIABILITY.0);
2742 assert!(NROS_RMW_QOS_POLICY_DURABILITY_VOLATILE as u32 == M::DURABILITY_VOLATILE.0);
2743 assert!(
2744 NROS_RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL as u32 == M::DURABILITY_TRANSIENT_LOCAL.0
2745 );
2746 assert!(NROS_RMW_QOS_POLICY_HISTORY as u32 == M::HISTORY.0);
2747 assert!(NROS_RMW_QOS_POLICY_DEPTH as u32 == M::DEPTH.0);
2748 assert!(NROS_RMW_QOS_POLICY_DEADLINE as u32 == M::DEADLINE.0);
2749 assert!(NROS_RMW_QOS_POLICY_LIFESPAN as u32 == M::LIFESPAN.0);
2750 assert!(NROS_RMW_QOS_POLICY_LIVELINESS_AUTOMATIC as u32 == M::LIVELINESS_AUTOMATIC.0);
2751 assert!(
2752 NROS_RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC as u32 == M::LIVELINESS_MANUAL_BY_TOPIC.0
2753 );
2754 assert!(NROS_RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_NODE as u32 == M::LIVELINESS_MANUAL_BY_NODE.0);
2755 assert!(NROS_RMW_QOS_POLICY_LIVELINESS_LEASE as u32 == M::LIVELINESS_LEASE.0);
2756 assert!(
2757 NROS_RMW_QOS_POLICY_AVOID_ROS_NAMESPACE_CONVENTIONS as u32
2758 == M::AVOID_ROS_NAMESPACE_CONVENTIONS.0
2759 );
2760 assert!(NROS_RMW_QOS_POLICY_NONE as u32 == M::NONE.0);
2761 assert!(NROS_RMW_QOS_POLICY_CORE as u32 == M::CORE.0);
2762};
2763
2764/// Every policy bit the C ABI names, as one mask.
2765///
2766/// Derived from the generated constants rather than written as a literal, so a
2767/// policy added to `rmw_entity.h` joins it with no edit here.
2768const QOS_POLICY_ALL: u32 = (NROS_RMW_QOS_POLICY_RELIABILITY
2769 | NROS_RMW_QOS_POLICY_DURABILITY_VOLATILE
2770 | NROS_RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL
2771 | NROS_RMW_QOS_POLICY_HISTORY
2772 | NROS_RMW_QOS_POLICY_DEPTH
2773 | NROS_RMW_QOS_POLICY_DEADLINE
2774 | NROS_RMW_QOS_POLICY_LIFESPAN
2775 | NROS_RMW_QOS_POLICY_LIVELINESS_AUTOMATIC
2776 | NROS_RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC
2777 | NROS_RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_NODE
2778 | NROS_RMW_QOS_POLICY_LIVELINESS_LEASE
2779 | NROS_RMW_QOS_POLICY_AVOID_ROS_NAMESPACE_CONVENTIONS) as u32;
2780
2781/// Report a QoS DOWNGRADE — the granted profile differing from the requested
2782/// one — once per entity, at creation.
2783///
2784/// Issue 0823 gave the runtime the ability to READ the granted QoS. This is the
2785/// half that makes it a diagnostic. Silence from a QoS mismatch is
2786/// indistinguishable from a topic-name typo, a domain split (issue 0801) and a
2787/// discovery failure (issue 0803); all three were run to ground this month and
2788/// each cost hours precisely because nothing separated them. A line naming the
2789/// field that changed separates this one in a sentence.
2790///
2791/// Only a DIFFERENCE is reported. Equality is the common case and printing it
2792/// would bury the signal — the same reason `nros_platform_task_init` only warns
2793/// when the kernel disagreed with the priority it was asked for.
2794///
2795/// Best-effort by construction: a backend with no read-back slot reports
2796/// nothing, which is correct rather than missing (zenoh-pico's QoS is
2797/// per-message flags with no negotiation to read).
2798#[cfg(feature = "alloc")]
2799fn report_qos_downgrade(kind: &str, name: &str, requested: &NrosRmwQos, granted: &NrosRmwQos) {
2800 // The generated constants are `i32` (bindgen) while the struct field is
2801 // `u8`; compare in the constants' type rather than casting them down.
2802 fn reliability(v: u8) -> &'static str {
2803 match v as i32 {
2804 NROS_RMW_RELIABILITY_RELIABLE => "RELIABLE",
2805 NROS_RMW_RELIABILITY_BEST_EFFORT => "BEST_EFFORT",
2806 _ => "?",
2807 }
2808 }
2809 fn durability(v: u8) -> &'static str {
2810 match v as i32 {
2811 NROS_RMW_DURABILITY_TRANSIENT_LOCAL => "TRANSIENT_LOCAL",
2812 NROS_RMW_DURABILITY_VOLATILE => "VOLATILE",
2813 _ => "?",
2814 }
2815 }
2816 // An `UNKNOWN` field is the backend saying it could not determine the
2817 // policy. Comparing it against the request would report every unreportable
2818 // policy as a downgrade, which is the inverse of the old bug and just as
2819 // wrong: silence is not a grant, and neither is it a change.
2820 if requested.reliability != granted.reliability
2821 && !is_unknown(granted.reliability, NROS_RMW_RELIABILITY_UNKNOWN)
2822 {
2823 nros_log::log_warn!(
2824 nros_log::get_logger("nros_rmw_cffi"),
2825 "{kind} `{name}`: asked for reliability {} and the backend granted {}. A RELIABLE \
2826 reader does not match a BEST_EFFORT writer, so this is the usual reason a pair \
2827 goes silent.",
2828 reliability(requested.reliability),
2829 reliability(granted.reliability)
2830 );
2831 }
2832 if requested.durability != granted.durability
2833 && !is_unknown(granted.durability, NROS_RMW_DURABILITY_UNKNOWN)
2834 {
2835 nros_log::log_warn!(
2836 nros_log::get_logger("nros_rmw_cffi"),
2837 "{kind} `{name}`: asked for durability {} and the backend granted {}.",
2838 durability(requested.durability),
2839 durability(granted.durability)
2840 );
2841 }
2842 if requested.depth != granted.depth && granted.depth != 0 {
2843 // Issue 2815 -- ONE warning per distinct (requested, granted) depth
2844 // pair, the rest at debug. A depth clamp is the backend's fixed
2845 // ceiling, so every endpoint asking the same depth gets the same
2846 // answer: an image serving the parameter services asks 1000 for each
2847 // of their twelve endpoints and zenoh-pico grants 4, which was twelve
2848 // identical warnings in the first 80 ms of boot -- the burst a
2849 // Nucleo-F767ZI faulted inside. Reliability and durability above stay
2850 // per entity: they are what silences a pair, and they are rare.
2851 if first_depth_downgrade(requested.depth, granted.depth) {
2852 nros_log::log_warn!(
2853 nros_log::get_logger("nros_rmw_cffi"),
2854 "{kind} `{name}`: asked for history depth {} and the backend granted {}. \
2855 Further endpoints granted the same are logged at debug.",
2856 requested.depth,
2857 granted.depth
2858 );
2859 } else {
2860 nros_log::log_debug!(
2861 nros_log::get_logger("nros_rmw_cffi"),
2862 "{kind} `{name}`: asked for history depth {} and the backend granted {}.",
2863 requested.depth,
2864 granted.depth
2865 );
2866 }
2867 }
2868}
2869
2870/// Issue 2815 -- whether this (requested, granted) depth pair is the first of
2871/// its kind since the last DIFFERENT pair, i.e. whether it earns a warning.
2872///
2873/// One word holds the last pair warned about. Load and store only, no
2874/// read-modify-write, because thumbv6m has no atomic compare-and-swap; two
2875/// threads racing on a new pair can each warn once, which is harmless. A
2876/// workload alternating between two pairs warns on every change, which is
2877/// what it should do: a new pair is new information.
2878#[cfg(feature = "alloc")]
2879fn first_depth_downgrade(requested: u16, granted: u16) -> bool {
2880 static LAST_WARNED: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
2881 first_depth_downgrade_in(&LAST_WARNED, requested, granted)
2882}
2883
2884/// [`first_depth_downgrade`] over a caller's word, so a test owns its own.
2885#[cfg(feature = "alloc")]
2886fn first_depth_downgrade_in(
2887 last: &core::sync::atomic::AtomicU32,
2888 requested: u16,
2889 granted: u16,
2890) -> bool {
2891 let key = (u32::from(requested) << 16) | u32::from(granted);
2892 if last.load(Ordering::Relaxed) == key {
2893 return false;
2894 }
2895 last.store(key, Ordering::Relaxed);
2896 true
2897}
2898
2899/// The C-ABI spelling of [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every policy an
2900/// ABSENCE.
2901///
2902/// This is what a `*_get_actual_qos` out-struct is pre-loaded with, so a field
2903/// the backend does not overwrite reads as "I cannot report this" rather than
2904/// as a confident grant. Built from the Rust preset rather than restated, so
2905/// the two cannot drift.
2906fn qos_unknown_c() -> NrosRmwQos {
2907 // The conversion's only failure is `depth > u16::MAX`, and the preset's
2908 // depth is 0.
2909 NrosRmwQos::try_from(QoSProfile::QOS_PROFILE_UNKNOWN)
2910 .expect("QOS_PROFILE_UNKNOWN has depth 0 and therefore lowers")
2911}
2912
2913/// Is this policy value the C ABI's `*_UNKNOWN` sentinel?
2914///
2915/// Only `report_qos_downgrade` asks, and that is `alloc`-only (it logs), so
2916/// this carries the same gate rather than sitting dead in a `no_std` build.
2917#[cfg(feature = "alloc")]
2918fn is_unknown(field: u8, unknown: i32) -> bool {
2919 field as i32 == unknown
2920}
2921
2922/// Read the GRANTED QoS back off one entity.
2923///
2924/// The read-back is SIX slots — publisher, subscription, and the four
2925/// service/client directions — and every one of them is the same three steps:
2926/// pre-load the out-struct, call the slot, keep the answer.
2927/// `create_publisher` carried those three steps inline, and issue 1327 needed
2928/// four more copies of them — which is how the sizes-header mirror reached six
2929/// sites. One helper instead, generic over the entity type, since the slots
2930/// differ only in which handle they take.
2931///
2932/// **The pre-load is `UNKNOWN`, not the request.** It was the request until
2933/// this phase, and that inverted the slot's own contract: `rmw_vtable.h` says a
2934/// backend writes `*_UNKNOWN` for a policy it cannot determine, so a field
2935/// nobody overwrote read back as GRANTED — a caller comparing request against
2936/// answer saw agreement precisely where the backend had said nothing. Cyclone's
2937/// `qos_from_dds` overwrites exactly the fields whose `dds_qget_*` succeeds, so
2938/// the pre-load is the whole of the difference.
2939///
2940/// `None` means the backend has no read-back for this entity (NULL slot) or
2941/// declined this one (a non-OK return), which is a declared absence and not a
2942/// downgrade. Callers store [`qos_unknown_c`] for it — the same absence, spelled
2943/// per policy.
2944///
2945/// # Safety
2946/// `entity` must point at a live view of an entity this session created, and
2947/// `slot` must be a slot the registered vtable installed for that entity type.
2948unsafe fn read_granted_qos<E>(
2949 entity: *const E,
2950 slot: Option<unsafe extern "C" fn(*const E, *mut NrosRmwQos) -> NrosRmwRet>,
2951) -> Option<NrosRmwQos> {
2952 let read = slot?;
2953 let mut granted = qos_unknown_c();
2954 // SAFETY: the caller's contract, above.
2955 if unsafe { read(entity, &mut granted) } != NROS_RMW_RET_OK {
2956 return None;
2957 }
2958 Some(granted)
2959}
2960
2961/// [`read_granted_qos`] plus the diagnostic line, and the granted profile for
2962/// the caller to RETAIN.
2963///
2964/// Returns what the entity will actually run: the backend's answer where it
2965/// has one, and [`qos_unknown_c`] where it does not — never the request, which
2966/// is the value this accessor exists to be different from.
2967///
2968/// # Safety
2969/// As [`read_granted_qos`].
2970unsafe fn granted_qos_of<E>(
2971 kind: &str,
2972 name: &str,
2973 requested: &NrosRmwQos,
2974 entity: *const E,
2975 slot: Option<unsafe extern "C" fn(*const E, *mut NrosRmwQos) -> NrosRmwRet>,
2976) -> NrosRmwQos {
2977 // SAFETY: the caller's contract.
2978 let Some(granted) = (unsafe { read_granted_qos(entity, slot) }) else {
2979 return qos_unknown_c();
2980 };
2981 #[cfg(feature = "alloc")]
2982 report_qos_downgrade(kind, name, requested, &granted);
2983 #[cfg(not(feature = "alloc"))]
2984 {
2985 let _ = (kind, name, requested);
2986 }
2987 granted
2988}
2989
2990impl Session for CffiSession {
2991 /// The backend is chosen at run time here, so the trait's compile-time
2992 /// default would be a guess. Ask the vtable, and answer `None` when the
2993 /// slot is NULL: a backend that installed no body has not said what it
2994 /// speaks, which is the contract `rmw_vtable.h` states for the slot.
2995 ///
2996 /// A forwarder onto the inherent
2997 /// [`CffiSession::serialization_format`](CffiSession::serialization_format),
2998 /// which has always read the slot that way. Until phase-467 Q2 this impl
2999 /// `unwrap_or`-ed the trait constant instead, so the one session that
3000 /// cannot know its format at compile time was the one that guessed.
3001 fn serialization_format(&self) -> Option<&'static str> {
3002 CffiSession::serialization_format(self)
3003 }
3004
3005 /// The vtable's answer, or the registered name — never the trait's `None`
3006 /// default, which is right only for a backend known at compile time.
3007 fn implementation_identifier(&self) -> Option<&'static str> {
3008 CffiSession::implementation_identifier(self)
3009 }
3010
3011 /// phase-461 W2 / issue 1352 -- this session FORWARDS over a C vtable,
3012 /// and the vtable has no slot that carries a ring.
3013 ///
3014 /// `create_service` reaches the backend through
3015 /// `rmw_vtable.create_service` (`packages/core/nros-rmw-abi/include/nros/`),
3016 /// whose arguments are the node, the type support, the name, the domain
3017 /// and the QoS. A caller-owned inbox is four more words, so accepting one
3018 /// here means a second ABI slot and its bindgen regeneration -- not a
3019 /// default this session can answer `true` to on the backend's behalf. It
3020 /// stays `false` until that slot exists, which is the one thing standing
3021 /// between `nros-node`'s `PARAM_INBOX` and the zenoh ring that would hold
3022 /// it (the zenoh side has been caller-visible since W1).
3023 ///
3024 /// Deliberately NOT a runtime question of the vtable: the const is what
3025 /// lets the caller refuse at COMPILE time, and a session that answered
3026 /// from a vtable installed later could only refuse at boot.
3027 const SUPPORTS_CALLER_INBOX: bool = false;
3028
3029 type Error = TransportError;
3030 type PublisherHandle = CffiPublisher;
3031 type SubscriptionHandle = CffiSubscription;
3032 type ServiceHandle = CffiService;
3033 type ClientHandle = CffiClient;
3034
3035 fn create_publisher(
3036 &mut self,
3037 topic: &TopicInfo,
3038 qos: QoSProfile,
3039 ) -> Result<CffiPublisher, TransportError> {
3040 let mut hash_buf = [0u8; HASH_BUF_LEN];
3041 let hash_ptr = to_c_str(topic.type_hash, &mut hash_buf);
3042 // issue 1973 — resolve BEST_AVAILABLE here, the one seam every
3043 // backend's create passes through (`nros-node`'s session IS this
3044 // type), so no backend's create slot ever receives the request
3045 // value and its `*_get_actual_qos` reports the concrete choice. The
3046 // graph comes from the backend's own `get_*_info_by_topic` slot; a
3047 // NULL slot (XRCE, uORB) is "nothing discovered" — upstream's
3048 // documented default, see `QoSProfile::resolve_best_available`.
3049 let qos = nros_rmw::resolve_best_available_on(
3050 self,
3051 nros_rmw::BestAvailableRole::Publisher,
3052 topic.name,
3053 qos,
3054 );
3055 let qos_struct = NrosRmwQos::try_from(qos)?;
3056 // phase-301 (issue 0240) — the express hint travels in the options
3057 // struct, not the QoS profile. Either surface wins: the QoS profile
3058 // field (language APIs) or `TopicInfo::with_tx_express` (direct RMW).
3059 let options = rmw_publisher_options_t {
3060 tx_express: (topic.tx_express || qos.tx_express) as u8,
3061 _reserved: [0u8; 7],
3062 };
3063
3064 let mut pub_state = CffiPublisher {
3065 vtable: self.vtable,
3066 topic_name_buf: [0u8; NAME_BUF_LEN],
3067 type_name_buf: [0u8; NAME_BUF_LEN],
3068 qos: qos_struct,
3069 // Overwritten with the backend's answer below, once the entity
3070 // exists. An absence until then, never the request.
3071 actual_qos: qos_unknown_c(),
3072 can_loan_messages: false,
3073 backend_data: core::ptr::null_mut(),
3074 polled_events: [const { Cell::new(None) }; PUB_EVENT_KINDS.len()],
3075 polling_events: Cell::new(false),
3076 };
3077 let topic_ptr = to_c_str(topic.name, &mut pub_state.topic_name_buf);
3078 let type_ptr = to_c_str(topic.type_name, &mut pub_state.type_name_buf);
3079
3080 let mut view = NrosRmwPublisher {
3081 topic_name: topic_ptr,
3082 type_name: type_ptr,
3083 qos: qos_struct,
3084 can_loan_messages: false,
3085 _reserved: [0u8; 7],
3086 backend_data: core::ptr::null_mut(),
3087 };
3088 // Phase 376 W5/B1 — the entity is created ON ITS NODE. `session_view`
3089 // must outlive the call: `node_view` points the node's `session` field
3090 // at it.
3091 let mut session_view = self.make_view();
3092 let node_view = self.node_slot(topic.node_name, topic.namespace, &mut session_view)?;
3093 let ret = unsafe {
3094 (self
3095 .vtable
3096 .create_publisher
3097 .expect("rmw vtable: create_publisher"))(
3098 &node_view,
3099 // phase-406 W1 — the identity as ONE argument, in upstream's
3100 // position. Built here on the stack: it borrows the same two
3101 // pointers the two loose arguments did, so nothing changed about
3102 // their lifetime, only about how many arguments carry them.
3103 &generated::rmw_message_type_support_t {
3104 type_name: type_ptr,
3105 type_hash: hash_ptr,
3106 },
3107 topic_ptr,
3108 topic.domain_id,
3109 &qos_struct,
3110 &options,
3111 &mut view,
3112 )
3113 };
3114 if ret != NROS_RMW_RET_OK {
3115 return Err(error_from_ret(ret));
3116 }
3117 if view.backend_data.is_null() {
3118 return Err(TransportError::PublisherCreationFailed);
3119 }
3120 pub_state.backend_data = view.backend_data;
3121 // issue 0814 — DERIVED from the vtable, never merely declared.
3122 //
3123 // The field is the same fact as `borrow_loaned_message` being
3124 // non-NULL — the header defines it as "the backend exposes the
3125 // loan_publish / commit_publish primitive" — and a fact with two
3126 // spellings drifts. It had drifted BOTH ways at once:
3127 //
3128 // * UNDER-claim. Nothing wrote `true` anywhere outside a test.
3129 // A C backend writes the field, but `RustBackendAdapter`'s
3130 // generic `create_publisher_trampoline` cannot: it is generic
3131 // over the Session and does not know which vtable it was
3132 // registered under, so it writes only `backend_data`
3133 // (`rust_adapter.rs:541-548`) and leaves the runtime's pre-zero
3134 // (`:1951`) standing. That is not an oversight to fix in the
3135 // trampoline; it is structural. So zenoh built with `lending` —
3136 // whose vtable DOES fill all three loan slots
3137 // (`nros-rmw-zenoh/src/lib.rs:427-432`) and whose loans work —
3138 // reported that it cannot loan.
3139 // * OVER-claim. A backend may write `true` with the slot NULL and
3140 // be believed; the test stub at `:4390` does exactly that.
3141 //
3142 // Neither was doing damage YET, because nothing branches on the
3143 // field (every read is a copy into the C view or an accessor) —
3144 // dispatch keys on the slot at `:2760`. The damage is scheduled:
3145 // the moment anyone implements the branch the header promises,
3146 // zenoh's working loan path silently drops to the copy fallback.
3147 //
3148 // A backend that must refuse a loan for a PARTICULAR entity has not
3149 // lost anything — it returns `NROS_RMW_RET_UNSUPPORTED` from
3150 // `borrow_loaned_message` and `try_lend_slot` surfaces that as an
3151 // error. The per-entity answer belongs on the call, which is
3152 // consulted; not on a flag, which is not.
3153 pub_state.can_loan_messages = pub_state.vtable.borrow_loaned_message.is_some();
3154 // phase-393 W1 — say so when the backend granted something else, and
3155 // RETAIN the answer: `actual_qos()` is the accessor upstream's
3156 // `rmw_publisher_get_actual_qos` is, and the read-back used to be
3157 // logged and dropped, so nobody could ask.
3158 {
3159 let mut v = pub_state.make_view();
3160 let slot = pub_state.vtable.publisher_get_actual_qos;
3161 // SAFETY: the entity was created above and `v` describes it.
3162 pub_state.actual_qos =
3163 unsafe { granted_qos_of("publisher", topic.name, &qos_struct, &v, slot) };
3164 let _ = &mut v;
3165 }
3166 Ok(pub_state)
3167 }
3168
3169 fn create_subscription(
3170 &mut self,
3171 topic: &TopicInfo,
3172 qos: QoSProfile,
3173 ) -> Result<CffiSubscription, TransportError> {
3174 let mut hash_buf = [0u8; HASH_BUF_LEN];
3175 let hash_ptr = to_c_str(topic.type_hash, &mut hash_buf);
3176 // issue 1973 — see `create_publisher`.
3177 let qos = nros_rmw::resolve_best_available_on(
3178 self,
3179 nros_rmw::BestAvailableRole::Subscription,
3180 topic.name,
3181 qos,
3182 );
3183 let qos_struct = NrosRmwQos::try_from(qos)?;
3184 // Phase 231 (RFC-0038) / phase-301 (issue 0240) — the receive-buffer
3185 // size hint travels in the options struct so a size-classing backend
3186 // can route its receive storage. A hint, not a policy: oversize
3187 // saturates.
3188 let options = rmw_subscription_options_t {
3189 rx_buffer_hint: topic.rx_buffer_hint.min(u32::MAX as usize) as u32,
3190 // phase-519 W3 — the declared arrival rate (RFC-0074).
3191 arrival_rate_mhz: topic.arrival_rate_mhz,
3192 };
3193
3194 let mut sub_state = CffiSubscription {
3195 vtable: self.vtable,
3196 topic_name_buf: [0u8; NAME_BUF_LEN],
3197 type_name_buf: [0u8; NAME_BUF_LEN],
3198 qos: qos_struct,
3199 actual_qos: qos_unknown_c(),
3200 can_loan_messages: false,
3201 backend_data: core::ptr::null_mut(),
3202 supports_in_place: false,
3203 pending_status: None,
3204 refused_len: None,
3205 polled_events: [const { Cell::new(None) }; SUB_EVENT_KINDS.len()],
3206 polling_events: Cell::new(false),
3207 entity_waker: WakerSlot::new(),
3208 };
3209 let topic_ptr = to_c_str(topic.name, &mut sub_state.topic_name_buf);
3210 let type_ptr = to_c_str(topic.type_name, &mut sub_state.type_name_buf);
3211
3212 let mut view = NrosRmwSubscription {
3213 topic_name: topic_ptr,
3214 type_name: type_ptr,
3215 qos: qos_struct,
3216 can_loan_messages: false,
3217 _reserved: [0u8; 7],
3218 backend_data: core::ptr::null_mut(),
3219 };
3220 // Phase 376 W5/B1 — the entity is created ON ITS NODE. `session_view`
3221 // must outlive the call: `node_view` points the node's `session` field
3222 // at it.
3223 let mut session_view = self.make_view();
3224 let node_view = self.node_slot(topic.node_name, topic.namespace, &mut session_view)?;
3225 let ret = unsafe {
3226 (self
3227 .vtable
3228 .create_subscription
3229 .expect("rmw vtable: create_subscription"))(
3230 &node_view,
3231 // phase-406 W1 — the identity as ONE argument, in upstream's
3232 // position. Built here on the stack: it borrows the same two
3233 // pointers the two loose arguments did, so nothing changed about
3234 // their lifetime, only about how many arguments carry them.
3235 &generated::rmw_message_type_support_t {
3236 type_name: type_ptr,
3237 type_hash: hash_ptr,
3238 },
3239 topic_ptr,
3240 topic.domain_id,
3241 &qos_struct,
3242 &options,
3243 &mut view,
3244 )
3245 };
3246 if ret != NROS_RMW_RET_OK {
3247 return Err(error_from_ret(ret));
3248 }
3249 if view.backend_data.is_null() {
3250 return Err(TransportError::SubscriberCreationFailed);
3251 }
3252 sub_state.backend_data = view.backend_data;
3253 // issue 0814 — the receive-side twin, derived from its own slot for
3254 // the same reason as the publisher above. `take_loaned_message` is
3255 // NULL in every backend we ship, so this is `false` everywhere today
3256 // — but now it is false BECAUSE no backend fills the slot, which is
3257 // checkable, rather than because nobody remembered to write it.
3258 sub_state.can_loan_messages = sub_state.vtable.take_loaned_message.is_some();
3259 // The SIXTH read-back, and the one that was never dispatched. Issue
3260 // 1327 wired the publisher and the four service/client directions;
3261 // `subscription_get_actual_qos` was filled by cyclonedds and uORB and
3262 // called by nobody, so a subscription — the entity whose reliability
3263 // downgrade is the classic "why is nothing arriving" — was the one
3264 // that could not answer.
3265 {
3266 let mut v = sub_state.make_view();
3267 let slot = sub_state.vtable.subscription_get_actual_qos;
3268 // SAFETY: the entity was created above and `v` describes it.
3269 sub_state.actual_qos =
3270 unsafe { granted_qos_of("subscription", topic.name, &qos_struct, &v, slot) };
3271 let _ = &mut v;
3272 }
3273 // Phase 231 (RFC-0038) — cache the in-place capability once.
3274 // The capability is the CONJUNCTION of the probe and the slot that
3275 // would serve it (issue 0781). The probe alone was the whole answer,
3276 // so a backend answering true with a NULL `process_raw_in_place` chose
3277 // the in-place dispatch path and then failed every take; and the slot
3278 // alone cannot answer, because `RustBackendAdapter::<R>::VTABLE` is a
3279 // `const` that installs `process_raw_in_place` for every `R` while the
3280 // Rust-side answer is a runtime method (zenoh true, metadata false
3281 // behind the same nullity). Neither mechanism subsumes the other.
3282 sub_state.supports_in_place = sub_state.vtable.process_raw_in_place.is_some()
3283 && match sub_state.vtable.subscription_supports_in_place {
3284 Some(f) => {
3285 let mut v = sub_state.make_view();
3286 // Phase 376 W3.d step A — a backend that FAILS the probe is not
3287 // one that supports in-place: both answer false, but only one of
3288 // them is an error, and the status now says which.
3289 let mut supports = false;
3290 let rc = unsafe { f(&mut v, &mut supports) };
3291 static SITE: StatusSite = StatusSite::new("subscription_supports_in_place");
3292 status_ok(rc, &SITE) && supports
3293 }
3294 None => false,
3295 };
3296 Ok(sub_state)
3297 }
3298
3299 fn create_service(
3300 &mut self,
3301 service: &ServiceInfo,
3302 qos: QoSProfile,
3303 ) -> Result<CffiService, TransportError> {
3304 // issue 1973 — see `create_publisher`.
3305 let qos = nros_rmw::resolve_best_available_on(
3306 self,
3307 nros_rmw::BestAvailableRole::Service,
3308 service.name,
3309 qos,
3310 );
3311 let qos_struct = NrosRmwQos::try_from(qos)?;
3312 let mut hash_buf = [0u8; HASH_BUF_LEN];
3313 let hash_ptr = to_c_str(service.type_hash, &mut hash_buf);
3314
3315 let mut srv_state = CffiService {
3316 vtable: self.vtable,
3317 service_name_buf: [0u8; NAME_BUF_LEN],
3318 type_name_buf: [0u8; NAME_BUF_LEN],
3319 backend_data: core::ptr::null_mut(),
3320 // Both overwritten with the backend's answers below, once the
3321 // entity exists. An absence until then, never the request.
3322 request_qos: qos_unknown_c(),
3323 response_qos: qos_unknown_c(),
3324 refused_len: None,
3325 entity_waker: WakerSlot::new(),
3326 request_info: ServiceRequestInfo::NOT_REPORTED,
3327 };
3328 let svc_ptr = to_c_str(service.name, &mut srv_state.service_name_buf);
3329 let type_ptr = to_c_str(service.type_name, &mut srv_state.type_name_buf);
3330
3331 let mut view = NrosRmwService {
3332 service_name: svc_ptr,
3333 type_name: type_ptr,
3334 _reserved: [0u8; 8],
3335 backend_data: core::ptr::null_mut(),
3336 };
3337 // Phase 376 W5/B1 — see `create_publisher`.
3338 let mut session_view = self.make_view();
3339 let node_view = self.node_slot(service.node_name, service.namespace, &mut session_view)?;
3340 let ret = unsafe {
3341 (self
3342 .vtable
3343 .create_service
3344 .expect("rmw vtable: create_service"))(
3345 &node_view,
3346 // phase-406 W1 — see the publisher site. A SERVICE type support
3347 // is its own type: upstream keeps `rosidl_service_type_support_t`
3348 // distinct from the message form, and collapsing them here would
3349 // let a service type be passed where a message type is required
3350 // with no diagnostic.
3351 &generated::rmw_service_type_support_t {
3352 type_name: type_ptr,
3353 type_hash: hash_ptr,
3354 },
3355 svc_ptr,
3356 service.domain_id,
3357 &qos_struct,
3358 &mut view,
3359 )
3360 };
3361 if ret != NROS_RMW_RET_OK {
3362 return Err(error_from_ret(ret));
3363 }
3364 if view.backend_data.is_null() {
3365 return Err(TransportError::ServiceServerCreationFailed);
3366 }
3367 srv_state.backend_data = view.backend_data;
3368 // issue 1327 — the service half of the publisher site above.
3369 //
3370 // `create_service` takes ONE profile and builds TWO endpoints from it,
3371 // and `rmw_service_t` has no `qos` field, so the granted per-direction
3372 // profile is observable through these slots and nowhere else. Both are
3373 // read: the request endpoint and the response endpoint negotiate
3374 // against different peers and may be granted different things.
3375 {
3376 let mut v = srv_state.make_view();
3377 let req = srv_state.vtable.service_request_subscription_get_actual_qos;
3378 let resp = srv_state.vtable.service_response_publisher_get_actual_qos;
3379 // SAFETY: the entity was created above and `v` describes it.
3380 unsafe {
3381 srv_state.request_qos = granted_qos_of(
3382 "service request subscription",
3383 service.name,
3384 &qos_struct,
3385 &v,
3386 req,
3387 );
3388 srv_state.response_qos = granted_qos_of(
3389 "service response publisher",
3390 service.name,
3391 &qos_struct,
3392 &v,
3393 resp,
3394 );
3395 }
3396 let _ = &mut v;
3397 }
3398 Ok(srv_state)
3399 }
3400
3401 fn create_client(
3402 &mut self,
3403 service: &ServiceInfo,
3404 qos: QoSProfile,
3405 ) -> Result<CffiClient, TransportError> {
3406 // issue 1973 — see `create_publisher`.
3407 let qos = nros_rmw::resolve_best_available_on(
3408 self,
3409 nros_rmw::BestAvailableRole::Service,
3410 service.name,
3411 qos,
3412 );
3413 let qos_struct = NrosRmwQos::try_from(qos)?;
3414 let mut hash_buf = [0u8; HASH_BUF_LEN];
3415 let hash_ptr = to_c_str(service.type_hash, &mut hash_buf);
3416
3417 let mut cli_state = CffiClient {
3418 vtable: self.vtable,
3419 service_name_buf: [0u8; NAME_BUF_LEN],
3420 type_name_buf: [0u8; NAME_BUF_LEN],
3421 backend_data: core::ptr::null_mut(),
3422 // Both overwritten with the backend's answers below, once the
3423 // entity exists. An absence until then, never the request.
3424 request_qos: qos_unknown_c(),
3425 response_qos: qos_unknown_c(),
3426 refused_len: None,
3427 entity_waker: WakerSlot::new(),
3428 response_info: ServiceRequestInfo::NOT_REPORTED,
3429 };
3430 let svc_ptr = to_c_str(service.name, &mut cli_state.service_name_buf);
3431 let type_ptr = to_c_str(service.type_name, &mut cli_state.type_name_buf);
3432
3433 let mut view = NrosRmwClient {
3434 service_name: svc_ptr,
3435 type_name: type_ptr,
3436 _reserved: [0u8; 8],
3437 backend_data: core::ptr::null_mut(),
3438 };
3439 // Phase 376 W5/B1 — see `create_publisher`.
3440 let mut session_view = self.make_view();
3441 let node_view = self.node_slot(service.node_name, service.namespace, &mut session_view)?;
3442 let ret = unsafe {
3443 (self
3444 .vtable
3445 .create_client
3446 .expect("rmw vtable: create_client"))(
3447 &node_view,
3448 // phase-406 W1 — see the publisher site. A SERVICE type support
3449 // is its own type: upstream keeps `rosidl_service_type_support_t`
3450 // distinct from the message form, and collapsing them here would
3451 // let a service type be passed where a message type is required
3452 // with no diagnostic.
3453 &generated::rmw_service_type_support_t {
3454 type_name: type_ptr,
3455 type_hash: hash_ptr,
3456 },
3457 svc_ptr,
3458 service.domain_id,
3459 &qos_struct,
3460 &mut view,
3461 )
3462 };
3463 if ret != NROS_RMW_RET_OK {
3464 return Err(error_from_ret(ret));
3465 }
3466 if view.backend_data.is_null() {
3467 return Err(TransportError::ServiceClientCreationFailed);
3468 }
3469 cli_state.backend_data = view.backend_data;
3470 // issue 1327 — the client half; see `create_service` for why both
3471 // directions are read.
3472 {
3473 let mut v = cli_state.make_view();
3474 let req = cli_state.vtable.client_request_publisher_get_actual_qos;
3475 let resp = cli_state.vtable.client_response_subscription_get_actual_qos;
3476 // SAFETY: the entity was created above and `v` describes it.
3477 unsafe {
3478 cli_state.request_qos = granted_qos_of(
3479 "client request publisher",
3480 service.name,
3481 &qos_struct,
3482 &v,
3483 req,
3484 );
3485 cli_state.response_qos = granted_qos_of(
3486 "client response subscription",
3487 service.name,
3488 &qos_struct,
3489 &v,
3490 resp,
3491 );
3492 }
3493 let _ = &mut v;
3494 }
3495 Ok(cli_state)
3496 }
3497
3498 fn close(&mut self) -> Result<(), TransportError> {
3499 if self.backend_data.is_null() {
3500 return Ok(());
3501 }
3502 // Phase 376 W5/B1 — hand the node slots back BEFORE the backend loses
3503 // its session state. A static table that is never reclaimed would let a
3504 // long-running image that opens and closes sessions exhaust it.
3505 let mut view = self.make_view();
3506 release_session_nodes(self.backend_data as usize, self.vtable, &mut view);
3507 let ret = unsafe {
3508 (self
3509 .vtable
3510 .destroy_session
3511 .expect("rmw vtable: destroy_session"))(&mut view)
3512 };
3513 if ret != NROS_RMW_RET_OK {
3514 return Err(error_from_ret(ret));
3515 }
3516 self.backend_data = core::ptr::null_mut();
3517 Ok(())
3518 }
3519
3520 fn drive_io(&mut self, timeout_ms: i32) -> Result<(), TransportError> {
3521 let mut view = self.make_view();
3522 let ret =
3523 unsafe { (self.vtable.drive_io.expect("rmw vtable: drive_io"))(&mut view, timeout_ms) };
3524 if ret != NROS_RMW_RET_OK {
3525 return Err(error_from_ret(ret));
3526 }
3527 Ok(())
3528 }
3529
3530 fn next_deadline_ms(&self) -> Option<u32> {
3531 let f = self.vtable.next_deadline_ms?;
3532 // SAFETY: build a transient `&self`-only view of the session
3533 // fields the C side may inspect; matches the layout `make_view`
3534 // produces but doesn't require `&mut self`.
3535 let view = NrosRmwSession {
3536 node_name: self.node_name_buf.as_ptr().cast(),
3537 namespace_: self.namespace_buf.as_ptr().cast(),
3538 _reserved: [0u8; 8],
3539 backend_data: self.backend_data,
3540 };
3541 // Phase 376 W3.d step A — the trait returns `Option<u32>` and has no
3542 // error channel, so a FAILING probe maps to `None` here. That is the
3543 // same answer a quiet link gives, but it is now a decision rather than
3544 // the arithmetic of a negative sentinel — and the backend can at least
3545 // distinguish the two on its side of the seam.
3546 let mut out_ms: u32 = 0;
3547 let mut has_deadline = false;
3548 let ret = unsafe { f(&view as *const _, &mut out_ms, &mut has_deadline) };
3549 static SITE: StatusSite = StatusSite::new("next_deadline_ms");
3550 if !status_ok(ret, &SITE) || !has_deadline {
3551 return None;
3552 }
3553 Some(out_ms)
3554 }
3555
3556 unsafe fn set_wake_callback(
3557 &mut self,
3558 cb: Option<unsafe extern "C" fn(ctx: *mut core::ffi::c_void)>,
3559 ctx: *mut core::ffi::c_void,
3560 ) {
3561 let Some(f) = self.vtable.set_wake_callback else {
3562 return;
3563 };
3564 let mut view = NrosRmwSession {
3565 node_name: self.node_name_buf.as_ptr().cast(),
3566 namespace_: self.namespace_buf.as_ptr().cast(),
3567 _reserved: [0u8; 8],
3568 backend_data: self.backend_data,
3569 };
3570 // SAFETY: vtable trampoline owns the install/clear; result is
3571 // ignored — best-effort.
3572 let _ = unsafe { f(&mut view as *mut _, cb, ctx) };
3573 }
3574
3575 fn supports_wake_callback(&self) -> bool {
3576 // Phase 130.4 — the vtable slot's presence is the truthful
3577 // signal. Poll-only backends (XRCE-DDS-Client, current dust-DDS
3578 // shim) leave the slot NULL; only backends with an async wake
3579 // source fill it. Cyclone DOES fill it (`vtable.cpp:322`) and
3580 // backs it with a real `dds_set_listener` / `on_data_available`
3581 // firing on a Cyclone worker thread — this comment named it
3582 // poll-only long after that landed, which is misleading for
3583 // exactly the reader asking whether their lane gets async wakes.
3584 //
3585 // phase-521 W4 (RFC-0113 D4) — unless the backend states its
3586 // readiness: then the slot can be present on a session whose
3587 // transport has no notification (XRCE over a board's custom
3588 // transport, or over a stack with a descriptor instead), and only the
3589 // stated kind says whether an arrival will ever call it.
3590 if self.vtable.readiness_source.is_some() {
3591 return self.readiness_source() == nros_rmw::ReadinessSource::Notify;
3592 }
3593 self.vtable.set_wake_callback.is_some()
3594 }
3595
3596 /// phase-521 W3 (RFC-0113 D4) — forward to the backend's
3597 /// `readiness_source` slot. A NULL slot keeps the trait's inference from
3598 /// `set_wake_callback`'s presence; a slot that FAILS, or answers a kind
3599 /// this runtime does not know, reads as `None`, which the runtime refuses
3600 /// at open (RFC-0113 D5) rather than parking on a handle nobody vouched for.
3601 fn readiness_source(&self) -> nros_rmw::ReadinessSource {
3602 let Some(f) = self.vtable.readiness_source else {
3603 return if self.supports_wake_callback() {
3604 nros_rmw::ReadinessSource::Notify
3605 } else {
3606 nros_rmw::ReadinessSource::None
3607 };
3608 };
3609 let view = NrosRmwSession {
3610 node_name: self.node_name_buf.as_ptr().cast(),
3611 namespace_: self.namespace_buf.as_ptr().cast(),
3612 _reserved: [0u8; 8],
3613 backend_data: self.backend_data,
3614 };
3615 let mut kind: u8 = 0;
3616 let mut handle: i32 = -1;
3617 // SAFETY: a transient read-only view, as `next_deadline_ms` builds.
3618 let ret = unsafe { f(&view as *const _, &mut kind, &mut handle) };
3619 if ret != NROS_RMW_RET_OK {
3620 return nros_rmw::ReadinessSource::None;
3621 }
3622 match kind as i32 {
3623 generated::NROS_RMW_READINESS_NOTIFY => nros_rmw::ReadinessSource::Notify,
3624 generated::NROS_RMW_READINESS_WAITABLE if !handle.is_negative() => {
3625 nros_rmw::ReadinessSource::Waitable(handle)
3626 }
3627 _ => nros_rmw::ReadinessSource::None,
3628 }
3629 }
3630
3631 /// phase-467 Row 8 — forward to the backend's graph-change slot; NULL
3632 /// means UNSUPPORTED.
3633 ///
3634 /// **This is the CONSUMER the slot never had.** It was declared in
3635 /// phase-376 W4 and read by nothing for five phases, so
3636 /// `check-rmw-slot-producers` classified it `inert` and a family entry
3637 /// carried the reason. Both real backends already received the graph-change
3638 /// edge and discarded the discrimination — one line each — which is why the
3639 /// expensive half of closing this was never the backends.
3640 ///
3641 /// NULL surfaces `Unsupported` rather than `Ok(())`, for the same reason
3642 /// the eleven enumeration slots do: accepting a callback that will never
3643 /// fire is the silent difference RFC-0089 Part I refuses, and it is what
3644 /// "hand back a guard condition nothing triggers" would look like from the
3645 /// caller's side.
3646 unsafe fn set_graph_change_callback(
3647 &mut self,
3648 callback: Option<unsafe extern "C" fn(user_data: *const core::ffi::c_void, count: usize)>,
3649 user_data: *const core::ffi::c_void,
3650 ) -> Result<(), TransportError> {
3651 let Some(f) = self.vtable.node_get_graph_guard_condition else {
3652 return Err(TransportError::Unsupported);
3653 };
3654 let mut view = self.make_view();
3655 // SAFETY: the slot takes a `rmw_session_t *`, and the view carries the
3656 // backend data pointer the trampoline reads. The callback/user_data
3657 // lifetime contract is the caller's (see the trait's `# Safety`).
3658 let rc = unsafe { f(&mut view as *mut NrosRmwSession, callback, user_data) };
3659 if rc == NROS_RMW_RET_OK {
3660 Ok(())
3661 } else {
3662 Err(error_from_ret(rc))
3663 }
3664 }
3665
3666 /// phase-381 W5/W6 — forward to the backend's slot; NULL means UNSUPPORTED.
3667 ///
3668 /// Without this the graph slots were unreachable for every C backend: the
3669 /// trait default returns `Unsupported`, so a wired slot — cyclone's, as of
3670 /// W5 — would never be called and would look implemented while being dead
3671 /// code. That is exactly the "a slot exists, therefore it works"
3672 /// overstatement issue 0800 measured, one layer above where 0800 found it.
3673 ///
3674 /// NULL surfaces `Unsupported` rather than an empty enumeration, which is
3675 /// W6's requirement: a backend with no graph (uORB) must say "cannot tell
3676 /// you", not "nothing is there".
3677 fn get_node_names(
3678 &mut self,
3679 visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
3680 ) -> Result<(), TransportError> {
3681 let Some(f) = self.vtable.get_node_names else {
3682 return Err(TransportError::Unsupported);
3683 };
3684 // The C visitor gets a pointer to this closure as its `ctx`; the
3685 // trampoline below turns the borrowed C strings back into `&str`.
3686 // `&view`, not `&mut`: the slot takes a `const rmw_session_t *`.
3687 let view = self.make_view();
3688 let mut cb: &mut dyn FnMut(&str, &str, Option<&str>) -> bool = visit;
3689 let rc = unsafe {
3690 f(
3691 &view as *const NrosRmwSession,
3692 generated::rmw_node_visitor_t {
3693 visit: Some(node_visit_trampoline),
3694 ctx: &mut cb as *mut _ as *mut core::ffi::c_void,
3695 },
3696 )
3697 };
3698 if rc == NROS_RMW_RET_OK {
3699 Ok(())
3700 } else {
3701 Err(error_from_ret(rc))
3702 }
3703 }
3704
3705 /// phase-381 / issue 0903 — the REST of the graph family.
3706 ///
3707 /// W5 added `get_node_names` here and stopped, which made this the same
3708 /// defect one method wide: every other graph call fell through to the trait
3709 /// default and returned `Unsupported`, so the zenoh backend — which reaches
3710 /// the runtime through this vtable — answered node names and NOTHING else.
3711 /// Measured against a live `rmw_zenoh_cpp` talker: node enumeration worked
3712 /// and `get_topic_names_and_types` returned empty, because the entity query
3713 /// was never even STARTED.
3714 ///
3715 /// Fixing one method of eleven is how the first version passed every unit
3716 /// test in the phase.
3717 fn get_topic_names_and_types(
3718 &mut self,
3719 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3720 ) -> Result<(), TransportError> {
3721 let Some(f) = self.vtable.get_topic_names_and_types else {
3722 return Err(TransportError::Unsupported);
3723 };
3724 let view = self.make_view();
3725 let mut cb: &mut dyn FnMut(&str, &[&str]) -> bool = visit;
3726 let rc = unsafe {
3727 f(
3728 &view as *const NrosRmwSession,
3729 false,
3730 generated::rmw_names_and_types_visitor_t {
3731 visit: Some(names_and_types_visit_trampoline),
3732 ctx: &mut cb as *mut _ as *mut core::ffi::c_void,
3733 },
3734 )
3735 };
3736 if rc == NROS_RMW_RET_OK {
3737 Ok(())
3738 } else {
3739 Err(error_from_ret(rc))
3740 }
3741 }
3742
3743 /// phase-381 W4, wired here by the live acceptance run.
3744 ///
3745 /// The zenoh shim implemented this and `get_endpoint_info_by_topic` all
3746 /// along; `CffiSession` never dispatched them, so both fell through to the
3747 /// trait default and every caller got `Unsupported`. That is issue 0903's
3748 /// third defect for the SIX slots the 0903 fix did not cover — it wired the
3749 /// five that had a failing symptom in front of it and left these, and
3750 /// `check-rmw-slot-producers` calls them `produced` either way because it
3751 /// asks whether a slot has a producer, not whether anything reaches it.
3752 ///
3753 /// Found by `graph_interop.rs` on its first run against a real peer, which
3754 /// is the only place it could have been found.
3755 fn get_names_and_types_by_node(
3756 &mut self,
3757 kind: GraphEntityKind,
3758 node_name: &str,
3759 node_namespace: &str,
3760 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3761 ) -> Result<(), TransportError> {
3762 // The four slots do NOT share a signature: the publisher and subscriber
3763 // forms take `no_demangle`, the service and client forms do not. That
3764 // asymmetry is upstream's (`rmw_get_service_names_and_types_by_node`
3765 // has no demangle argument), and RFC-0054 makes the C headers the SSoT,
3766 // so it is mirrored rather than smoothed over — which is why this is
3767 // two calls instead of one `match` producing a function pointer.
3768 let mut name_buf = [0u8; GRAPH_NAME_CAP];
3769 let mut ns_buf = [0u8; GRAPH_NAME_CAP];
3770 if node_name.len() >= GRAPH_NAME_CAP || node_namespace.len() >= GRAPH_NAME_CAP {
3771 return Err(TransportError::BufferTooSmall);
3772 }
3773 name_buf[..node_name.len()].copy_from_slice(node_name.as_bytes());
3774 ns_buf[..node_namespace.len()].copy_from_slice(node_namespace.as_bytes());
3775
3776 let view = self.make_view();
3777 let mut cb: &mut dyn FnMut(&str, &[&str]) -> bool = visit;
3778 let ctx = &mut cb as *mut _ as *mut core::ffi::c_void;
3779 let name = name_buf.as_ptr() as *const core::ffi::c_char;
3780 let ns = ns_buf.as_ptr() as *const core::ffi::c_char;
3781
3782 let rc = match kind {
3783 GraphEntityKind::Publisher | GraphEntityKind::Subscriber => {
3784 let slot = if matches!(kind, GraphEntityKind::Publisher) {
3785 self.vtable.get_publisher_names_and_types_by_node
3786 } else {
3787 self.vtable.get_subscriber_names_and_types_by_node
3788 };
3789 let Some(f) = slot else {
3790 return Err(TransportError::Unsupported);
3791 };
3792 unsafe {
3793 f(
3794 &view as *const NrosRmwSession,
3795 name,
3796 ns,
3797 false,
3798 generated::rmw_names_and_types_visitor_t {
3799 visit: Some(names_and_types_visit_trampoline),
3800 ctx,
3801 },
3802 )
3803 }
3804 }
3805 GraphEntityKind::Service | GraphEntityKind::Client => {
3806 let slot = if matches!(kind, GraphEntityKind::Service) {
3807 self.vtable.get_service_names_and_types_by_node
3808 } else {
3809 self.vtable.get_client_names_and_types_by_node
3810 };
3811 let Some(f) = slot else {
3812 return Err(TransportError::Unsupported);
3813 };
3814 unsafe {
3815 f(
3816 &view as *const NrosRmwSession,
3817 name,
3818 ns,
3819 generated::rmw_names_and_types_visitor_t {
3820 visit: Some(names_and_types_visit_trampoline),
3821 ctx,
3822 },
3823 )
3824 }
3825 }
3826 };
3827 if rc == NROS_RMW_RET_OK {
3828 Ok(())
3829 } else {
3830 Err(error_from_ret(rc))
3831 }
3832 }
3833
3834 /// The endpoints on a topic — see [`Self::get_names_and_types_by_node`] for
3835 /// why this was unreachable until the live run.
3836 fn get_endpoint_info_by_topic(
3837 &mut self,
3838 publishers: bool,
3839 topic_name: &str,
3840 visit: &mut dyn FnMut(&GraphEndpointInfo<'_>) -> bool,
3841 ) -> Result<(), TransportError> {
3842 let slot = if publishers {
3843 self.vtable.get_publishers_info_by_topic
3844 } else {
3845 self.vtable.get_subscriptions_info_by_topic
3846 };
3847 let Some(f) = slot else {
3848 return Err(TransportError::Unsupported);
3849 };
3850 let mut topic_buf = [0u8; GRAPH_NAME_CAP];
3851 if topic_name.len() >= GRAPH_NAME_CAP {
3852 return Err(TransportError::BufferTooSmall);
3853 }
3854 topic_buf[..topic_name.len()].copy_from_slice(topic_name.as_bytes());
3855
3856 let view = self.make_view();
3857 let mut cb: &mut dyn FnMut(&GraphEndpointInfo<'_>) -> bool = visit;
3858 let rc = unsafe {
3859 f(
3860 &view as *const NrosRmwSession,
3861 topic_buf.as_ptr() as *const core::ffi::c_char,
3862 false,
3863 generated::rmw_topic_endpoint_info_visitor_t {
3864 visit: Some(endpoint_info_visit_trampoline),
3865 ctx: &mut cb as *mut _ as *mut core::ffi::c_void,
3866 },
3867 )
3868 };
3869 if rc == NROS_RMW_RET_OK {
3870 Ok(())
3871 } else {
3872 Err(error_from_ret(rc))
3873 }
3874 }
3875
3876 fn get_service_names_and_types(
3877 &mut self,
3878 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3879 ) -> Result<(), TransportError> {
3880 let Some(f) = self.vtable.get_service_names_and_types else {
3881 return Err(TransportError::Unsupported);
3882 };
3883 let view = self.make_view();
3884 let mut cb: &mut dyn FnMut(&str, &[&str]) -> bool = visit;
3885 let rc = unsafe {
3886 f(
3887 &view as *const NrosRmwSession,
3888 generated::rmw_names_and_types_visitor_t {
3889 visit: Some(names_and_types_visit_trampoline),
3890 ctx: &mut cb as *mut _ as *mut core::ffi::c_void,
3891 },
3892 )
3893 };
3894 if rc == NROS_RMW_RET_OK {
3895 Ok(())
3896 } else {
3897 Err(error_from_ret(rc))
3898 }
3899 }
3900
3901 fn count_publishers(&mut self, topic_name: &str) -> Result<usize, TransportError> {
3902 let Some(f) = self.vtable.count_publishers else {
3903 return Err(TransportError::Unsupported);
3904 };
3905 count_on_topic(&self.make_view(), f, topic_name)
3906 }
3907
3908 fn count_subscribers(&mut self, topic_name: &str) -> Result<usize, TransportError> {
3909 let Some(f) = self.vtable.count_subscribers else {
3910 return Err(TransportError::Unsupported);
3911 };
3912 count_on_topic(&self.make_view(), f, topic_name)
3913 }
3914
3915 /// Issue 1978 — upstream (Jazzy) `rmw_count_clients`. A NULL slot is
3916 /// `Unsupported`, never `Ok(0)`.
3917 fn count_clients(&mut self, service_name: &str) -> Result<usize, TransportError> {
3918 let Some(f) = self.vtable.count_clients else {
3919 return Err(TransportError::Unsupported);
3920 };
3921 count_on_topic(&self.make_view(), f, service_name)
3922 }
3923
3924 /// Issue 1978 — upstream (Jazzy) `rmw_count_services`.
3925 fn count_services(&mut self, service_name: &str) -> Result<usize, TransportError> {
3926 let Some(f) = self.vtable.count_services else {
3927 return Err(TransportError::Unsupported);
3928 };
3929 count_on_topic(&self.make_view(), f, service_name)
3930 }
3931
3932 fn ping_session(&mut self, timeout_ms: i32) -> Result<(), TransportError> {
3933 // Phase 124.F.1 — forward to the backend's vtable slot when
3934 // available; NULL surfaces `Unsupported` to the caller (no
3935 // implicit emulation — backends without a wire-level
3936 // round-trip can't probe honestly).
3937 let Some(f) = self.vtable.ping_session else {
3938 return Err(TransportError::Unsupported);
3939 };
3940 let mut view = self.make_view();
3941 let rc = unsafe { f(&mut view, timeout_ms) };
3942 if rc == NROS_RMW_RET_OK {
3943 Ok(())
3944 } else {
3945 Err(error_from_ret(rc))
3946 }
3947 }
3948
3949 /// This session MULTIPLEXES: it has no QoS behaviour of its own, so it
3950 /// ROUTES the question to whichever backend registered, through
3951 /// `vtable.supported_qos_policies`, and answers what that backend said.
3952 ///
3953 /// nros-qos-mux: packages/rmw/cyclonedds packages/rmw/xrce packages/rmw/uorb
3954 ///
3955 /// # This used to be a union, and a union over-claims for every member
3956 ///
3957 /// Until issue 1329 the vtable had no slot to ask through, so this method
3958 /// returned the UNION of what any backend it routes to honours. phase-428
3959 /// W9 made that union DERIVED — every bit was claimed by a
3960 /// `nros-qos-honours:` site in one of the crates above — which caught
3961 /// `LIVELINESS_MANUAL_BY_NODE`, a bit advertised here and implemented by
3962 /// nobody (issue 1328), and did nothing about the shape itself. Measured
3963 /// 2026-09-11, before the slot:
3964 ///
3965 /// | policy | cyclonedds | xrce | uorb |
3966 /// | --- | --- | --- | --- |
3967 /// | reliability / durability / history / depth | yes | yes (to the Agent) | no |
3968 /// | deadline / lifespan | yes | no | no |
3969 /// | liveliness kind + lease | yes (AUTOMATIC, MANUAL_BY_TOPIC) | no | no |
3970 /// | avoid_ros_namespace_conventions | no | pub + sub only | no |
3971 ///
3972 /// Every `no` in that table was admitted here and then ignored downstream
3973 /// — the no-silent-downgrade contract broken one layer below where it is
3974 /// enforced. The answer is now the registered backend's own, read once at
3975 /// `open` (`read_supported_qos_policies`, cached in this session's
3976 /// `qos_policies` field); the union is gone and no second copy of it
3977 /// survives to drift.
3978 ///
3979 /// A backend that fills no slot has declared nothing, and this answers
3980 /// `NONE` for it — loudly, with one WARN at open. See the slot's header
3981 /// block for why the absence resolves that way rather than to a union.
3982 fn supported_qos_policies(&self) -> nros_rmw::QoSPolicyMask {
3983 self.qos_policies
3984 }
3985}
3986
3987impl Drop for CffiSession {
3988 fn drop(&mut self) {
3989 if !self.backend_data.is_null() {
3990 let mut view = self.make_view();
3991 unsafe {
3992 (self
3993 .vtable
3994 .destroy_session
3995 .expect("rmw vtable: destroy_session"))(&mut view)
3996 };
3997 }
3998 }
3999}
4000
4001// ============================================================================
4002// CffiPublisher
4003// ============================================================================
4004
4005/// Publisher backed by a C vtable.
4006pub struct CffiPublisher {
4007 vtable: &'static NrosRmwVtable,
4008 topic_name_buf: [u8; NAME_BUF_LEN],
4009 type_name_buf: [u8; NAME_BUF_LEN],
4010 qos: NrosRmwQos,
4011 /// The profile the backend GRANTED, read back at create time.
4012 ///
4013 /// Not the request: `qos` above is what was asked for, this is what the
4014 /// entity runs, and every policy the backend could not report carries its
4015 /// `*_UNKNOWN` sentinel. `qos_unknown_c()` for a backend with no read-back
4016 /// slot at all — every policy an absence, which is the honest answer and
4017 /// is what [`nros_rmw::Publisher::actual_qos`] returns there.
4018 ///
4019 /// Read once at create rather than on every call: upstream's
4020 /// `rmw_*_get_actual_qos` is a property of the entity, and a slot that
4021 /// re-enters the backend would make an accessor a transport operation.
4022 actual_qos: NrosRmwQos,
4023 can_loan_messages: bool,
4024 backend_data: *mut c_void,
4025 /// Issue 1164 — callbacks the runtime serves by polling
4026 /// `publisher_take_event`, indexed by [`PUB_EVENT_KINDS`]. Empty on a
4027 /// backend that fills `publisher_event_init`; the registration goes
4028 /// straight through in that case.
4029 polled_events: [Cell<Option<PolledEventReg>>; PUB_EVENT_KINDS.len()],
4030 /// Re-entrancy guard for [`CffiPublisher::poll_status_events`]. A user
4031 /// callback is free to publish, and publishing polls — so the drain must
4032 /// not call itself. A `Cell`, not a lock: the entity is `!Sync` (it holds
4033 /// the backend's raw pointer), so there is no second thread to exclude,
4034 /// and a lock here would be one a backend listener could also want, which
4035 /// is the self-relock that hangs on POSIX and passes on Zephyr.
4036 polling_events: Cell<bool>,
4037}
4038
4039impl CffiPublisher {
4040 fn make_view(&mut self) -> NrosRmwPublisher {
4041 NrosRmwPublisher {
4042 topic_name: self.topic_name_buf.as_ptr().cast(),
4043 type_name: self.type_name_buf.as_ptr().cast(),
4044 qos: self.qos,
4045 can_loan_messages: self.can_loan_messages,
4046 _reserved: [0u8; 7],
4047 backend_data: self.backend_data,
4048 }
4049 }
4050
4051 /// `make_view` from a shared borrow. The view is a by-value snapshot of
4052 /// this publisher's fields; the backend reads it and never writes through
4053 /// it, which is the same reasoning `has_data` uses one entity over.
4054 fn view_shared(&self) -> NrosRmwPublisher {
4055 NrosRmwPublisher {
4056 topic_name: self.topic_name_buf.as_ptr().cast(),
4057 type_name: self.type_name_buf.as_ptr().cast(),
4058 qos: self.qos,
4059 can_loan_messages: self.can_loan_messages,
4060 _reserved: [0u8; 7],
4061 backend_data: self.backend_data,
4062 }
4063 }
4064
4065 /// Issue 1164 — drain `publisher_take_event` for every kind this
4066 /// publisher has a registered callback for, and fire the callbacks.
4067 ///
4068 /// Called from the publisher's ordinary data path (`publish_raw`,
4069 /// `publish_streamed`, `assert_liveliness`), which is where the zenoh
4070 /// shim fires its own publisher-side events from. A publisher that stops
4071 /// publishing therefore stops polling — the same limitation zenoh has,
4072 /// and the reason `OfferedDeadlineMissed` is observed on the NEXT publish
4073 /// rather than at the instant the deadline lapsed.
4074 ///
4075 /// No callback is invoked while the backend holds anything: `take_event`
4076 /// copies the status out and returns, and only then is the user's
4077 /// callback called. Nothing here is re-entrant into the backend.
4078 fn poll_status_events(&self) {
4079 let Some(take) = self.vtable.publisher_take_event else {
4080 return;
4081 };
4082 if self.polling_events.replace(true) {
4083 return;
4084 }
4085 for (slot, kind) in PUB_EVENT_KINDS.iter().enumerate() {
4086 let Some(reg) = self.polled_events[slot].get() else {
4087 continue;
4088 };
4089 let cb = reg.cb;
4090 let view = self.view_shared();
4091 let mut payload = empty_event_payload();
4092 let mut taken = false;
4093 // SAFETY: `view` is a live snapshot of this publisher, `payload`
4094 // and `taken` are stack locals the slot writes through. The slot
4095 // writes `payload` only when it sets `taken`.
4096 let rc = unsafe { take(&view, event_kind_to_c(*kind), &mut payload, &mut taken) };
4097 static SITE: StatusSite = StatusSite::new("publisher_take_event");
4098 if !status_ok(rc, &SITE) || !taken {
4099 continue;
4100 }
4101 // SAFETY: `cb` and `user_ctx` were supplied together at
4102 // registration and the registrant keeps `user_ctx` alive for the
4103 // entity's lifetime (`nros-node`'s `EventRegs`). `payload` lives
4104 // to the end of this statement, which is the whole contract the
4105 // callback gets.
4106 unsafe { cb(event_kind_to_c(*kind), &payload, reg.user_ctx) };
4107 }
4108 self.polling_events.set(false);
4109 }
4110
4111 /// Topic name. Result is the null-terminated string written at
4112 /// publisher creation; never re-resolved from the backend.
4113 pub fn topic_name(&self) -> &str {
4114 cstr_buf_to_str(&self.topic_name_buf)
4115 }
4116
4117 /// Fully-qualified type name (`"std_msgs/msg/Int32"`).
4118 pub fn type_name(&self) -> &str {
4119 cstr_buf_to_str(&self.type_name_buf)
4120 }
4121
4122 /// QoS used to create this publisher.
4123 pub fn qos(&self) -> NrosRmwQos {
4124 self.qos
4125 }
4126
4127 /// `true` iff the backend exposes the publish loan primitive.
4128 /// Mirrors upstream `rmw_publisher_t::can_loan_messages`.
4129 pub fn can_loan_messages(&self) -> bool {
4130 self.can_loan_messages
4131 }
4132
4133 /// Issue 1164 — record a callback the runtime will serve by polling
4134 /// `publisher_take_event`. Returns `Unsupported` when there is no poll
4135 /// slot either, or when `kind` is not a publisher-side kind.
4136 fn register_polled_event(
4137 &self,
4138 kind: nros_rmw::EventKind,
4139 cb: NrosRmwEventCallback,
4140 user_ctx: *mut c_void,
4141 ) -> Result<(), TransportError> {
4142 let Some(cb) = cb else {
4143 return Err(TransportError::Unsupported);
4144 };
4145 if self.vtable.publisher_take_event.is_none() {
4146 return Err(TransportError::Unsupported);
4147 }
4148 let Some(slot) = pub_event_slot(kind) else {
4149 return Err(TransportError::Unsupported);
4150 };
4151 self.polled_events[slot].set(Some(PolledEventReg { cb, user_ctx }));
4152 Ok(())
4153 }
4154}
4155
4156/// Writable slot returned by
4157/// [`CffiPublisher::try_lend_slot`]. Holds the backend's raw buffer
4158/// and opaque token until `commit_slot` consumes it or `Drop` fires
4159/// ~~`pub_discard`~~.
4160#[cfg(feature = "lending")]
4161pub struct CffiSlot<'a> {
4162 buf: *mut u8,
4163 cap: usize,
4164 cursor: usize,
4165 token: *mut generated::rmw_loan_token_t,
4166 /// `None` after `commit_slot` consumes the slot — Drop skips the
4167 /// discard call in that case.
4168 publisher: Option<&'a CffiPublisher>,
4169}
4170
4171#[cfg(feature = "lending")]
4172impl<'a> CffiSlot<'a> {
4173 /// Mark the actual bytes written before commit. Defaults to the
4174 /// full capacity; callers that write a shorter prefix MUST call
4175 /// `set_len` first.
4176 pub fn set_len(&mut self, len: usize) {
4177 debug_assert!(len <= self.cap);
4178 self.cursor = len.min(self.cap);
4179 }
4180}
4181
4182#[cfg(feature = "lending")]
4183impl<'a> AsMut<[u8]> for CffiSlot<'a> {
4184 fn as_mut(&mut self) -> &mut [u8] {
4185 // SAFETY: `buf` came from `pub_loan` with capacity `cap`. The
4186 // loan contract guarantees the slot stays valid until commit
4187 // or discard. The lifetime `'a` borrows the publisher so the
4188 // returned slice can't outlive the loan.
4189 unsafe { core::slice::from_raw_parts_mut(self.buf, self.cap) }
4190 }
4191}
4192
4193#[cfg(feature = "lending")]
4194impl<'a> Drop for CffiSlot<'a> {
4195 fn drop(&mut self) {
4196 if self.publisher.is_none() {
4197 // commit_slot consumed the loan — nothing to release.
4198 return;
4199 }
4200 if let Some(p) = self.publisher
4201 && let Some(discard) = p.vtable.return_loaned_message_from_publisher
4202 {
4203 // Re-materialise the publisher view so the backend sees
4204 // the same `NrosRmwPublisher` shape it created the loan
4205 // against.
4206 let view = NrosRmwPublisher {
4207 topic_name: p.topic_name_buf.as_ptr().cast(),
4208 type_name: p.type_name_buf.as_ptr().cast(),
4209 qos: p.qos,
4210 can_loan_messages: p.can_loan_messages,
4211 _reserved: [0u8; 7],
4212 backend_data: p.backend_data,
4213 };
4214 // SAFETY: `token` came from a paired `pub_loan` on this
4215 // publisher and the publisher is still alive (lifetime
4216 // `'a` borrows it).
4217 let ret = unsafe { discard(&view, self.token) };
4218 if ret != NROS_RMW_RET_OK {
4219 nros_log::log_error!(
4220 nros_log::get_logger("nros_rmw_cffi"),
4221 "return_loaned_message_from_publisher failed with {}; the loan slot may be stranded",
4222 ret
4223 );
4224 }
4225 }
4226 }
4227}
4228
4229#[cfg(feature = "lending")]
4230impl nros_rmw::SlotLending for CffiPublisher {
4231 type Slot<'a> = CffiSlot<'a>;
4232
4233 fn try_lend_slot(&self, len: usize) -> Result<Option<CffiSlot<'_>>, TransportError> {
4234 let Some(loan) = self.vtable.borrow_loaned_message else {
4235 // Issue 0814 (option 2) — a backend with no `borrow_loaned_message`
4236 // cannot lend, and that is a STATIC fact about this publisher's
4237 // vtable, the same in every build. So the answer is the same in
4238 // every build: a permanent `Unsupported`.
4239 //
4240 // There used to be a staging fallback here in `alloc` builds: a
4241 // `Box` + `Vec` per loan, encoded into exactly as the caller's own
4242 // buffer would have been, then `publish_raw` of it at commit. It
4243 // removed no copy and added an allocation pair per message, while
4244 // `can_loan_messages` (derived from this same slot) said `false` —
4245 // a loan API advertising a saving it did not make, and answering
4246 // differently with and without a heap.
4247 //
4248 // Not `Ok(None)`: every caller reads that as "no slot RIGHT NOW,
4249 // retry" (`LoanError::WouldBlock`, `loan_with_timeout` spinning its
4250 // whole budget), and no retry can
4251 // change a vtable. Not `LoanNotSupported` either: its doc bundles
4252 // "or the loan slot is currently in use", the transient reading.
4253 //
4254 // What a caller should do on seeing it: stop asking for a loan on
4255 // this publisher — `can_loan_messages` says so up front — and take
4256 // `publish_raw`, or `publish_streamed`, which needs no token, no
4257 // arena and no heap.
4258 let _ = len;
4259 return Err(TransportError::Unsupported);
4260 };
4261 let view = NrosRmwPublisher {
4262 topic_name: self.topic_name_buf.as_ptr().cast(),
4263 type_name: self.type_name_buf.as_ptr().cast(),
4264 qos: self.qos,
4265 can_loan_messages: self.can_loan_messages,
4266 _reserved: [0u8; 7],
4267 backend_data: self.backend_data,
4268 };
4269 let mut slot = generated::rmw_mut_byte_span_t {
4270 data: core::ptr::null_mut(),
4271 capacity: 0,
4272 len: 0,
4273 };
4274 let mut out_token: *mut generated::rmw_loan_token_t = core::ptr::null_mut();
4275 // SAFETY: vtable contract — slot pointers stay valid until
4276 // commit / discard.
4277 let ret = unsafe { loan(&view, len, &mut slot, &mut out_token) };
4278 let (out_buf, out_cap) = (slot.data, slot.capacity);
4279 if ret == NROS_RMW_RET_WOULD_BLOCK || ret == NROS_RMW_RET_NO_DATA {
4280 return Ok(None);
4281 }
4282 if ret != NROS_RMW_RET_OK {
4283 return Err(error_from_ret(ret));
4284 }
4285 if out_buf.is_null() || out_cap < len {
4286 // Defensive: a buggy backend returned OK with a too-small
4287 // slot. Treat as transient.
4288 if let Some(discard) = self.vtable.return_loaned_message_from_publisher {
4289 // The loan is already being abandoned; a failure to hand it back
4290 // does not change what this function returns, but it is the
4291 // second fault in a row and worth a line.
4292 let ret = unsafe { discard(&view, out_token) };
4293 if ret != NROS_RMW_RET_OK {
4294 nros_log::log_error!(
4295 nros_log::get_logger("nros_rmw_cffi"),
4296 "discarding an undersized loan also failed with {}",
4297 ret
4298 );
4299 }
4300 }
4301 return Ok(None);
4302 }
4303 Ok(Some(CffiSlot {
4304 buf: out_buf,
4305 cap: out_cap,
4306 cursor: len,
4307 token: out_token,
4308 publisher: Some(self),
4309 }))
4310 }
4311
4312 fn commit_slot(&self, mut slot: CffiSlot<'_>) -> Result<(), TransportError> {
4313 // Cancel Drop's discard — we're committing, not abandoning.
4314 let publisher = slot
4315 .publisher
4316 .take()
4317 .ok_or(TransportError::InvalidArgument)?;
4318 debug_assert!(core::ptr::eq(publisher, self));
4319 let commit = self
4320 .vtable
4321 .publish_loaned_message
4322 .ok_or(TransportError::Unsupported)?;
4323 let view = NrosRmwPublisher {
4324 topic_name: self.topic_name_buf.as_ptr().cast(),
4325 type_name: self.type_name_buf.as_ptr().cast(),
4326 qos: self.qos,
4327 can_loan_messages: self.can_loan_messages,
4328 _reserved: [0u8; 7],
4329 backend_data: self.backend_data,
4330 };
4331 let len = slot.cursor;
4332 let token = slot.token;
4333 // `slot` drops here without firing
4334 // `return_loaned_message_from_publisher` because `publisher` is `None`.
4335 let ret = unsafe { commit(&view, token, len) };
4336 if ret != NROS_RMW_RET_OK {
4337 return Err(error_from_ret(ret));
4338 }
4339 Ok(())
4340 }
4341}
4342
4343// ---------------------------------------------------------------------------
4344// Issue 0812 — the loan path across the C / C++ boundary, without a heap.
4345//
4346// `SlotLending` hands back a `CffiSlot`, which is a Rust value with a `Drop`
4347// impl. An FFI entry point has to keep that value alive between `_loan` and
4348// `_commit` / `_discard` and has nowhere to put it, so `nros-c` / `nros-cpp`
4349// each boxed one per loan: a `malloc` on the path whose whole purpose is to
4350// remove copies and, worse, a hard `alloc` dependency on a surface that a
4351// heap-free image is supposed to be able to use.
4352//
4353// None of that state has to cross the boundary. Commit and discard are handed
4354// the publisher back as a parameter, and the backend already minted a stable
4355// token of its own (there is no runtime-side loan since issue 0814 retired the
4356// staging fallback: a backend with no loan slot refuses). So the FFI
4357// layers pass the BACKEND's token straight through and store nothing at all.
4358//
4359// One implementation, not two: `commit_raw` / `discard_raw` rebuild the
4360// `CffiSlot` and delegate to `commit_slot` / `Drop`, so the loan lifecycle
4361// keeps exactly one body and cannot drift from the `SlotLending` path.
4362// ---------------------------------------------------------------------------
4363#[cfg(feature = "lending")]
4364impl CffiPublisher {
4365 /// Rebuild the [`CffiSlot`] describing an outstanding loan from its
4366 /// token, so the shared commit / discard bodies can run on it.
4367 ///
4368 /// `buf` and `cap` are only ever read by `as_mut` / `set_len`, neither of
4369 /// which runs on the commit or discard path (both hand `token` to the
4370 /// backend), so the rebuilt slot deliberately carries no buffer.
4371 ///
4372 /// # Safety
4373 /// `token` must be the token of a loan that is still outstanding on
4374 /// `self`, and the returned slot must be committed or dropped exactly
4375 /// once.
4376 unsafe fn slot_from_token(
4377 &self,
4378 token: *mut generated::rmw_loan_token_t,
4379 len: usize,
4380 ) -> CffiSlot<'_> {
4381 CffiSlot {
4382 buf: core::ptr::null_mut(),
4383 cap: len,
4384 cursor: len,
4385 token,
4386 publisher: Some(self),
4387 }
4388 }
4389
4390 /// Allocation-free loan: reserve a slot and hand back the backend's own
4391 /// opaque token instead of a Rust value the caller would have to store.
4392 ///
4393 /// Returns `(buf, cap, token)`. `Ok(None)` means no slot is available
4394 /// right now — the same meaning `SlotLending::try_lend_slot` gives it.
4395 ///
4396 /// The loan stays outstanding until [`commit_raw`](Self::commit_raw) or
4397 /// [`discard_raw`](Self::discard_raw) consumes `token` — exactly one of
4398 /// them, exactly once. Callers that can hold a Rust value across the
4399 /// whole loan should use `SlotLending` instead and let `Drop` do it.
4400 pub fn try_lend_raw(
4401 &self,
4402 len: usize,
4403 ) -> Result<Option<(*mut u8, usize, *mut generated::rmw_loan_token_t)>, TransportError> {
4404 use nros_rmw::SlotLending as _;
4405 let Some(mut slot) = self.try_lend_slot(len)? else {
4406 return Ok(None);
4407 };
4408 let buf = slot.as_mut().as_mut_ptr();
4409 let cap = slot.as_mut().len();
4410 let token = slot.token;
4411 // Keep the loan outstanding — dropping the slot here would hand it
4412 // straight back to the backend.
4413 core::mem::forget(slot);
4414 Ok(Some((buf, cap, token)))
4415 }
4416
4417 /// Commit a loan taken with [`try_lend_raw`](Self::try_lend_raw).
4418 ///
4419 /// `actual_len` is the number of bytes written. It reaches the backend's
4420 /// own commit, which is the layer that knows the slot's capacity and is
4421 /// responsible for clamping.
4422 ///
4423 /// # Safety
4424 /// `token` must come from a prior `try_lend_raw` on THIS publisher, must
4425 /// still be outstanding, and must not be used again after this call.
4426 pub unsafe fn commit_raw(
4427 &self,
4428 token: *mut generated::rmw_loan_token_t,
4429 actual_len: usize,
4430 ) -> Result<(), TransportError> {
4431 use nros_rmw::SlotLending as _;
4432 // SAFETY: forwarded from this function's own contract.
4433 let slot = unsafe { self.slot_from_token(token, actual_len) };
4434 self.commit_slot(slot)
4435 }
4436
4437 /// Abandon a loan taken with [`try_lend_raw`](Self::try_lend_raw)
4438 /// without sending it.
4439 ///
4440 /// # Safety
4441 /// `token` must come from a prior `try_lend_raw` on THIS publisher, must
4442 /// still be outstanding, and must not be used again after this call.
4443 pub unsafe fn discard_raw(
4444 &self,
4445 token: *mut generated::rmw_loan_token_t,
4446 ) -> Result<(), TransportError> {
4447 // SAFETY: forwarded from this function's own contract. Dropping the
4448 // rebuilt slot is what fires the backend's discard.
4449 drop(unsafe { self.slot_from_token(token, 0) });
4450 Ok(())
4451 }
4452}
4453
4454impl Publisher for CffiPublisher {
4455 type Error = TransportError;
4456
4457 fn publish_raw(&self, data: &[u8]) -> Result<(), TransportError> {
4458 // Issue 1164 — the publisher's data path is its poll point for a
4459 // backend that fills `publisher_take_event`. No-op when nothing is
4460 // registered, and no-op for a backend that fills `*_event_init`.
4461 self.poll_status_events();
4462 let mut view = NrosRmwPublisher {
4463 topic_name: self.topic_name_buf.as_ptr().cast(),
4464 type_name: self.type_name_buf.as_ptr().cast(),
4465 qos: self.qos,
4466 can_loan_messages: self.can_loan_messages,
4467 _reserved: [0u8; 7],
4468 backend_data: self.backend_data,
4469 };
4470 let ret = unsafe {
4471 (self.vtable.publish.expect("rmw vtable: publish"))(
4472 &mut view,
4473 // phase-406 W2 — by VALUE: a read span has nothing to report back.
4474 generated::rmw_byte_span_t {
4475 data: data.as_ptr(),
4476 len: data.len(),
4477 },
4478 )
4479 };
4480 if ret != NROS_RMW_RET_OK {
4481 return Err(error_from_ret(ret));
4482 }
4483 Ok(())
4484 }
4485
4486 unsafe fn publish_streamed(
4487 &self,
4488 size_cb: unsafe extern "C" fn(out_total_len: *mut usize, user_ctx: *mut core::ffi::c_void),
4489 chunk_cb: unsafe extern "C" fn(
4490 out_buf: *mut u8,
4491 cap: usize,
4492 out_written: *mut usize,
4493 user_ctx: *mut core::ffi::c_void,
4494 ),
4495 user_ctx: *mut core::ffi::c_void,
4496 ) -> Result<(), TransportError> {
4497 // Phase 124.E.1+2 — vtable forwarder. If the backend exposes
4498 // `publish_streamed` natively, dispatch in one hop so the
4499 // callbacks land directly inside the backend's outbound
4500 // buffer (no staging copy). Otherwise fall back to the
4501 // `Publisher::publish_streamed` default body, which runs a
4502 // stack staging buffer + `publish_raw`.
4503 if let Some(f) = self.vtable.publish_streamed {
4504 // Issue 1164 — the native arm is a second publish path and needs
4505 // its own poll point. The staging fallback below does not: it
4506 // ends in `publish_raw`, which polls.
4507 self.poll_status_events();
4508 let mut view = NrosRmwPublisher {
4509 topic_name: self.topic_name_buf.as_ptr().cast(),
4510 type_name: self.type_name_buf.as_ptr().cast(),
4511 qos: self.qos,
4512 can_loan_messages: self.can_loan_messages,
4513 _reserved: [0u8; 7],
4514 backend_data: self.backend_data,
4515 };
4516 // Generated slot takes nullable callbacks; ours are live fn pointers.
4517 let ret = unsafe { f(&mut view, Some(size_cb), Some(chunk_cb), user_ctx) };
4518 if ret != NROS_RMW_RET_OK {
4519 return Err(error_from_ret(ret));
4520 }
4521 return Ok(());
4522 }
4523 // Inlined staging-buffer fallback. Mirrors the trait default
4524 // body so the override doesn't recurse through dynamic
4525 // dispatch — the default body would resolve back to this
4526 // function and deadlock.
4527 const STAGE_CAP: usize = 4096;
4528 let mut total = 0usize;
4529 unsafe { size_cb(&mut total as *mut usize, user_ctx) };
4530 if total > STAGE_CAP {
4531 return Err(TransportError::BufferTooSmall);
4532 }
4533 let mut stage = [0u8; STAGE_CAP];
4534 let mut written_so_far = 0usize;
4535 while written_so_far < total {
4536 let mut chunk_written = 0usize;
4537 let remaining = total - written_so_far;
4538 unsafe {
4539 chunk_cb(
4540 stage.as_mut_ptr().add(written_so_far),
4541 remaining,
4542 &mut chunk_written as *mut usize,
4543 user_ctx,
4544 );
4545 }
4546 if chunk_written == 0 {
4547 return Err(TransportError::BufferTooSmall);
4548 }
4549 written_so_far += chunk_written;
4550 }
4551 self.publish_raw(&stage[..total])
4552 }
4553
4554 fn buffer_error(&self) -> TransportError {
4555 TransportError::BufferTooSmall
4556 }
4557
4558 fn serialization_error(&self) -> TransportError {
4559 TransportError::SerializationError
4560 }
4561
4562 fn unsupported_event_error(&self) -> TransportError {
4563 TransportError::Unsupported
4564 }
4565
4566 unsafe fn register_event_callback(
4567 &mut self,
4568 kind: nros_rmw::EventKind,
4569 deadline_ms: u32,
4570 cb: nros_rmw::EventCallback,
4571 user_ctx: *mut core::ffi::c_void,
4572 ) -> Result<(), TransportError> {
4573 let view = NrosRmwPublisher {
4574 topic_name: self.topic_name_buf.as_ptr().cast(),
4575 type_name: self.type_name_buf.as_ptr().cast(),
4576 qos: self.qos,
4577 can_loan_messages: self.can_loan_messages,
4578 _reserved: [0u8; 7],
4579 backend_data: self.backend_data,
4580 };
4581 // Cffi event callback ABI matches nros_rmw::EventCallback (layout
4582 // notes in `rust_adapter`); the generated slot is nullable, so the
4583 // live fn pointer is wrapped in `Some`.
4584 let cb: NrosRmwEventCallback = Some(unsafe {
4585 core::mem::transmute::<
4586 nros_rmw::EventCallback,
4587 unsafe extern "C" fn(NrosRmwEventKind, *const NrosRmwEventPayload, *mut c_void),
4588 >(cb)
4589 });
4590 // Issue 0349 — a NULL slot means the backend does not implement this
4591 // OPTIONAL capability (xrce NULLs all three). Report it as
4592 // `Unsupported`; never panic, and never make it a registration error.
4593 //
4594 // Issue 1164 — NULL is ALSO the deliberate answer of a backend that
4595 // fills `publisher_take_event` instead, and for those the
4596 // registration is served here rather than refused. cyclonedds is one:
4597 // its `drive_io` is a sleep, so it has nowhere safe to call a
4598 // callback from and hands us its counters to drain.
4599 let Some(register) = self.vtable.publisher_event_init else {
4600 return self.register_polled_event(kind, cb, user_ctx);
4601 };
4602 let ret = unsafe { register(&view, event_kind_to_c(kind), deadline_ms, cb, user_ctx) };
4603 if ret != NROS_RMW_RET_OK {
4604 return Err(error_from_ret(ret));
4605 }
4606 Ok(())
4607 }
4608
4609 fn supports_event(&self, kind: nros_rmw::EventKind) -> bool {
4610 // Issue 1164 — SLOT granularity, not per-kind: the C ABI carries no
4611 // capability query, so the honest answer is "a path exists that could
4612 // carry this kind for this entity". A backend may still decline the
4613 // specific kind at registration, which is why `register_event_callback`
4614 // stays the authority.
4615 //
4616 // This used to be the trait default — a flat `false` for every cffi
4617 // backend, including the ones whose events work. `book/src/concepts/
4618 // status-events.md` tells applications to gate registration on this
4619 // call, so a flat `false` made every backend behind this vtable look
4620 // eventless whether it was or not.
4621 //
4622 // Issue 1978 — the ABI now HAS a per-kind query
4623 // (`event_type_is_supported`); the one helper folds it in.
4624 pub_event_slot(kind).is_some() && backend_event_type_is_supported(self.vtable, kind)
4625 }
4626
4627 fn assert_liveliness(&self) -> Result<(), TransportError> {
4628 // Phase 108.B — manual liveliness assertion.
4629 let view_ptr = self as *const _ as *mut Self;
4630 let view = unsafe { (*view_ptr).make_view() };
4631 // Issue 0349 — a NULL slot means the backend does not implement this
4632 // OPTIONAL capability (xrce NULLs all three). Report it as
4633 // `Unsupported`; never panic, and never make it a registration error.
4634 //
4635 // ...but ONLY when the caller actually asked for manual assertion.
4636 // `rmw_vtable.h` has stated this split since phase 108 — "runtime
4637 // returns `NROS_RMW_RET_OK` for AUTOMATIC / NONE callers and
4638 // `NROS_RMW_RET_UNSUPPORTED` for MANUAL_*" — and it was implemented
4639 // NOWHERE: this comment used to say "the runtime caller (Node) gates
4640 // the call by liveliness_kind so we just delegate", and
4641 // `EmbeddedPublisher::assert_liveliness` does no such gating, it
4642 // forwards. So a publisher with AUTOMATIC liveliness on a backend
4643 // with a NULL slot read `Unsupported` for a call that had nothing to
4644 // do. `self.qos` is the REQUEST, which is the right side to ask:
4645 // `actual_qos` may be the `Unknown` absence on a backend with no
4646 // read-back, and an absence is not a reason to refuse.
4647 // (The phase-467 RMW gap-closure design study's Row 7.)
4648 let Some(assert_liveliness) = self.vtable.publisher_assert_liveliness else {
4649 return if qos_from_c(&self.qos).liveliness_kind.is_manual() {
4650 Err(TransportError::Unsupported)
4651 } else {
4652 Ok(())
4653 };
4654 };
4655 let ret = unsafe { assert_liveliness(&view) };
4656 if ret != NROS_RMW_RET_OK {
4657 return Err(error_from_ret(ret));
4658 }
4659 // Issue 1164 — asserting liveliness is the other publisher-side data
4660 // path, and the one after which `LivelinessLost` is most likely to
4661 // have moved. Same poll point the zenoh shim uses.
4662 self.poll_status_events();
4663 Ok(())
4664 }
4665
4666 /// The profile the backend GRANTED, read back at create time.
4667 ///
4668 /// Answers off the retained value rather than re-entering the backend:
4669 /// upstream's `rmw_publisher_get_actual_qos` is a property of the entity,
4670 /// and a backend call here would make an accessor a transport operation on
4671 /// a `&self` that any callback may hold.
4672 fn actual_qos(&self) -> QoSProfile {
4673 qos_from_c(&self.actual_qos)
4674 }
4675
4676 /// Upstream `rmw_get_gid_for_publisher`, through the vtable slot.
4677 ///
4678 /// The phase-467 RMW gap-closure design study's Q1, step 2. A NULL slot
4679 /// answers `Unsupported` — uORB and XRCE NULL it. The Rust adapter table
4680 /// zenoh rides FILLS it now (it was NULL there too until this study, so a
4681 /// Rust backend with a real identity could not report one). Never an
4682 /// all-zero gid: that is what the uninitialised `rmw_gid_t` below holds,
4683 /// so returning it on the NULL path would make "no identity" read exactly
4684 /// like an answer.
4685 ///
4686 /// The backend's `implementation_identifier` is deliberately DROPPED
4687 /// here. `nros_rmw_cffi_register_named` admits several backends in one
4688 /// image and gids from two of them are not comparable, so upstream's
4689 /// pairing matters — but the trait answers bytes, and the identifier a
4690 /// caller needs is the one on the SESSION it asked. Carrying a second
4691 /// copy per publisher would be a second place for it to disagree.
4692 fn get_gid(&self) -> Result<[u8; nros_rmw::PUBLISHER_GID_SIZE], TransportError> {
4693 let view_ptr = self as *const _ as *mut Self;
4694 let view = unsafe { (*view_ptr).make_view() };
4695 let Some(get_gid_for_publisher) = self.vtable.get_gid_for_publisher else {
4696 return Err(TransportError::Unsupported);
4697 };
4698 let mut gid = NrosRmwGid {
4699 implementation_identifier: core::ptr::null(),
4700 data: [0u8; nros_rmw::PUBLISHER_GID_SIZE],
4701 };
4702 let ret = unsafe { get_gid_for_publisher(&view, &mut gid) };
4703 if ret != NROS_RMW_RET_OK {
4704 return Err(error_from_ret(ret));
4705 }
4706 Ok(gid.data)
4707 }
4708
4709 /// Upstream `rmw_publisher_count_matched_subscriptions`, through the
4710 /// vtable slot. Issue 1643 — the slot's first RUNTIME reader (the node
4711 /// API's `get_subscription_count`); until then only an interop probe and
4712 /// the backend's own tests asked. A NULL slot answers `Unsupported`.
4713 fn count_matched_subscriptions(&self) -> Result<usize, TransportError> {
4714 let Some(count) = self.vtable.publisher_count_matched_subscriptions else {
4715 return Err(TransportError::Unsupported);
4716 };
4717 let view = self.view_shared();
4718 let mut n: usize = 0;
4719 // SAFETY: the slot is the backend's, called with a live view of this
4720 // entity and an out-pointer to a local, per the vtable contract.
4721 let ret = unsafe { count(&view, &mut n) };
4722 if ret != NROS_RMW_RET_OK {
4723 return Err(error_from_ret(ret));
4724 }
4725 Ok(n)
4726 }
4727}
4728
4729impl Drop for CffiPublisher {
4730 fn drop(&mut self) {
4731 if !self.backend_data.is_null() {
4732 let mut view = self.make_view();
4733 let ret = unsafe {
4734 (self
4735 .vtable
4736 .destroy_publisher
4737 .expect("rmw vtable: destroy_publisher"))(&mut view)
4738 };
4739 // Phase 376 W5 — the slot reports now, and `Drop` is the one caller
4740 // that cannot propagate. Logging is not a consolation prize: a
4741 // teardown that failed is a leak, and a leak with no message
4742 // surfaces later as an allocation failure with no provenance.
4743 // `nros_log`, never std stdio — issue 0589.
4744 if ret != NROS_RMW_RET_OK {
4745 nros_log::log_error!(
4746 nros_log::get_logger("nros_rmw_cffi"),
4747 "destroy_publisher failed with {}; the backend may have leaked the publisher",
4748 ret
4749 );
4750 }
4751 }
4752 }
4753}
4754
4755// ============================================================================
4756// CffiSubscription
4757// ============================================================================
4758
4759/// Subscription backed by a C vtable.
4760pub struct CffiSubscription {
4761 vtable: &'static NrosRmwVtable,
4762 topic_name_buf: [u8; NAME_BUF_LEN],
4763 type_name_buf: [u8; NAME_BUF_LEN],
4764 qos: NrosRmwQos,
4765 /// The profile the backend GRANTED, read back at create time.
4766 ///
4767 /// Not the request: `qos` above is what was asked for, this is what the
4768 /// entity runs, and every policy the backend could not report carries its
4769 /// `*_UNKNOWN` sentinel. `qos_unknown_c()` for a backend with no read-back
4770 /// slot at all — every policy an absence, which is the honest answer and
4771 /// is what [`nros_rmw::Publisher::actual_qos`] returns there.
4772 ///
4773 /// Read once at create rather than on every call: upstream's
4774 /// `rmw_*_get_actual_qos` is a property of the entity, and a slot that
4775 /// re-enters the backend would make an accessor a transport operation.
4776 actual_qos: NrosRmwQos,
4777 can_loan_messages: bool,
4778 backend_data: *mut c_void,
4779 /// Phase 231 (RFC-0038) — cached `subscription_supports_in_place` capability,
4780 /// queried once at creation so `supports_process_in_place(&self)` is cheap.
4781 supports_in_place: bool,
4782 /// Issue 0971 — a status that happened where it could not be returned.
4783 ///
4784 /// `take_sequence` is contractually a COUNT: a partial drain reports
4785 /// what it got rather than erroring (`rmw_vtable.h`). So when the drain
4786 /// stops because a message did not fit the caller's slot, there is nowhere
4787 /// to put `BufferTooSmall` — and this loop used to answer it with `?`,
4788 /// throwing away the count for the messages it HAD delivered, while the
4789 /// native Cyclone path answered the same condition with `Ok(count)`.
4790 ///
4791 /// The status is parked here and returned by the next call instead. That is
4792 /// the shape `nros-verification`'s `take_post_fix` already proves for
4793 /// the single take — check the flag first, clear it, return the error, take
4794 /// nothing — moved one call later because that is where the contract leaves
4795 /// room for it.
4796 pending_status: Option<TransportError>,
4797 /// Issue 1612 — what the last refused take said the sample needed, as
4798 /// [`nros_rmw::Subscription::refused_sample_len`] reports it.
4799 refused_len: Option<usize>,
4800 /// Issue 1164 — callbacks the runtime serves by polling
4801 /// `subscription_take_event`, indexed by [`SUB_EVENT_KINDS`]. See the
4802 /// note above [`PolledEventReg`].
4803 polled_events: [Cell<Option<PolledEventReg>>; SUB_EVENT_KINDS.len()],
4804 /// Re-entrancy guard for [`CffiSubscription::poll_status_events`] — a
4805 /// user callback is free to take, and taking polls. A `Cell`, not a
4806 /// lock; see the publisher's field of the same name.
4807 polling_events: Cell<bool>,
4808 /// Issue 1940 — the waker `register_waker` installed, woken by the
4809 /// backend through the `subscription_set_on_new_message_callback` slot.
4810 entity_waker: WakerSlot,
4811}
4812
4813impl CffiSubscription {
4814 /// Issue 1495 — `take_serialized` through the `take_with_info` slot, the
4815 /// sample's `rmw_message_info_t` converted to a [`MessageInfo`].
4816 ///
4817 /// The same pending-status and event-poll rules as `take_serialized`, so
4818 /// a caller cannot tell the two entry points apart except by the metadata.
4819 fn take_serialized_via_slot(
4820 &mut self,
4821 buf: &mut [u8],
4822 take_with_info: unsafe extern "C" fn(
4823 *const generated::rmw_subscription_t,
4824 *mut generated::rmw_mut_byte_span_t,
4825 *mut bool,
4826 *mut generated::rmw_message_info_t,
4827 ) -> generated::rmw_ret_t,
4828 ) -> Result<Option<(usize, Option<MessageInfo>)>, TransportError> {
4829 if let Some(status) = self.pending_status.take() {
4830 return Err(status);
4831 }
4832 self.poll_status_events();
4833 let view = self.make_view();
4834 let mut taken = false;
4835 let mut span = generated::rmw_mut_byte_span_t {
4836 data: buf.as_mut_ptr(),
4837 capacity: buf.len(),
4838 len: 0,
4839 };
4840 // SAFETY: an all-zero `rmw_message_info_t` is valid (null identifier,
4841 // zero gid, false flag); the backend overwrites it on a take.
4842 let mut raw: generated::rmw_message_info_t = unsafe { core::mem::zeroed() };
4843 // SAFETY: `view` borrows this subscription's backend handle, `span`
4844 // points into `buf` with its true capacity, and every out-pointer is
4845 // a live local for the duration of the call.
4846 let rc = unsafe { take_with_info(&view, &mut span, &mut taken, &mut raw) };
4847 if rc != NROS_RMW_RET_OK {
4848 return Err(error_from_ret(rc));
4849 }
4850 if !taken {
4851 return Ok(None);
4852 }
4853 let len = checked_take_len(span.len, buf.len())?;
4854 Ok(Some((len, Some(message_info_from_raw(&raw)))))
4855 }
4856}
4857
4858/// Issue 1495 — `rmw_message_info_t` → [`MessageInfo`].
4859///
4860/// The ABI's "unsupported" sequence sentinel becomes 0, `MessageInfo`'s
4861/// default — it has no unsupported spelling, and a sentinel cast to `i64` would
4862/// read as `-1`, a sequence number nobody sent.
4863pub(crate) fn message_info_from_raw(raw: &generated::rmw_message_info_t) -> MessageInfo {
4864 const UNSUPPORTED: u64 = u64::MAX;
4865 let seq = |v: u64| if v == UNSUPPORTED { 0 } else { v as i64 };
4866 let mut info = MessageInfo::new();
4867 info.set_source_timestamp(nros_rmw::Time::from_nanos(raw.source_timestamp));
4868 info.set_received_timestamp(nros_rmw::Time::from_nanos(raw.received_timestamp));
4869 info.set_publication_sequence_number(seq(raw.publication_sequence_number));
4870 info.set_reception_sequence_number(seq(raw.reception_sequence_number));
4871 info.set_publisher_gid(raw.publisher_gid.data);
4872 info
4873}
4874
4875/// Issue 2081 — `rmw_service_info_t` → [`ServiceRequestInfo`].
4876///
4877/// The ABI spells "not reported" as ZERO (`rmw_service_info_t`'s doc), and the
4878/// Rust type as `None`: a timestamp of 0 and an all-zero writer GUID become
4879/// `None`, never `Some(0)`. A request id is reported when its GUID is — the
4880/// client sequence number alone identifies nothing.
4881pub(crate) fn service_info_from_raw(raw: &generated::rmw_service_info_t) -> ServiceRequestInfo {
4882 let ts = |ns: i64| (ns != 0).then(|| nros_rmw::Time::from_nanos(ns));
4883 let mut writer_guid = [0u8; REQUEST_WRITER_GUID_SIZE];
4884 for (dst, src) in writer_guid
4885 .iter_mut()
4886 .zip(raw.request_id.writer_guid.iter())
4887 {
4888 *dst = *src as u8;
4889 }
4890 ServiceRequestInfo {
4891 source_timestamp: ts(raw.source_timestamp),
4892 received_timestamp: ts(raw.received_timestamp),
4893 request_id: writer_guid.iter().any(|b| *b != 0).then_some(RequestId {
4894 writer_guid,
4895 sequence_number: raw.request_id.sequence_number,
4896 }),
4897 }
4898}
4899
4900impl CffiSubscription {
4901 fn make_view(&mut self) -> NrosRmwSubscription {
4902 NrosRmwSubscription {
4903 topic_name: self.topic_name_buf.as_ptr().cast(),
4904 type_name: self.type_name_buf.as_ptr().cast(),
4905 qos: self.qos,
4906 can_loan_messages: self.can_loan_messages,
4907 _reserved: [0u8; 7],
4908 backend_data: self.backend_data,
4909 }
4910 }
4911
4912 /// `make_view` from a shared borrow — the view is a by-value snapshot the
4913 /// backend reads and never writes through.
4914 fn view_shared(&self) -> NrosRmwSubscription {
4915 NrosRmwSubscription {
4916 topic_name: self.topic_name_buf.as_ptr().cast(),
4917 type_name: self.type_name_buf.as_ptr().cast(),
4918 qos: self.qos,
4919 can_loan_messages: self.can_loan_messages,
4920 _reserved: [0u8; 7],
4921 backend_data: self.backend_data,
4922 }
4923 }
4924
4925 /// Issue 1164 — record a callback the runtime will serve by polling
4926 /// `subscription_take_event`. Returns `Unsupported` when there is no poll
4927 /// slot either, or when `kind` is not a subscription-side kind.
4928 fn register_polled_event(
4929 &self,
4930 kind: nros_rmw::EventKind,
4931 cb: NrosRmwEventCallback,
4932 user_ctx: *mut c_void,
4933 ) -> Result<(), TransportError> {
4934 let Some(cb) = cb else {
4935 return Err(TransportError::Unsupported);
4936 };
4937 if self.vtable.subscription_take_event.is_none() {
4938 return Err(TransportError::Unsupported);
4939 }
4940 let Some(slot) = sub_event_slot(kind) else {
4941 return Err(TransportError::Unsupported);
4942 };
4943 self.polled_events[slot].set(Some(PolledEventReg { cb, user_ctx }));
4944 Ok(())
4945 }
4946
4947 /// Issue 1164 — drain `subscription_take_event` for every kind this
4948 /// subscription has a registered callback for, and fire the callbacks.
4949 ///
4950 /// Driven from `has_data` and `take_serialized`, which is literally what
4951 /// `subscriber.cpp` asks of a caller ("A caller polls them the way it
4952 /// already polls `has_data`") and the same pair the zenoh shim fires its
4953 /// own subscription events from. `has_data` is the executor's per-spin
4954 /// readiness scan, so a subscription owned by the dispatch loop is polled
4955 /// every spin without the application doing anything.
4956 ///
4957 /// The status is copied out of the backend before any callback runs, so
4958 /// no user code executes while the backend holds a lock of its own.
4959 fn poll_status_events(&self) {
4960 let Some(take) = self.vtable.subscription_take_event else {
4961 return;
4962 };
4963 if self.polling_events.replace(true) {
4964 return;
4965 }
4966 for (slot, kind) in SUB_EVENT_KINDS.iter().enumerate() {
4967 let Some(reg) = self.polled_events[slot].get() else {
4968 continue;
4969 };
4970 let cb = reg.cb;
4971 let view = self.view_shared();
4972 let mut payload = empty_event_payload();
4973 let mut taken = false;
4974 // SAFETY: `view` is a live snapshot of this subscription;
4975 // `payload` and `taken` are stack locals the slot writes through,
4976 // and the slot writes `payload` only when it sets `taken`.
4977 let rc = unsafe { take(&view, event_kind_to_c(*kind), &mut payload, &mut taken) };
4978 static SITE: StatusSite = StatusSite::new("subscription_take_event");
4979 if !status_ok(rc, &SITE) || !taken {
4980 continue;
4981 }
4982 // SAFETY: `cb` and `user_ctx` were supplied together at
4983 // registration; the registrant keeps `user_ctx` alive for the
4984 // entity's lifetime. `payload` outlives the call.
4985 unsafe { cb(event_kind_to_c(*kind), &payload, reg.user_ctx) };
4986 }
4987 self.polling_events.set(false);
4988 }
4989
4990 /// Phase 231 (RFC-0038) — drive the `process_raw_in_place` vtable slot,
4991 /// marshalling the Rust `FnOnce` through the C `ctx`/`cb`. A monomorphized
4992 /// trampoline takes the closure out of a stack `Option` cell and calls it
4993 /// with the borrowed slice. The named generic `G` is why the public trait
4994 /// method (which uses APIT) delegates here.
4995 fn run_process_in_place<G: FnOnce(&[u8])>(&mut self, f: G) -> Result<bool, TransportError> {
4996 let Some(slot) = self.vtable.process_raw_in_place else {
4997 return Err(TransportError::MessageTooLarge);
4998 };
4999 unsafe extern "C" fn cb_tramp<G: FnOnce(&[u8])>(
5000 ctx: *mut c_void,
5001 message: generated::rmw_byte_span_t,
5002 ) {
5003 let cell = unsafe { &mut *(ctx as *mut Option<G>) };
5004 if let Some(g) = cell.take() {
5005 g(unsafe { core::slice::from_raw_parts(message.data, message.len) });
5006 }
5007 }
5008 let mut cell: Option<G> = Some(f);
5009 let mut view = self.make_view();
5010 // Phase 376 W3.d step A — "processed one" arrives in the out-parameter.
5011 // The NO_DATA arm is gone: an empty subscription is now OK with
5012 // `processed = false`, which is what upstream's `taken = false` means.
5013 let mut processed = false;
5014 let rc = unsafe {
5015 slot(
5016 &mut view,
5017 &mut cell as *mut Option<G> as *mut c_void,
5018 Some(cb_tramp::<G>),
5019 &mut processed,
5020 )
5021 };
5022 if rc != NROS_RMW_RET_OK {
5023 return Err(error_from_ret(rc));
5024 }
5025 Ok(processed)
5026 }
5027
5028 pub fn topic_name(&self) -> &str {
5029 cstr_buf_to_str(&self.topic_name_buf)
5030 }
5031
5032 pub fn type_name(&self) -> &str {
5033 cstr_buf_to_str(&self.type_name_buf)
5034 }
5035
5036 pub fn qos(&self) -> NrosRmwQos {
5037 self.qos
5038 }
5039
5040 /// `true` iff the backend exposes the receive loan primitive.
5041 pub fn can_loan_messages(&self) -> bool {
5042 self.can_loan_messages
5043 }
5044}
5045
5046/// Read-only view returned by
5047/// [`CffiSubscription::try_borrow`]. Holds the backend's raw buffer +
5048/// opaque token until `Drop` fires `sub_release`.
5049#[cfg(feature = "lending")]
5050pub struct CffiView<'a> {
5051 buf: *const u8,
5052 len: usize,
5053 token: *mut generated::rmw_loan_token_t,
5054 subscriber: Option<&'a mut CffiSubscription>,
5055}
5056
5057#[cfg(feature = "lending")]
5058impl<'a> AsRef<[u8]> for CffiView<'a> {
5059 fn as_ref(&self) -> &[u8] {
5060 // SAFETY: `buf` came from `sub_borrow` with length `len`.
5061 // The borrow contract guarantees the buffer stays valid until
5062 // `sub_release` fires (in Drop). Lifetime `'a` borrows the
5063 // subscriber so the slice can't outlive the borrow.
5064 unsafe { core::slice::from_raw_parts(self.buf, self.len) }
5065 }
5066}
5067
5068#[cfg(feature = "lending")]
5069impl<'a> Drop for CffiView<'a> {
5070 fn drop(&mut self) {
5071 if let Some(sub) = self.subscriber.take()
5072 && let Some(release) = sub.vtable.return_loaned_message_from_subscription
5073 {
5074 let view = sub.make_view();
5075 // SAFETY: `token` paired with a prior `sub_borrow` on
5076 // this subscriber and the subscriber is still alive.
5077 let ret = unsafe { release(&view, self.token) };
5078 if ret != NROS_RMW_RET_OK {
5079 nros_log::log_error!(
5080 nros_log::get_logger("nros_rmw_cffi"),
5081 "return_loaned_message_from_subscription failed with {}; the sample may stay checked out",
5082 ret
5083 );
5084 }
5085 }
5086 }
5087}
5088
5089#[cfg(feature = "lending")]
5090impl nros_rmw::SlotBorrowing for CffiSubscription {
5091 type View<'a> = CffiView<'a>;
5092
5093 fn try_borrow(&mut self) -> Result<Option<CffiView<'_>>, TransportError> {
5094 let Some(borrow) = self.vtable.take_loaned_message else {
5095 // Phase 124.A — backend doesn't natively borrow; runtime
5096 // falls back to `take_serialized` into a staging buffer
5097 // (124.A.3). `None` lets the caller use the slow path.
5098 return Ok(None);
5099 };
5100 let view = self.make_view();
5101 let mut out_view = generated::rmw_byte_span_t {
5102 data: core::ptr::null(),
5103 len: 0,
5104 };
5105 let mut out_token: *mut generated::rmw_loan_token_t = core::ptr::null_mut();
5106 // SAFETY: vtable contract — borrowed pointers stay valid
5107 // until `sub_release` runs.
5108 // Phase 376 W3.b/W3.d step A — status returned, `taken` out. The old
5109 // shape carried the length TWICE (returned and written to `*out_len`)
5110 // and reconciled them with `min(rc, max(out_len, rc))`, which is `rc`
5111 // for every input — so a backend whose two answers disagreed had one
5112 // silently ignored. There is one length now.
5113 let mut taken = false;
5114 let rc = unsafe { borrow(&view, &mut out_view, &mut out_token, &mut taken) };
5115 if rc != NROS_RMW_RET_OK {
5116 return Err(error_from_ret(rc));
5117 }
5118 let (out_buf, len) = (out_view.data, out_view.len);
5119 if !taken || out_buf.is_null() {
5120 return Ok(None);
5121 }
5122 Ok(Some(CffiView {
5123 buf: out_buf,
5124 len,
5125 token: out_token,
5126 subscriber: Some(self),
5127 }))
5128 }
5129}
5130
5131/// A take reported more bytes than the buffer it was handed — issue 0773.
5132///
5133/// Every copying take passes the vtable BOTH a pointer and the capacity, so an
5134/// `out_len` above that capacity is an ABI violation by the backend: it was
5135/// told how much room there was. The Rust side used to take the number on
5136/// faith, and a Cyclone service reply of 1005 bytes into a 256-byte buffer
5137/// panicked the SERVER process with `range end index 1005 out of range for
5138/// slice of length 256`.
5139///
5140/// It fails rather than truncating. `&buf[..cap]` would hand the caller a
5141/// silently short message — a corrupted payload presented as a good one, which
5142/// is worse than a loud stop and is the shape issue 0757 spent a phase
5143/// removing. `BufferTooSmall` is already this crate's word for it (the batch
5144/// take pre-checks with the same variant), and a caller that wants the sample
5145/// raises its buffer knob.
5146fn checked_take_len(out_len: usize, cap: usize) -> Result<usize, TransportError> {
5147 if out_len > cap {
5148 return Err(TransportError::BufferTooSmall);
5149 }
5150 Ok(out_len)
5151}
5152
5153/// Issue 1612 — read the size a refused `take` says its sample needed.
5154///
5155/// `NROS_RMW_TAKE_LEN_UNKNOWN` (zero, which the caller pre-sets) is a backend
5156/// that cannot know, or one written before the rule. A value that would have
5157/// FIT is not a size anybody needed — a backend that wrote it broke the
5158/// contract — so it is reported as unknown too, rather than as a number the
5159/// drop log would print beside a buffer it is smaller than.
5160fn refused_len_from_span(len: usize, cap: usize) -> Option<usize> {
5161 (len != generated::NROS_RMW_TAKE_LEN_UNKNOWN as usize && len > cap).then_some(len)
5162}
5163
5164impl nros_rmw::Subscription for CffiSubscription {
5165 type Error = TransportError;
5166
5167 fn supports_process_in_place(&self) -> bool {
5168 self.supports_in_place
5169 }
5170
5171 fn process_raw_in_place(&mut self, f: impl FnOnce(&[u8])) -> Result<bool, Self::Error> {
5172 self.run_process_in_place(f)
5173 }
5174
5175 fn register_waker(&self, waker: &core::task::Waker) -> bool {
5176 // Issue 1940 — keep the waker here and point the backend at it,
5177 // through upstream's `set_on_new_message_callback` slot. The
5178 // slot is re-armed on EVERY call, not only the first: a handle that
5179 // moved since the last registration (into an arena slot, say) hands
5180 // the backend its CURRENT address, so a registration can never
5181 // outlive the place it points at for longer than one re-poll.
5182 let Some(set_wake) = self.vtable.subscription_set_on_new_message_callback else {
5183 return false;
5184 };
5185 self.entity_waker.register(waker);
5186 let view_ptr = self as *const _ as *mut Self;
5187 let mut view = unsafe { (*view_ptr).make_view() };
5188 let rc = unsafe {
5189 set_wake(
5190 &mut view,
5191 Some(runtime_entity_wake),
5192 self.entity_waker.as_user_data(),
5193 )
5194 };
5195 rc == NROS_RMW_RET_OK
5196 }
5197
5198 fn has_data(&self) -> bool {
5199 // Issue 1164 — the readiness scan is the poll point `subscriber.cpp`
5200 // names for `subscription_take_event`. No-op unless something is
5201 // registered on a backend that fills that slot.
5202 self.poll_status_events();
5203 // has_data takes &mut to match the C signature; cast away const
5204 // because the predicate is logically read-only — backends must
5205 // not mutate state from has_data.
5206 let view_ptr = self as *const _ as *mut Self;
5207 let mut view = unsafe { (*view_ptr).make_view() };
5208 // Phase 376 W3.d step A — the flag arrives in an out-parameter and the
5209 // return is a plain status. The old `rc > 0` read a NEGATIVE error as
5210 // "no data", which is the same answer an empty subscription gives: a
5211 // broken backend and a quiet one were indistinguishable here. The trait
5212 // returns `bool` and has no error channel, so an error still maps to
5213 // false — but now by an explicit decision rather than by the arithmetic
5214 // happening to say so. Issue 2410: and the first one is REPORTED, since
5215 // issue 2403's EBADF read as a quiet topic for an entire investigation.
5216 let mut has = false;
5217 let rc =
5218 unsafe { (self.vtable.has_data.expect("rmw vtable: has_data"))(&mut view, &mut has) };
5219 static SITE: StatusSite = StatusSite::new("subscription has_data");
5220 status_ok(rc, &SITE) && has
5221 }
5222
5223 fn take_serialized(&mut self, buf: &mut [u8]) -> Result<Option<usize>, TransportError> {
5224 // Issue 0971 — a status parked by an earlier `take_sequence` is
5225 // delivered here too, so a caller that mixes the two entry points still
5226 // hears about it rather than having it silently outlive the batch that
5227 // produced it. Cyclone's native flag is checked at both of its take
5228 // entry points for the same reason.
5229 if let Some(status) = self.pending_status.take() {
5230 return Err(status);
5231 }
5232 // Issue 1164 — the second poll point, mirroring the zenoh shim, which
5233 // fires its subscription events from `take_serialized` as well as from
5234 // `has_data`. A caller that only takes still sees its events.
5235 self.poll_status_events();
5236 let mut view = self.make_view();
5237 // Phase 376 W3.b/W3.d step A — `take` reports through out-parameters.
5238 // Three arms collapse into one: NO_DATA, a negative error, and the
5239 // `rc == 0` case that used to mean "zero bytes, treat as nothing" are
5240 // now `taken = false`, a status check, and `taken = true` with
5241 // `out_len == 0` respectively. That last one is a real behaviour fix:
5242 // a legitimately EMPTY message was previously indistinguishable from an
5243 // empty subscription.
5244 let mut taken = false;
5245 // phase-406 W2 — by POINTER: the callee sets `len`, and a by-value copy
5246 // would discard it. `capacity` in, `len` out.
5247 //
5248 // Issue 1612 — `len` starts at `NROS_RMW_TAKE_LEN_UNKNOWN`, and that is
5249 // load-bearing: it is what lets a backend that never writes `len` on a
5250 // refusal report "unknown" instead of whatever was on the stack.
5251 let mut span = generated::rmw_mut_byte_span_t {
5252 data: buf.as_mut_ptr(),
5253 capacity: buf.len(),
5254 len: generated::NROS_RMW_TAKE_LEN_UNKNOWN as usize,
5255 };
5256 let rc = unsafe {
5257 (self.vtable.take.expect("rmw vtable: take"))(&mut view, &mut span, &mut taken)
5258 };
5259 let out_len = span.len;
5260 if rc != NROS_RMW_RET_OK {
5261 if rc == NROS_RMW_RET_BUFFER_TOO_SMALL {
5262 self.refused_len = refused_len_from_span(out_len, buf.len());
5263 }
5264 return Err(error_from_ret(rc));
5265 }
5266 if !taken {
5267 return Ok(None);
5268 }
5269 // An over-long `out_len` (issue 0773) is refused here, and the number
5270 // that broke the contract is exactly the size the sample needed.
5271 checked_take_len(out_len, buf.len())
5272 .inspect_err(|_| self.refused_len = Some(out_len))
5273 .map(Some)
5274 }
5275
5276 fn refused_sample_len(&self) -> Option<usize> {
5277 self.refused_len
5278 }
5279
5280 fn take_serialized_with_info(
5281 &mut self,
5282 buf: &mut [u8],
5283 ) -> Result<Option<(usize, Option<MessageInfo>)>, TransportError> {
5284 // Issue 1495 — a backend that fills the `take_with_info` slot reports
5285 // metadata through caller-owned storage, which is the only channel a
5286 // pure C/C++ backend has: the side table below is written by the Rust
5287 // adapter alone, so before this dispatch existed Cyclone's
5288 // `message_info()` callback saw `None` for every sample. A NULL slot
5289 // keeps the side-table path unchanged (the Rust adapter leaves it
5290 // NULL and writes the table).
5291 if let Some(take_with_info) = self.vtable.take_with_info {
5292 return self.take_serialized_via_slot(buf, take_with_info);
5293 }
5294 let key = self.backend_data as usize;
5295 self.take_serialized(buf)
5296 .map(|opt| opt.map(|len| (len, take_cffi_message_info(key))))
5297 }
5298
5299 #[cfg(all(feature = "alloc", feature = "safety-e2e"))]
5300 fn take_validated(
5301 &mut self,
5302 buf: &mut [u8],
5303 ) -> Result<Option<(usize, nros_rmw::IntegrityStatus)>, Self::Error> {
5304 let key = self.backend_data as usize;
5305 request_cffi_integrity_status(key);
5306 self.take_serialized(buf).map(|opt| {
5307 opt.map(|len| {
5308 (
5309 len,
5310 take_cffi_integrity_status(key).unwrap_or(nros_rmw::IntegrityStatus {
5311 gap: 0,
5312 duplicate: false,
5313 crc_valid: None,
5314 }),
5315 )
5316 })
5317 })
5318 }
5319
5320 fn take_sequence(
5321 &mut self,
5322 buf: &mut [u8],
5323 per_msg_cap: usize,
5324 max_msgs: usize,
5325 out_lens: &mut [usize],
5326 ) -> Result<usize, TransportError> {
5327 // Phase 124.D.2 — runtime fallback. If the backend exposes
5328 // `take_sequence` natively, call it in one hop; otherwise
5329 // delegate to the trait's default body which loop-drives
5330 // `take_serialized`. Either way the caller sees the same shape:
5331 // contiguous slot block + per-slot length array + count
5332 // return.
5333 if let Some(f) = self.vtable.take_sequence {
5334 if per_msg_cap == 0 || max_msgs == 0 {
5335 return Ok(0);
5336 }
5337 let limit = max_msgs.min(out_lens.len());
5338 if buf.len() < limit.saturating_mul(per_msg_cap) {
5339 return Err(TransportError::BufferTooSmall);
5340 }
5341 let view = self.make_view();
5342 // Phase 376 W3.b/W3.d step A — the count arrives in `taken`.
5343 let mut taken = 0usize;
5344 let rc = unsafe {
5345 f(
5346 &view,
5347 buf.as_mut_ptr(),
5348 per_msg_cap,
5349 limit,
5350 out_lens.as_mut_ptr(),
5351 &mut taken,
5352 )
5353 };
5354 if rc != NROS_RMW_RET_OK {
5355 // Issue 1612 — the batch slot has no span to carry a size, so a
5356 // refusal here is an UNKNOWN one; an earlier take's number must
5357 // not be read as this sample's.
5358 self.refused_len = None;
5359 return Err(error_from_ret(rc));
5360 }
5361 return Ok(taken);
5362 }
5363 // Phase 124.D.2 — `take_serialized` loop fallback. Inlined
5364 // here (rather than dispatching back through the trait
5365 // default body) so the recursion is structurally
5366 // impossible — `Subscription::take_sequence` on
5367 // `CffiSubscription` is THIS function, and forwarding to
5368 // the default body would deadlock the override.
5369 if per_msg_cap == 0 || max_msgs == 0 {
5370 return Ok(0);
5371 }
5372 // Issue 0971 — a status parked by an earlier drain is delivered before
5373 // any new take, and taking nothing this call is the point: the caller
5374 // has to be able to act on it before it asks for more.
5375 if let Some(status) = self.pending_status.take() {
5376 return Err(status);
5377 }
5378 let limit = max_msgs.min(out_lens.len());
5379 if buf.len() < limit.saturating_mul(per_msg_cap) {
5380 return Err(TransportError::BufferTooSmall);
5381 }
5382 let mut count = 0;
5383 for i in 0..limit {
5384 let slot = &mut buf[i * per_msg_cap..(i + 1) * per_msg_cap];
5385 match self.take_serialized(slot) {
5386 Ok(Some(len)) => {
5387 out_lens[i] = len;
5388 count += 1;
5389 }
5390 Ok(None) => break,
5391 // Issue 0971 — this arm used to be `?`, which discarded `count`
5392 // and reported the error, so a caller could not tell how many
5393 // of the slots it can see are valid. The messages already
5394 // written are real and are reported; the status is parked for
5395 // the next call. With nothing delivered yet there is no count
5396 // worth protecting, so it goes out immediately — which is also
5397 // what makes the single-message case identical to `take_serialized`.
5398 Err(e) => {
5399 if count == 0 {
5400 return Err(e);
5401 }
5402 self.pending_status = Some(e);
5403 break;
5404 }
5405 }
5406 }
5407 Ok(count)
5408 }
5409
5410 fn deserialization_error(&self) -> TransportError {
5411 TransportError::DeserializationError
5412 }
5413
5414 fn unsupported_event_error(&self) -> TransportError {
5415 TransportError::Unsupported
5416 }
5417
5418 unsafe fn register_event_callback(
5419 &mut self,
5420 kind: nros_rmw::EventKind,
5421 deadline_ms: u32,
5422 cb: nros_rmw::EventCallback,
5423 user_ctx: *mut core::ffi::c_void,
5424 ) -> Result<(), TransportError> {
5425 let view = self.make_view();
5426 let cb: NrosRmwEventCallback = Some(unsafe {
5427 core::mem::transmute::<
5428 nros_rmw::EventCallback,
5429 unsafe extern "C" fn(NrosRmwEventKind, *const NrosRmwEventPayload, *mut c_void),
5430 >(cb)
5431 });
5432 // Issue 0349 — a NULL slot means the backend does not implement this
5433 // OPTIONAL capability (xrce NULLs all three). Report it as
5434 // `Unsupported`; never panic, and never make it a registration error.
5435 //
5436 // Issue 1164 — NULL is ALSO the deliberate answer of a backend that
5437 // fills `subscription_take_event` instead. cyclonedds is one, and
5438 // says so where it declines: "So `*_event_init` stays NULL here and
5439 // these two slots carry the surface." Serve those here instead of
5440 // refusing them.
5441 let Some(register) = self.vtable.subscription_event_init else {
5442 return self.register_polled_event(kind, cb, user_ctx);
5443 };
5444 let ret = unsafe { register(&view, event_kind_to_c(kind), deadline_ms, cb, user_ctx) };
5445 if ret != NROS_RMW_RET_OK {
5446 return Err(error_from_ret(ret));
5447 }
5448 Ok(())
5449 }
5450
5451 fn supports_event(&self, kind: nros_rmw::EventKind) -> bool {
5452 // Issue 1164 — slot granularity; see `CffiPublisher::supports_event`
5453 // for why that is the honest answer and why a flat `false` was not.
5454 sub_event_slot(kind).is_some() && backend_event_type_is_supported(self.vtable, kind)
5455 }
5456
5457 /// The profile the backend GRANTED. See
5458 /// [`CffiPublisher::actual_qos`](Publisher::actual_qos).
5459 fn actual_qos(&self) -> QoSProfile {
5460 qos_from_c(&self.actual_qos)
5461 }
5462
5463 /// Upstream `rmw_subscription_count_matched_publishers`, through the
5464 /// vtable slot. See [`CffiPublisher::count_matched_subscriptions`]
5465 /// (`Publisher::count_matched_subscriptions`).
5466 fn count_matched_publishers(&self) -> Result<usize, TransportError> {
5467 let Some(count) = self.vtable.subscription_count_matched_publishers else {
5468 return Err(TransportError::Unsupported);
5469 };
5470 let view = self.view_shared();
5471 let mut n: usize = 0;
5472 // SAFETY: the slot is the backend's, called with a live view of this
5473 // entity and an out-pointer to a local, per the vtable contract.
5474 let ret = unsafe { count(&view, &mut n) };
5475 if ret != NROS_RMW_RET_OK {
5476 return Err(error_from_ret(ret));
5477 }
5478 Ok(n)
5479 }
5480}
5481
5482impl Drop for CffiSubscription {
5483 fn drop(&mut self) {
5484 if !self.backend_data.is_null() {
5485 clear_cffi_message_info(self.backend_data as usize);
5486 let mut view = self.make_view();
5487 let ret = unsafe {
5488 (self
5489 .vtable
5490 .destroy_subscription
5491 .expect("rmw vtable: destroy_subscription"))(&mut view)
5492 };
5493 // Phase 376 W5 — the slot reports now, and `Drop` is the one caller
5494 // that cannot propagate. Logging is not a consolation prize: a
5495 // teardown that failed is a leak, and a leak with no message
5496 // surfaces later as an allocation failure with no provenance.
5497 // `nros_log`, never std stdio — issue 0589.
5498 if ret != NROS_RMW_RET_OK {
5499 nros_log::log_error!(
5500 nros_log::get_logger("nros_rmw_cffi"),
5501 "destroy_subscription failed with {}; the backend may have leaked the subscription",
5502 ret
5503 );
5504 }
5505 }
5506 }
5507}
5508
5509// ============================================================================
5510// CffiService
5511// ============================================================================
5512
5513/// Service server backed by a C vtable.
5514pub struct CffiService {
5515 vtable: &'static NrosRmwVtable,
5516 service_name_buf: [u8; NAME_BUF_LEN],
5517 type_name_buf: [u8; NAME_BUF_LEN],
5518 backend_data: *mut c_void,
5519 /// The profiles the backend GRANTED for this entity's TWO endpoints.
5520 ///
5521 /// `create_*` takes ONE profile and builds a request endpoint and a
5522 /// response endpoint from it; they negotiate against different peers and
5523 /// may be granted different things, and neither `rmw_service_t` nor
5524 /// `rmw_client_t` has a `qos` field, so this is the only place the
5525 /// per-direction answer exists. `qos_unknown_c()` where the backend has no
5526 /// read-back slot.
5527 request_qos: NrosRmwQos,
5528 /// See [`Self::request_qos`].
5529 response_qos: NrosRmwQos,
5530 /// Issue 1632 — what the last refused `take_request` said the request
5531 /// needed, as [`ServiceTrait::refused_request_len`] reports it.
5532 refused_len: Option<usize>,
5533 /// Issue 1940 — see [`CffiSubscription`]'s field of the same name.
5534 entity_waker: WakerSlot,
5535 /// Issue 1942 — the metadata of the request the last successful
5536 /// `take_request` returned, as [`ServiceTrait::request_info`] reports it.
5537 request_info: ServiceRequestInfo,
5538}
5539
5540impl CffiService {
5541 fn make_view(&mut self) -> NrosRmwService {
5542 NrosRmwService {
5543 service_name: self.service_name_buf.as_ptr().cast(),
5544 type_name: self.type_name_buf.as_ptr().cast(),
5545 _reserved: [0u8; 8],
5546 backend_data: self.backend_data,
5547 }
5548 }
5549
5550 pub fn service_name(&self) -> &str {
5551 cstr_buf_to_str(&self.service_name_buf)
5552 }
5553
5554 pub fn type_name(&self) -> &str {
5555 cstr_buf_to_str(&self.type_name_buf)
5556 }
5557}
5558
5559impl ServiceTrait for CffiService {
5560 type Error = TransportError;
5561
5562 fn register_waker(&self, waker: &core::task::Waker) -> bool {
5563 // Issue 1940 — see `CffiSubscription::register_waker`.
5564 let Some(set_wake) = self.vtable.service_set_on_new_request_callback else {
5565 return false;
5566 };
5567 self.entity_waker.register(waker);
5568 let view_ptr = self as *const _ as *mut Self;
5569 let mut view = unsafe { (*view_ptr).make_view() };
5570 let rc = unsafe {
5571 set_wake(
5572 &mut view,
5573 Some(runtime_entity_wake),
5574 self.entity_waker.as_user_data(),
5575 )
5576 };
5577 rc == NROS_RMW_RET_OK
5578 }
5579
5580 fn has_request(&self) -> bool {
5581 let view_ptr = self as *const _ as *mut Self;
5582 let mut view = unsafe { (*view_ptr).make_view() };
5583 // Phase 376 W3.d step A — see `has_data` above for why an error maps to
5584 // false explicitly rather than through `rc > 0`.
5585 let mut has = false;
5586 let rc = unsafe {
5587 (self.vtable.has_request.expect("rmw vtable: has_request"))(&mut view, &mut has)
5588 };
5589 static SITE: StatusSite = StatusSite::new("service has_request");
5590 status_ok(rc, &SITE) && has
5591 }
5592
5593 fn take_request<'a>(
5594 &mut self,
5595 buf: &'a mut [u8],
5596 ) -> Result<Option<ServiceRequest<'a>>, TransportError> {
5597 let mut seq: i64 = 0;
5598 let mut view = self.make_view();
5599 // Phase 376 W3.b/W3.d step A — status returned, payload length and
5600 // `taken` in out-parameters. The `rc == 0` arm is gone with the same
5601 // fix `take` got: a zero-length REQUEST is a legitimate message and
5602 // used to be indistinguishable from an empty queue.
5603 // Issue 1632 — `len` starts at `NROS_RMW_TAKE_LEN_UNKNOWN`, so a
5604 // backend that never writes it on a refusal reports "unknown".
5605 let mut request_span = generated::rmw_mut_byte_span_t {
5606 data: buf.as_mut_ptr(),
5607 capacity: buf.len(),
5608 len: generated::NROS_RMW_TAKE_LEN_UNKNOWN as usize,
5609 };
5610 let mut taken = false;
5611 // Issue 2081 — a backend that fills `take_request_with_info` reports
5612 // the request's metadata in this caller-owned struct; one that does not
5613 // is taken through `take_request`, and only a Rust backend's side table
5614 // can then say anything.
5615 // SAFETY: an all-zero `rmw_service_info_t` is valid and means "nothing
5616 // reported"; the backend overwrites it on a take.
5617 let mut raw_info: generated::rmw_service_info_t = unsafe { core::mem::zeroed() };
5618 let with_info = self.vtable.take_request_with_info;
5619 let rc = unsafe {
5620 match with_info {
5621 Some(take_with_info) => take_with_info(
5622 &view,
5623 &mut request_span,
5624 &mut seq,
5625 &mut taken,
5626 &mut raw_info,
5627 ),
5628 None => (self.vtable.take_request.expect("rmw vtable: take_request"))(
5629 &mut view,
5630 &mut request_span,
5631 &mut seq,
5632 &mut taken,
5633 ),
5634 }
5635 };
5636 if rc != NROS_RMW_RET_OK {
5637 if rc == NROS_RMW_RET_BUFFER_TOO_SMALL {
5638 self.refused_len = refused_len_from_span(request_span.len, buf.len());
5639 }
5640 return Err(error_from_ret(rc));
5641 }
5642 if !taken {
5643 return Ok(None);
5644 }
5645 // Issue 2081 — the slot's struct when the backend fills the slot;
5646 // otherwise issue 1942's side table, which a Rust backend's adapter
5647 // writes for exactly this take and a pure C backend never does (so it
5648 // reads `NOT_REPORTED`).
5649 self.request_info = if with_info.is_some() {
5650 service_info_from_raw(&raw_info)
5651 } else {
5652 take_cffi_service_info(self.backend_data as usize)
5653 };
5654 let out_len = request_span.len;
5655 let len = checked_take_len(out_len, buf.len())
5656 .inspect_err(|_| self.refused_len = Some(out_len))?;
5657 Ok(Some(ServiceRequest {
5658 data: &buf[..len],
5659 sequence_number: seq,
5660 }))
5661 }
5662
5663 fn refused_request_len(&self) -> Option<usize> {
5664 self.refused_len
5665 }
5666
5667 fn request_info(&self) -> ServiceRequestInfo {
5668 self.request_info
5669 }
5670
5671 fn send_response(&mut self, sequence_number: i64, data: &[u8]) -> Result<(), TransportError> {
5672 let mut view = self.make_view();
5673 let ret = unsafe {
5674 (self
5675 .vtable
5676 .send_response
5677 .expect("rmw vtable: send_response"))(
5678 &mut view,
5679 sequence_number,
5680 generated::rmw_byte_span_t {
5681 data: data.as_ptr(),
5682 len: data.len(),
5683 },
5684 )
5685 };
5686 if ret != NROS_RMW_RET_OK {
5687 return Err(error_from_ret(ret));
5688 }
5689 Ok(())
5690 }
5691
5692 /// What the REQUEST endpoint — the subscription this service takes
5693 /// requests on — was granted.
5694 fn request_subscription_actual_qos(&self) -> QoSProfile {
5695 qos_from_c(&self.request_qos)
5696 }
5697
5698 /// What the RESPONSE endpoint — the publisher this service answers on —
5699 /// was granted. Not necessarily the same profile: one request built both
5700 /// endpoints, and they negotiate against different peers.
5701 fn response_publisher_actual_qos(&self) -> QoSProfile {
5702 qos_from_c(&self.response_qos)
5703 }
5704}
5705
5706impl Drop for CffiService {
5707 fn drop(&mut self) {
5708 if !self.backend_data.is_null() {
5709 // Issue 1942 — release the side-table slot the adapter may hold for
5710 // this service, as `CffiSubscription` does for its key.
5711 clear_cffi_message_info(self.backend_data as usize);
5712 let mut view = self.make_view();
5713 let ret = unsafe {
5714 (self
5715 .vtable
5716 .destroy_service
5717 .expect("rmw vtable: destroy_service"))(&mut view)
5718 };
5719 // Phase 376 W5 — the slot reports now, and `Drop` is the one caller
5720 // that cannot propagate. Logging is not a consolation prize: a
5721 // teardown that failed is a leak, and a leak with no message
5722 // surfaces later as an allocation failure with no provenance.
5723 // `nros_log`, never std stdio — issue 0589.
5724 if ret != NROS_RMW_RET_OK {
5725 nros_log::log_error!(
5726 nros_log::get_logger("nros_rmw_cffi"),
5727 "destroy_service failed with {}; the backend may have leaked the service",
5728 ret
5729 );
5730 }
5731 }
5732 }
5733}
5734
5735// ============================================================================
5736// CffiClient
5737// ============================================================================
5738
5739/// Service client backed by a C vtable.
5740pub struct CffiClient {
5741 vtable: &'static NrosRmwVtable,
5742 service_name_buf: [u8; NAME_BUF_LEN],
5743 type_name_buf: [u8; NAME_BUF_LEN],
5744 backend_data: *mut c_void,
5745 /// The profiles the backend GRANTED for this entity's TWO endpoints.
5746 ///
5747 /// `create_*` takes ONE profile and builds a request endpoint and a
5748 /// response endpoint from it; they negotiate against different peers and
5749 /// may be granted different things, and neither `rmw_service_t` nor
5750 /// `rmw_client_t` has a `qos` field, so this is the only place the
5751 /// per-direction answer exists. `qos_unknown_c()` where the backend has no
5752 /// read-back slot.
5753 request_qos: NrosRmwQos,
5754 /// See [`Self::request_qos`].
5755 response_qos: NrosRmwQos,
5756 /// Issue 1632 — what the last refused `take_response` said the reply
5757 /// needed, as [`ClientTrait::refused_response_len`] reports it.
5758 refused_len: Option<usize>,
5759 /// Issue 1940 — see [`CffiSubscription`]'s field of the same name.
5760 entity_waker: WakerSlot,
5761 /// Issue 2136 — the metadata of the reply the last `take_response_raw`
5762 /// returned, for [`ClientTrait::response_info`].
5763 response_info: ServiceRequestInfo,
5764}
5765
5766impl CffiClient {
5767 fn make_view(&mut self) -> NrosRmwClient {
5768 NrosRmwClient {
5769 service_name: self.service_name_buf.as_ptr().cast(),
5770 type_name: self.type_name_buf.as_ptr().cast(),
5771 _reserved: [0u8; 8],
5772 backend_data: self.backend_data,
5773 }
5774 }
5775
5776 pub fn service_name(&self) -> &str {
5777 cstr_buf_to_str(&self.service_name_buf)
5778 }
5779
5780 pub fn type_name(&self) -> &str {
5781 cstr_buf_to_str(&self.type_name_buf)
5782 }
5783}
5784
5785impl ClientTrait for CffiClient {
5786 type Error = TransportError;
5787
5788 fn register_waker(&self, waker: &core::task::Waker) -> bool {
5789 // Issue 1940 — see `CffiSubscription::register_waker`.
5790 let Some(set_wake) = self.vtable.client_set_on_new_response_callback else {
5791 return false;
5792 };
5793 self.entity_waker.register(waker);
5794 let view_ptr = self as *const _ as *mut Self;
5795 let mut view = unsafe { (*view_ptr).make_view() };
5796 let rc = unsafe {
5797 set_wake(
5798 &mut view,
5799 Some(runtime_entity_wake),
5800 self.entity_waker.as_user_data(),
5801 )
5802 };
5803 rc == NROS_RMW_RET_OK
5804 }
5805
5806 fn send_request_raw(&mut self, request: &[u8]) -> Result<i64, TransportError> {
5807 // Phase-301 (issue 0240) — `send_request_raw` +
5808 // `take_response_raw` is the ONE request/reply path (the
5809 // blocking `call_raw` slot is gone from the vtable). Backends
5810 // that omit the slot get `Unsupported`; the executor surfaces
5811 // the error instead of silently degrading.
5812 let Some(f) = self.vtable.send_request else {
5813 return Err(TransportError::Unsupported);
5814 };
5815 let view = self.make_view();
5816 // Issue 0778 — the id the backend assigned. Issue 2009 — pre-set to
5817 // `NROS_RMW_SEQUENCE_ID_UNKNOWN`, the way `take`'s `len` is pre-set to
5818 // `NROS_RMW_TAKE_LEN_UNKNOWN`: a backend that leaves it untouched now
5819 // reads as "no id", where it used to read as id 0 — a legal id that
5820 // the correlation layer would have matched against.
5821 let mut sequence_id: i64 = generated::NROS_RMW_SEQUENCE_ID_UNKNOWN;
5822 let rc = unsafe {
5823 f(
5824 &view,
5825 generated::rmw_byte_span_t {
5826 data: request.as_ptr(),
5827 len: request.len(),
5828 },
5829 &mut sequence_id,
5830 )
5831 };
5832 if rc != NROS_RMW_RET_OK {
5833 return Err(error_from_ret(rc));
5834 }
5835 Ok(sequence_id)
5836 }
5837
5838 fn take_response_raw(
5839 &mut self,
5840 reply_buf: &mut [u8],
5841 ) -> Result<Option<(usize, i64)>, TransportError> {
5842 // Non-blocking poll only. NULL slot = backend doesn't implement
5843 // the service-client path; surface Unsupported.
5844 let Some(f) = self.vtable.take_response else {
5845 return Err(TransportError::Unsupported);
5846 };
5847 let view = self.make_view();
5848 // Phase 376 W3.b/W3.d step A — see `take_request`.
5849 // Issue 1632 — pre-set to UNKNOWN, as in `take_request`.
5850 let mut reply_span = generated::rmw_mut_byte_span_t {
5851 data: reply_buf.as_mut_ptr(),
5852 capacity: reply_buf.len(),
5853 len: generated::NROS_RMW_TAKE_LEN_UNKNOWN as usize,
5854 };
5855 let mut taken = false;
5856 // Issue 2009 — see `send_request_raw`.
5857 let mut seq: i64 = generated::NROS_RMW_SEQUENCE_ID_UNKNOWN;
5858 // Issue 2136 — a backend that fills `take_response_with_info` reports
5859 // the reply's metadata in this caller-owned struct; one that does not
5860 // is taken through `take_response` and reports nothing.
5861 // SAFETY: an all-zero `rmw_service_info_t` is valid and means "nothing
5862 // reported"; the backend overwrites it on a take.
5863 let mut raw_info: generated::rmw_service_info_t = unsafe { core::mem::zeroed() };
5864 let with_info = self.vtable.take_response_with_info;
5865 let rc = unsafe {
5866 match with_info {
5867 Some(take_with_info) => {
5868 take_with_info(&view, &mut reply_span, &mut seq, &mut taken, &mut raw_info)
5869 }
5870 None => f(&view, &mut reply_span, &mut seq, &mut taken),
5871 }
5872 };
5873 if rc != NROS_RMW_RET_OK {
5874 if rc == NROS_RMW_RET_BUFFER_TOO_SMALL {
5875 self.refused_len = refused_len_from_span(reply_span.len, reply_buf.len());
5876 }
5877 return Err(error_from_ret(rc));
5878 }
5879 if !taken {
5880 return Ok(None);
5881 }
5882 // Issue 2136 — this reply's metadata: the slot's struct when the
5883 // backend fills the slot, `NOT_REPORTED` when it does not.
5884 self.response_info = if with_info.is_some() {
5885 service_info_from_raw(&raw_info)
5886 } else {
5887 ServiceRequestInfo::NOT_REPORTED
5888 };
5889 let out_len = reply_span.len;
5890 let len = checked_take_len(out_len, reply_buf.len())
5891 .inspect_err(|_| self.refused_len = Some(out_len))?;
5892 Ok(Some((len, seq)))
5893 }
5894
5895 fn refused_response_len(&self) -> Option<usize> {
5896 self.refused_len
5897 }
5898
5899 fn response_info(&self) -> ServiceRequestInfo {
5900 self.response_info
5901 }
5902
5903 fn service_is_ready(&self) -> Result<bool, TransportError> {
5904 let Some(f) = self.vtable.service_server_is_available else {
5905 return Err(TransportError::Unsupported);
5906 };
5907 // SAFETY: `f` accepts a `*mut NrosRmwClient`. We
5908 // construct a transient view from this client's fields the
5909 // same way `make_view` does, but on `&self` (no mutation
5910 // required for a graph probe). The borrowed pointers all
5911 // alias into `&self`, so the lifetime is bounded by the
5912 // call.
5913 let view = NrosRmwClient {
5914 service_name: self.service_name_buf.as_ptr().cast(),
5915 type_name: self.type_name_buf.as_ptr().cast(),
5916 _reserved: [0u8; 8],
5917 backend_data: self.backend_data,
5918 };
5919 // Phase 376 W3.d step A — the slot answers through an out-parameter and
5920 // returns a plain status, so there is no non-spec value left to be
5921 // lenient about: the old arm treating "any positive other than 1" as
5922 // available existed only because a count and a status shared one int.
5923 let mut available = false;
5924 let rc = unsafe { f(&view, &mut available) };
5925 if rc != NROS_RMW_RET_OK {
5926 return Err(error_from_ret(rc));
5927 }
5928 Ok(available)
5929 }
5930
5931 /// Issue 1978 — upstream (Jazzy) `rmw_get_gid_for_client`, through the
5932 /// `get_gid_for_client` slot. The client twin of
5933 /// [`CffiPublisher::get_gid`](Publisher::get_gid); a NULL slot answers
5934 /// `Unsupported`, never an all-zero gid.
5935 fn get_gid(&self) -> Result<[u8; nros_rmw::PUBLISHER_GID_SIZE], TransportError> {
5936 let Some(f) = self.vtable.get_gid_for_client else {
5937 return Err(TransportError::Unsupported);
5938 };
5939 // Same transient `&self` view as `service_is_ready` above.
5940 let view = NrosRmwClient {
5941 service_name: self.service_name_buf.as_ptr().cast(),
5942 type_name: self.type_name_buf.as_ptr().cast(),
5943 _reserved: [0u8; 8],
5944 backend_data: self.backend_data,
5945 };
5946 let mut gid = NrosRmwGid {
5947 implementation_identifier: core::ptr::null(),
5948 data: [0u8; nros_rmw::PUBLISHER_GID_SIZE],
5949 };
5950 let rc = unsafe { f(&view, &mut gid) };
5951 if rc != NROS_RMW_RET_OK {
5952 return Err(error_from_ret(rc));
5953 }
5954 Ok(gid.data)
5955 }
5956
5957 /// What the REQUEST endpoint — the publisher this client sends requests on
5958 /// — was granted.
5959 fn request_publisher_actual_qos(&self) -> QoSProfile {
5960 qos_from_c(&self.request_qos)
5961 }
5962
5963 /// What the RESPONSE endpoint — the subscription this client takes replies
5964 /// on — was granted. See [`Self::request_publisher_actual_qos`].
5965 fn response_subscription_actual_qos(&self) -> QoSProfile {
5966 qos_from_c(&self.response_qos)
5967 }
5968}
5969
5970impl Drop for CffiClient {
5971 fn drop(&mut self) {
5972 if !self.backend_data.is_null() {
5973 let mut view = self.make_view();
5974 let ret = unsafe {
5975 (self
5976 .vtable
5977 .destroy_client
5978 .expect("rmw vtable: destroy_client"))(&mut view)
5979 };
5980 // Phase 376 W5 — the slot reports now, and `Drop` is the one caller
5981 // that cannot propagate. Logging is not a consolation prize: a
5982 // teardown that failed is a leak, and a leak with no message
5983 // surfaces later as an allocation failure with no provenance.
5984 // `nros_log`, never std stdio — issue 0589.
5985 if ret != NROS_RMW_RET_OK {
5986 nros_log::log_error!(
5987 nros_log::get_logger("nros_rmw_cffi"),
5988 "destroy_client failed with {}; the backend may have leaked the client",
5989 ret
5990 );
5991 }
5992 }
5993 }
5994}
5995
5996// ============================================================================
5997// Factory
5998// ============================================================================
5999
6000/// RMW factory for the C function table backend.
6001#[derive(Default)]
6002pub struct CffiRmw;
6003
6004impl nros_rmw::Rmw for CffiRmw {
6005 type Session = CffiSession;
6006 type Error = TransportError;
6007
6008 fn open(self, config: &nros_rmw::RmwConfig) -> Result<CffiSession, TransportError> {
6009 // issue 0331 — the wire values are specified by
6010 // `nros_rmw_session_mode_t` in rmw_vtable.h; keep this match aligned
6011 // with it rather than restating bare literals.
6012 let mode = match config.mode {
6013 nros_rmw::SessionMode::Client => {
6014 generated::nros_rmw_session_mode_t::NROS_RMW_SESSION_MODE_CLIENT as u8
6015 }
6016 nros_rmw::SessionMode::Peer => {
6017 generated::nros_rmw_session_mode_t::NROS_RMW_SESSION_MODE_PEER as u8
6018 }
6019 };
6020 // phase-206 W3 — forward `config.properties` instead of dropping it.
6021 // This was the outbound half of the same silence the cffi adapter had
6022 // on the inbound side: the trait handed us properties, and the seam
6023 // threw them away without a word.
6024 // Issue 1444 — `config.namespace` used to stop here. `Executor::open`
6025 // fills `RmwConfig { namespace: config.namespace, .. }`, and this seam
6026 // read every other field and not that one, so the session's own
6027 // liveliness token sat at the ROOT on every namespaced image — visible
6028 // as an EXTRA `ros2 node list` line rather than as a wrong one.
6029 CffiSession::open_with_properties(
6030 config.locator,
6031 mode,
6032 config.domain_id,
6033 config.node_name,
6034 config.namespace,
6035 config.properties,
6036 )
6037 .and_then(refuse_without_readiness)
6038 }
6039}
6040
6041/// A runtime session must state how it becomes
6042/// ready: `Notify` (the backend calls the executor's wake callback on an
6043/// arrival) or `Waitable` (a handle the port parks on). A session that states
6044/// neither could only be drained by blocking inside its own receive, which
6045/// no deadline and no other session can end, so nano-ros cannot keep its
6046/// real-time wait promise over it. It is refused at open, by name, instead of
6047/// parked on blindly.
6048///
6049/// Every runtime open goes through [`CffiRmw`] (the executor's, an extra
6050/// session's, the C/C++ support context's), so this is the one place the
6051/// rule is asked. [`CffiSession`]'s own constructors stay unchecked: they are
6052/// the seam a backend's own tests drive directly.
6053pub fn refuse_without_readiness(session: CffiSession) -> Result<CffiSession, TransportError> {
6054 use nros_rmw::Session as _;
6055 if matches!(session.readiness_source(), nros_rmw::ReadinessSource::None) {
6056 // RFC-0113 D5
6057 nros_log::log_error!(
6058 nros_log::get_logger("nros_rmw_cffi"),
6059 "the session states no readiness form: its backend neither calls a wake \
6060 callback on an arrival nor reports a handle to park on, so an executor \
6061 over it could only block inside its receive. Refused. \
6062 Give the transport a receive notification (for a custom XRCE transport, \
6063 `nros_rmw_xrce_set_custom_transport_rx_notify`)."
6064 );
6065 // Dropping the session closes it.
6066 return Err(TransportError::Unsupported);
6067 }
6068 Ok(session)
6069}
6070
6071impl CffiRmw {
6072 /// Open a session against a named backend.
6073 /// `rmw_name` selects an entry from the registry populated by
6074 /// `nros_rmw_cffi_register_named`.
6075 pub fn open_with_rmw(
6076 rmw_name: &str,
6077 config: &nros_rmw::RmwConfig,
6078 ) -> Result<CffiSession, TransportError> {
6079 let mode = match config.mode {
6080 nros_rmw::SessionMode::Client => 0u8,
6081 nros_rmw::SessionMode::Peer => 1u8,
6082 };
6083 CffiSession::open_named_with_properties(
6084 rmw_name,
6085 config.locator,
6086 mode,
6087 config.domain_id,
6088 config.node_name,
6089 config.namespace,
6090 config.properties,
6091 )
6092 .and_then(refuse_without_readiness)
6093 }
6094}
6095
6096// ============================================================================
6097// Phase 102.5 — typed-struct roundtrip test
6098// ============================================================================
6099//
6100// Verifies the visible-struct contract end-to-end:
6101// 1. Runtime fills `topic_name` / `type_name` / `qos` before
6102// `create_publisher`.
6103// 2. Backend's `create_publisher` writes `backend_data` and
6104// `can_loan_messages` into the same struct.
6105// 3. Rust accessors (`CffiPublisher::topic_name()`, `qos()`,
6106// `can_loan_messages()`) read back the values without any
6107// vtable callback.
6108
6109// ============================================================================
6110// Phase 376 W5 — backend log severity
6111// ============================================================================
6112
6113/// Map `nros_log`'s ladder onto upstream's.
6114///
6115/// `Trace` has no upstream counterpart and folds into `DEBUG`. Losing a
6116/// distinction upstream never had is better than inventing a value a ROS-side
6117/// caller could not produce — the mapping is deliberately lossy in the
6118/// direction that keeps the wire vocabulary standard.
6119#[must_use]
6120pub fn rmw_severity_of(severity: nros_log::Severity) -> generated::rmw_log_severity_t::Type {
6121 match severity {
6122 nros_log::Severity::Trace | nros_log::Severity::Debug => {
6123 generated::rmw_log_severity_t::RMW_LOG_SEVERITY_DEBUG
6124 }
6125 nros_log::Severity::Info => generated::rmw_log_severity_t::RMW_LOG_SEVERITY_INFO,
6126 nros_log::Severity::Warn => generated::rmw_log_severity_t::RMW_LOG_SEVERITY_WARN,
6127 nros_log::Severity::Error => generated::rmw_log_severity_t::RMW_LOG_SEVERITY_ERROR,
6128 nros_log::Severity::Fatal => generated::rmw_log_severity_t::RMW_LOG_SEVERITY_FATAL,
6129 }
6130}
6131
6132/// Set the verbosity of every registered BACKEND's own logging.
6133///
6134/// This is the backend's logger — Cyclone's `dds_log`, zenoh-pico's — not
6135/// `nros_log`, which is the runtime's and is set directly through
6136/// `nros_log::Logger::set_level` with no ABI involved.
6137///
6138/// Applies to EVERY registered backend, because an image may link more than one
6139/// (`nros_rmw_cffi_register_named`) and verbosity is a property of the process
6140/// rather than of a session. Upstream has no equivalent decision to make: it
6141/// loads one implementation.
6142///
6143/// Returns `Unsupported` when no registered backend implements the slot, the
6144/// first error any backend reported otherwise, and `Ok` when at least one
6145/// accepted it.
6146pub fn set_backend_log_severity(severity: nros_log::Severity) -> Result<(), TransportError> {
6147 const MAX: usize = 8;
6148 let mut names: [*const core::ffi::c_char; MAX] = [core::ptr::null(); MAX];
6149 // SAFETY: `names` is `MAX` entries and the callee writes at most that many.
6150 let n = unsafe { nros_rmw_cffi_registered_names(names.as_mut_ptr(), MAX) };
6151
6152 let wire = rmw_severity_of(severity);
6153 let mut applied = false;
6154 let mut first_err = None;
6155 for name in names.iter().take(n.min(MAX)) {
6156 // SAFETY: the registry hands back NUL-terminated static names.
6157 let vt = unsafe { nros_rmw_cffi_lookup(*name) };
6158 if vt.is_null() {
6159 continue;
6160 }
6161 // SAFETY: a non-null lookup yields a vtable valid for the image's life.
6162 let Some(f) = (unsafe { (*vt).set_log_severity }) else {
6163 continue;
6164 };
6165 // SAFETY: the slot takes a plain enum by value.
6166 let rc = unsafe { f(wire) };
6167 if rc == NROS_RMW_RET_OK {
6168 applied = true;
6169 } else if first_err.is_none() {
6170 first_err = Some(error_from_ret(rc));
6171 }
6172 }
6173
6174 match (applied, first_err) {
6175 (true, _) => Ok(()),
6176 (false, Some(e)) => Err(e),
6177 (false, None) => Err(TransportError::Unsupported),
6178 }
6179}
6180
6181// ============================================================================
6182// Phase 376 W4 — the two PURE functions, defined ONCE
6183// ============================================================================
6184//
6185// Declared in `nros/rmw_entity.h`, which explains at length why they are plain
6186// exported functions rather than vtable slots. The one-line version: a vtable
6187// slot is the mechanism for letting backends DIFFER, and these two must not.
6188// They compute over types the ABI defines, they take no entity, and they are
6189// wanted at create time before any backend has registered.
6190//
6191// Defined here for the same reason `nros_rmw_cffi_register_named` is: it keeps
6192// `nros-rmw-abi` a header-only INTERFACE target, with no compiled TU and no new
6193// link edge, and it keeps the implementation in ONE place — which is the whole
6194// point.
6195
6196/// Reason strings, one per clash bit. SELECTED, never formatted: upstream's
6197/// implementations `snprintf` their reason, which would pull the printf engine
6198/// into images that deliberately excluded it.
6199const CLASH_REASONS: &[(u32, &str)] = &[
6200 (
6201 generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_RELIABILITY,
6202 "reliability: publisher is best-effort, subscription requires reliable; ",
6203 ),
6204 (
6205 generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_DURABILITY,
6206 "durability: publisher is volatile, subscription requires transient-local; ",
6207 ),
6208 (
6209 generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_DEADLINE,
6210 "deadline: publisher's period is longer than the subscription requires; ",
6211 ),
6212 (
6213 generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_LIVELINESS_KIND,
6214 "liveliness: publisher's kind is weaker than the subscription requires; ",
6215 ),
6216 (
6217 generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_LIVELINESS_LEASE,
6218 "liveliness lease: publisher's lease is longer than the subscription requires; ",
6219 ),
6220];
6221
6222/// `0` means "unset/no check", and `NROS_RMW_DURATION_INFINITE_MS` means
6223/// explicit infinity — so neither can be compared as a plain number. Map both to
6224/// "infinitely lax" for an OFFERED duration and "infinitely tolerant" for a
6225/// REQUESTED one, which is the same thing: `u64::MAX`.
6226fn duration_or_infinite(ms: u32) -> u64 {
6227 if ms == 0 || u64::from(ms) == generated::NROS_RMW_DURATION_INFINITE_MS as u64 {
6228 u64::MAX
6229 } else {
6230 u64::from(ms)
6231 }
6232}
6233
6234/// How strict a liveliness kind is. A publisher must assert at least as
6235/// strongly as the subscription asks.
6236fn liveliness_strength(kind: u8) -> u8 {
6237 match u32::from(kind) {
6238 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_MANUAL_BY_TOPIC => 3,
6239 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_MANUAL_BY_NODE => 2,
6240 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_AUTOMATIC => 1,
6241 _ => 0,
6242 }
6243}
6244
6245/// The DDS request-offered rules, in one place.
6246/// Does this profile leave any policy UNDETERMINED?
6247///
6248/// Phase 376 W5/B2. `*_UNKNOWN` means "the backend could not read this back",
6249/// which is an ABSENCE, not a value: comparing it as if it were one produces a
6250/// confident wrong verdict. Upstream's answer to that is
6251/// `RMW_QOS_COMPATIBILITY_WARNING` — "these look compatible, but I could not
6252/// check everything" — which was unreachable here until there was a sentinel
6253/// that could trigger it.
6254fn qos_has_unknown(q: &NrosRmwQos) -> bool {
6255 i32::from(q.reliability) == generated::NROS_RMW_RELIABILITY_UNKNOWN
6256 || i32::from(q.durability) == generated::NROS_RMW_DURABILITY_UNKNOWN
6257 || i32::from(q.history) == generated::NROS_RMW_HISTORY_UNKNOWN
6258 || u32::from(q.liveliness_kind)
6259 == generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_UNKNOWN
6260}
6261
6262fn qos_clash_mask(offered: &NrosRmwQos, requested: &NrosRmwQos) -> u32 {
6263 let mut mask = 0u32;
6264 if requested.reliability == generated::NROS_RMW_RELIABILITY_RELIABLE as u8
6265 && offered.reliability == generated::NROS_RMW_RELIABILITY_BEST_EFFORT as u8
6266 {
6267 mask |= generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_RELIABILITY;
6268 }
6269 if requested.durability == generated::NROS_RMW_DURABILITY_TRANSIENT_LOCAL as u8
6270 && offered.durability == generated::NROS_RMW_DURABILITY_VOLATILE as u8
6271 {
6272 mask |= generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_DURABILITY;
6273 }
6274 // A publisher promising samples no more often than every N ms cannot
6275 // satisfy a subscription that demands one at least every M ms when N > M.
6276 if duration_or_infinite(offered.deadline_ms) > duration_or_infinite(requested.deadline_ms) {
6277 mask |= generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_DEADLINE;
6278 }
6279 if liveliness_strength(offered.liveliness_kind) < liveliness_strength(requested.liveliness_kind)
6280 {
6281 mask |= generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_LIVELINESS_KIND;
6282 }
6283 if duration_or_infinite(offered.liveliness_lease_ms)
6284 > duration_or_infinite(requested.liveliness_lease_ms)
6285 {
6286 mask |= generated::nros_rmw_qos_clash_t::NROS_RMW_QOS_CLASH_LIVELINESS_LEASE;
6287 }
6288 mask
6289}
6290
6291/// See `nros/rmw_entity.h`.
6292///
6293/// # Safety
6294/// `compatibility` and `clash_mask` must be valid for writes when non-NULL.
6295#[unsafe(no_mangle)]
6296pub unsafe extern "C" fn nros_rmw_qos_incompatibility_mask(
6297 offered: NrosRmwQos,
6298 requested: NrosRmwQos,
6299 compatibility: *mut generated::rmw_qos_compatibility_type_t::Type,
6300 clash_mask: *mut u32,
6301) -> NrosRmwRet {
6302 if compatibility.is_null() || clash_mask.is_null() {
6303 return NROS_RMW_RET_INVALID_ARGUMENT;
6304 }
6305 let mask = qos_clash_mask(&offered, &requested);
6306 let undetermined = qos_has_unknown(&offered) || qos_has_unknown(&requested);
6307 // SAFETY: both checked non-null above.
6308 unsafe {
6309 *clash_mask = mask;
6310 // A definite clash outranks an unknown: policies we COULD compare are
6311 // already incompatible, and reporting that as a warning would soften a
6312 // verdict the caller can act on.
6313 *compatibility = if mask != 0 {
6314 generated::rmw_qos_compatibility_type_t::RMW_QOS_COMPATIBILITY_ERROR
6315 } else if undetermined {
6316 generated::rmw_qos_compatibility_type_t::RMW_QOS_COMPATIBILITY_WARNING
6317 } else {
6318 generated::rmw_qos_compatibility_type_t::RMW_QOS_COMPATIBILITY_OK
6319 };
6320 }
6321 NROS_RMW_RET_OK
6322}
6323
6324/// See `nros/rmw_entity.h`.
6325///
6326/// # Safety
6327/// `compatibility` must be valid for writes; `reason` must be valid for
6328/// `reason_size` bytes when non-NULL.
6329#[unsafe(no_mangle)]
6330pub unsafe extern "C" fn rmw_qos_profile_check_compatible(
6331 publisher_profile: NrosRmwQos,
6332 subscription_profile: NrosRmwQos,
6333 compatibility: *mut generated::rmw_qos_compatibility_type_t::Type,
6334 reason: *mut core::ffi::c_char,
6335 reason_size: usize,
6336) -> NrosRmwRet {
6337 let mut mask = 0u32;
6338 // SAFETY: forwarding the caller's `compatibility` pointer, which the callee
6339 // null-checks; `mask` is a local.
6340 let rc = unsafe {
6341 nros_rmw_qos_incompatibility_mask(
6342 publisher_profile,
6343 subscription_profile,
6344 compatibility,
6345 &mut mask,
6346 )
6347 };
6348 if rc != NROS_RMW_RET_OK {
6349 return rc;
6350 }
6351 if reason.is_null() || reason_size == 0 {
6352 // The create-time path: the verdict is the whole answer.
6353 return NROS_RMW_RET_OK;
6354 }
6355 // Bounded copy, always NUL-terminated. Truncation is NOT an error: a
6356 // `BUFFER_TOO_SMALL` here would cost the caller the verdict, which is the
6357 // half that matters.
6358 let mut written = 0usize;
6359 for (bit, text) in CLASH_REASONS {
6360 if mask & bit == 0 {
6361 continue;
6362 }
6363 for byte in text.as_bytes() {
6364 if written + 1 >= reason_size {
6365 break;
6366 }
6367 // SAFETY: `written + 1 < reason_size`, so this and the NUL below are
6368 // both inside the caller's buffer.
6369 unsafe { *reason.add(written) = *byte as core::ffi::c_char };
6370 written += 1;
6371 }
6372 }
6373 // SAFETY: `written < reason_size` by the bound above.
6374 unsafe { *reason.add(written) = 0 };
6375 NROS_RMW_RET_OK
6376}
6377
6378/// See `nros/rmw_entity.h`.
6379///
6380/// # Safety
6381/// Both gids must be valid for reads and `result` valid for writes when
6382/// non-NULL.
6383#[unsafe(no_mangle)]
6384pub unsafe extern "C" fn rmw_compare_gids_equal(
6385 gid1: *const generated::rmw_gid_t,
6386 gid2: *const generated::rmw_gid_t,
6387 result: *mut bool,
6388) -> NrosRmwRet {
6389 if gid1.is_null() || gid2.is_null() || result.is_null() {
6390 return NROS_RMW_RET_INVALID_ARGUMENT;
6391 }
6392 // SAFETY: all three checked non-null above.
6393 let (a, b) = unsafe { (&*gid1, &*gid2) };
6394 // Identity first: gids from two backends are never equal, whatever their
6395 // bytes say. `register_named` admits several backends in one image, so this
6396 // is reachable here in a way it is not upstream.
6397 let same_impl = match (a.implementation_identifier, b.implementation_identifier) {
6398 (x, y) if x == y => true,
6399 (x, y) if x.is_null() || y.is_null() => false,
6400 // SAFETY: both non-null, and a backend's identifier is a static C string.
6401 (x, y) => unsafe { core::ffi::CStr::from_ptr(x) == core::ffi::CStr::from_ptr(y) },
6402 };
6403 // SAFETY: checked non-null above.
6404 unsafe { *result = same_impl && a.data == b.data };
6405 NROS_RMW_RET_OK
6406}
6407
6408#[cfg(test)]
6409#[allow(static_mut_refs)]
6410mod tests {
6411 use super::*;
6412 use nros_rmw::{Rmw, RmwConfig, Session, SessionMode, TopicInfo};
6413
6414 /// Issue 2815 -- one warning per distinct depth downgrade, not one per
6415 /// endpoint: twelve parameter-service endpoints asking 1000 and granted 4
6416 /// warn once, and a different pair warns again.
6417 #[cfg(feature = "alloc")]
6418 #[test]
6419 fn a_repeated_depth_downgrade_warns_once() {
6420 let last = core::sync::atomic::AtomicU32::new(0);
6421 assert!(first_depth_downgrade_in(&last, 1000, 4));
6422 for _ in 0..11 {
6423 assert!(!first_depth_downgrade_in(&last, 1000, 4));
6424 }
6425 assert!(
6426 first_depth_downgrade_in(&last, 10, 4),
6427 "a new pair is new information"
6428 );
6429 assert!(
6430 first_depth_downgrade_in(&last, 1000, 4),
6431 "and so is the old one again"
6432 );
6433 }
6434
6435 // Stub backend state. Statically allocated; the vtable's
6436 // `backend_data` round-trips a `&'static mut StubBackend`.
6437 static mut STUB_OPEN_CALLED: bool = false;
6438 static mut STUB_CREATE_PUB_CALLED: bool = false;
6439 static mut STUB_PUBLISH_CALLED: bool = false;
6440 static mut STUB_LAST_TOPIC_NAME: [u8; 64] = [0u8; 64];
6441 static mut STUB_LAST_TYPE_NAME: [u8; 64] = [0u8; 64];
6442 static mut STUB_LAST_QOS: NrosRmwQos = NrosRmwQos {
6443 reliability: 0,
6444 durability: 0,
6445 history: 0,
6446 liveliness_kind: 0,
6447 depth: 0,
6448 _reserved0: 0,
6449 deadline_ms: 0,
6450 lifespan_ms: 0,
6451 liveliness_lease_ms: 0,
6452 avoid_ros_namespace_conventions: 0,
6453 _reserved1: [0; 3],
6454 };
6455
6456 /// Read a null-terminated `*const u8` into the supplied byte
6457 /// buffer. Used by the stub backend to capture the topic / type
6458 /// names that the runtime hands it.
6459 unsafe fn copy_cstr(src: *const core::ffi::c_char, dst: &mut [u8]) {
6460 let src = src.cast::<u8>();
6461 let mut i = 0;
6462 while i < dst.len() {
6463 let b = unsafe { *src.add(i) };
6464 dst[i] = b;
6465 if b == 0 {
6466 break;
6467 }
6468 i += 1;
6469 }
6470 }
6471
6472 unsafe extern "C" fn stub_create_session(
6473 _locator: *const core::ffi::c_char,
6474 _mode: u8,
6475 _domain_id: u32,
6476 _node_name: *const core::ffi::c_char,
6477 _options: *const NrosRmwSessionOptions,
6478 out: *mut NrosRmwSession,
6479 ) -> NrosRmwRet {
6480 unsafe {
6481 STUB_OPEN_CALLED = true;
6482 (*out).backend_data = 0xDEAD_BEEFusize as *mut c_void;
6483 }
6484 NROS_RMW_RET_OK
6485 }
6486
6487 unsafe extern "C" fn stub_destroy_session(_session: *mut NrosRmwSession) -> NrosRmwRet {
6488 NROS_RMW_RET_OK
6489 }
6490
6491 unsafe extern "C" fn stub_drive_io(
6492 _session: *mut NrosRmwSession,
6493 _timeout_ms: i32,
6494 ) -> NrosRmwRet {
6495 NROS_RMW_RET_OK
6496 }
6497
6498 unsafe extern "C" fn stub_create_publisher(
6499 _session: *const NrosRmwNode,
6500 _type_support: *const generated::rmw_message_type_support_t,
6501 _topic_name: *const core::ffi::c_char,
6502 _domain_id: u32,
6503 qos: *const NrosRmwQos,
6504 _options: *const rmw_publisher_options_t,
6505 out: *mut NrosRmwPublisher,
6506 ) -> NrosRmwRet {
6507 // Capture the typed-struct fields the runtime supplied.
6508 unsafe {
6509 STUB_CREATE_PUB_CALLED = true;
6510 copy_cstr((*out).topic_name, &mut STUB_LAST_TOPIC_NAME);
6511 copy_cstr((*out).type_name, &mut STUB_LAST_TYPE_NAME);
6512 STUB_LAST_QOS = *qos;
6513 (*out).backend_data = 0xCAFEusize as *mut c_void;
6514 (*out).can_loan_messages = true;
6515 }
6516 NROS_RMW_RET_OK
6517 }
6518
6519 unsafe extern "C" fn stub_destroy_publisher(_publisher: *mut NrosRmwPublisher) -> NrosRmwRet {
6520 NROS_RMW_RET_OK
6521 }
6522
6523 unsafe extern "C" fn stub_publish_raw(
6524 publisher: *const NrosRmwPublisher,
6525 _payload: generated::rmw_byte_span_t,
6526 ) -> NrosRmwRet {
6527 // Verify the runtime is still passing the same backend_data
6528 // and topic_name on every call.
6529 unsafe {
6530 STUB_PUBLISH_CALLED = true;
6531 assert_eq!((*publisher).backend_data as usize, 0xCAFE);
6532 let mut buf = [0u8; 64];
6533 copy_cstr((*publisher).topic_name, &mut buf);
6534 assert_eq!(&buf[..], &STUB_LAST_TOPIC_NAME);
6535 }
6536 NROS_RMW_RET_OK
6537 }
6538
6539 unsafe extern "C" fn stub_create_subscription(
6540 _: *const NrosRmwNode,
6541 _: *const generated::rmw_message_type_support_t,
6542 _: *const core::ffi::c_char,
6543 _: u32,
6544 _: *const NrosRmwQos,
6545 _: *const rmw_subscription_options_t,
6546 out: *mut NrosRmwSubscription,
6547 ) -> NrosRmwRet {
6548 unsafe {
6549 (*out).backend_data = core::ptr::dangling_mut::<c_void>();
6550 }
6551 NROS_RMW_RET_OK
6552 }
6553 unsafe extern "C" fn stub_destroy_subscription(_: *mut NrosRmwSubscription) -> NrosRmwRet {
6554 NROS_RMW_RET_OK
6555 }
6556 unsafe extern "C" fn stub_take(
6557 _: *const NrosRmwSubscription,
6558 _out: *mut generated::rmw_mut_byte_span_t,
6559 taken: *mut bool,
6560 ) -> NrosRmwRet {
6561 // Phase 376 W3.d step A — the stub takes nothing, which is now stated
6562 // rather than encoded as a zero byte count.
6563 unsafe { *taken = false };
6564 NROS_RMW_RET_OK
6565 }
6566 unsafe extern "C" fn stub_has_data(
6567 _: *mut NrosRmwSubscription,
6568 out_has_data: *mut bool,
6569 ) -> NrosRmwRet {
6570 // Phase 376 W3.d step A — flag out, status returned.
6571 unsafe { *out_has_data = false };
6572 NROS_RMW_RET_OK
6573 }
6574
6575 unsafe extern "C" fn stub_create_service(
6576 _: *const NrosRmwNode,
6577 _: *const generated::rmw_service_type_support_t,
6578 _: *const core::ffi::c_char,
6579 _: u32,
6580 _: *const NrosRmwQos,
6581 out: *mut NrosRmwService,
6582 ) -> NrosRmwRet {
6583 unsafe {
6584 (*out).backend_data = core::ptr::dangling_mut::<c_void>();
6585 }
6586 NROS_RMW_RET_OK
6587 }
6588 unsafe extern "C" fn stub_destroy_service(_: *mut NrosRmwService) -> NrosRmwRet {
6589 NROS_RMW_RET_OK
6590 }
6591 unsafe extern "C" fn stub_take_request(
6592 _: *const NrosRmwService,
6593 _: *mut crate::generated::rmw_mut_byte_span_t,
6594 _: *mut i64,
6595 taken: *mut bool,
6596 ) -> NrosRmwRet {
6597 // Phase 376 W3.d step A — NO_DATA retires: nothing to take is
6598 // `taken = false` with OK.
6599 unsafe { *taken = false };
6600 NROS_RMW_RET_OK
6601 }
6602 unsafe extern "C" fn stub_has_request(
6603 _: *mut NrosRmwService,
6604 out_has_request: *mut bool,
6605 ) -> NrosRmwRet {
6606 // Phase 376 W3.d step A — flag out, status returned.
6607 unsafe { *out_has_request = false };
6608 NROS_RMW_RET_OK
6609 }
6610 unsafe extern "C" fn stub_send_response(
6611 _: *const NrosRmwService,
6612 _: i64,
6613 _: crate::generated::rmw_byte_span_t,
6614 ) -> NrosRmwRet {
6615 NROS_RMW_RET_OK
6616 }
6617
6618 unsafe extern "C" fn stub_create_client(
6619 _: *const NrosRmwNode,
6620 _: *const generated::rmw_service_type_support_t,
6621 _: *const core::ffi::c_char,
6622 _: u32,
6623 _: *const NrosRmwQos,
6624 out: *mut NrosRmwClient,
6625 ) -> NrosRmwRet {
6626 unsafe {
6627 (*out).backend_data = core::ptr::dangling_mut::<c_void>();
6628 }
6629 NROS_RMW_RET_OK
6630 }
6631 /// phase-521 W6 (RFC-0113 D5) — `CffiRmw` refuses a session stating no
6632 /// readiness form, so the stub states `Notify`.
6633 unsafe extern "C" fn stub_readiness_notify(
6634 _: *const generated::rmw_session_t,
6635 out_kind: *mut u8,
6636 out_handle: *mut i32,
6637 ) -> NrosRmwRet {
6638 unsafe {
6639 *out_kind = generated::NROS_RMW_READINESS_NOTIFY as u8;
6640 *out_handle = -1;
6641 }
6642 NROS_RMW_RET_OK
6643 }
6644 unsafe extern "C" fn stub_destroy_client(_: *mut NrosRmwClient) -> NrosRmwRet {
6645 NROS_RMW_RET_OK
6646 }
6647 unsafe extern "C" fn stub_register_subscription_event(
6648 _: *const NrosRmwSubscription,
6649 _: NrosRmwEventKind,
6650 _: u32,
6651 _: NrosRmwEventCallback,
6652 _: *mut c_void,
6653 ) -> NrosRmwRet {
6654 NROS_RMW_RET_UNSUPPORTED
6655 }
6656 unsafe extern "C" fn stub_register_publisher_event(
6657 _: *const NrosRmwPublisher,
6658 _: NrosRmwEventKind,
6659 _: u32,
6660 _: NrosRmwEventCallback,
6661 _: *mut c_void,
6662 ) -> NrosRmwRet {
6663 NROS_RMW_RET_UNSUPPORTED
6664 }
6665 unsafe extern "C" fn stub_assert_publisher_liveliness(
6666 _: *const NrosRmwPublisher,
6667 ) -> NrosRmwRet {
6668 NROS_RMW_RET_UNSUPPORTED
6669 }
6670
6671 static STUB_VTABLE: NrosRmwVtable = NrosRmwVtable {
6672 create_session: Some(stub_create_session),
6673 readiness_source: Some(stub_readiness_notify),
6674 destroy_session: Some(stub_destroy_session),
6675 drive_io: Some(stub_drive_io),
6676 create_publisher: Some(stub_create_publisher),
6677 destroy_publisher: Some(stub_destroy_publisher),
6678 publish: Some(stub_publish_raw),
6679 create_subscription: Some(stub_create_subscription),
6680 destroy_subscription: Some(stub_destroy_subscription),
6681 take: Some(stub_take),
6682 has_data: Some(stub_has_data),
6683 create_service: Some(stub_create_service),
6684 destroy_service: Some(stub_destroy_service),
6685 take_request: Some(stub_take_request),
6686 has_request: Some(stub_has_request),
6687 send_response: Some(stub_send_response),
6688 create_client: Some(stub_create_client),
6689 destroy_client: Some(stub_destroy_client),
6690 subscription_event_init: Some(stub_register_subscription_event),
6691 publisher_event_init: Some(stub_register_publisher_event),
6692 publisher_assert_liveliness: Some(stub_assert_publisher_liveliness),
6693 ..EMPTY_VTABLE
6694 };
6695
6696 // Phase-301 (issue 0241) — boundary semantics of the QoS lowering.
6697
6698 #[test]
6699 fn qos_depth_at_u16_max_lowers() {
6700 let qos = nros_rmw::QoSProfile::default().keep_last(u16::MAX as u32);
6701 let lowered = NrosRmwQos::try_from(qos).expect("depth 65535 must lower");
6702 assert_eq!(lowered.depth, u16::MAX);
6703 }
6704
6705 #[test]
6706 fn qos_depth_past_u16_max_is_create_time_error() {
6707 let qos = nros_rmw::QoSProfile::default().keep_last(u16::MAX as u32 + 1);
6708 assert_eq!(
6709 NrosRmwQos::try_from(qos),
6710 Err(TransportError::InvalidArgument)
6711 );
6712 }
6713
6714 /// issue 0829 — the POLICY sentinel lowers rather than resolving, and the
6715 /// hand-mirrored C constant agrees with what the Rust profile lowers to.
6716 ///
6717 /// Two things at once, both hand-mirror class (issues 0088/0160/0245):
6718 /// `NROS_RMW_QOS_PROFILE_SYSTEM_DEFAULT` here is a second copy of the macro
6719 /// in `nros/rmw_entity.h`, and the lowering is a third statement of the same
6720 /// mapping. All three must say "every field is zero", because a C backend
6721 /// resolving the sentinel can only do so if it actually receives one.
6722 #[test]
6723 fn system_default_lowers_to_all_sentinel_and_matches_the_c_mirror() {
6724 let lowered = NrosRmwQos::try_from(nros_rmw::QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT)
6725 .expect("the sentinel profile must lower");
6726
6727 assert_eq!(
6728 lowered.reliability as i32,
6729 generated::NROS_RMW_RELIABILITY_SYSTEM_DEFAULT
6730 );
6731 assert_eq!(
6732 lowered.durability as i32,
6733 generated::NROS_RMW_DURABILITY_SYSTEM_DEFAULT
6734 );
6735 assert_eq!(
6736 lowered.history as i32,
6737 generated::NROS_RMW_HISTORY_SYSTEM_DEFAULT
6738 );
6739 assert_eq!(lowered.depth, 0, "depth sentinel must lower as 0");
6740 assert_eq!(
6741 lowered.liveliness_kind as u32,
6742 generated::rmw_liveliness_kind_t::NROS_RMW_LIVELINESS_SYSTEM_DEFAULT
6743 );
6744
6745 // The hand-mirrored C constant says the same thing.
6746 assert_eq!(
6747 lowered, NROS_RMW_QOS_PROFILE_SYSTEM_DEFAULT,
6748 "the C mirror drifted from what the Rust profile lowers to"
6749 );
6750 // And it is NOT `_DEFAULT` — the aliasing was half the 0829 defect.
6751 assert_ne!(
6752 NROS_RMW_QOS_PROFILE_SYSTEM_DEFAULT, NROS_RMW_QOS_PROFILE_DEFAULT,
6753 "SYSTEM_DEFAULT aliased DEFAULT again — see issue 0829"
6754 );
6755 }
6756
6757 #[test]
6758 fn qos_infinite_sentinel_passes_through_and_reads_as_unset() {
6759 use nros_rmw::{DURATION_INFINITE_MS, QoSPolicyMask};
6760 let qos = nros_rmw::QoSProfile {
6761 deadline_ms: DURATION_INFINITE_MS,
6762 lifespan_ms: DURATION_INFINITE_MS,
6763 liveliness_lease_ms: DURATION_INFINITE_MS,
6764 ..Default::default()
6765 };
6766 // Sentinel behaves like 0 at the check sites: no extra policy demanded.
6767 let required = qos.required_policies();
6768 assert!(!required.contains(QoSPolicyMask::DEADLINE));
6769 assert!(!required.contains(QoSPolicyMask::LIFESPAN));
6770 assert!(!required.contains(QoSPolicyMask::LIVELINESS_LEASE));
6771 // And lowers unchanged — the C side sees the explicit spelling.
6772 let lowered = NrosRmwQos::try_from(qos).expect("sentinel must lower");
6773 assert_eq!(lowered.deadline_ms, DURATION_INFINITE_MS);
6774 assert_eq!(lowered.lifespan_ms, DURATION_INFINITE_MS);
6775 assert_eq!(lowered.liveliness_lease_ms, DURATION_INFINITE_MS);
6776 }
6777
6778 #[test]
6779 fn duration_lowering_boundaries() {
6780 use core::time::Duration;
6781 use nros_rmw::{DURATION_INFINITE_MS, duration_to_qos_ms};
6782 // 0 keeps its unset/no-check meaning.
6783 assert_eq!(duration_to_qos_ms(Duration::ZERO), Ok(0));
6784 // Sub-ms CEILs to 1 ms — never floors to "no deadline".
6785 assert_eq!(duration_to_qos_ms(Duration::from_nanos(1)), Ok(1));
6786 assert_eq!(duration_to_qos_ms(Duration::from_micros(999)), Ok(1));
6787 assert_eq!(duration_to_qos_ms(Duration::from_millis(1)), Ok(1));
6788 assert_eq!(duration_to_qos_ms(Duration::from_micros(1001)), Ok(2));
6789 // Largest representable finite value — one below the best-available
6790 // sentinel (issue 1973), which no finite duration may lower onto.
6791 assert_eq!(
6792 duration_to_qos_ms(Duration::from_millis(DURATION_INFINITE_MS as u64 - 2)),
6793 Ok(DURATION_INFINITE_MS - 2)
6794 );
6795 assert_eq!(
6796 duration_to_qos_ms(Duration::from_millis(DURATION_INFINITE_MS as u64 - 1)),
6797 Err(TransportError::InvalidArgument)
6798 );
6799 // At / past the sentinel: create-time error, never a clamp (infinite
6800 // is spelled via the sentinel or 0, not a huge finite duration).
6801 assert_eq!(
6802 duration_to_qos_ms(Duration::from_millis(DURATION_INFINITE_MS as u64)),
6803 Err(TransportError::InvalidArgument)
6804 );
6805 assert_eq!(
6806 duration_to_qos_ms(Duration::from_secs(u64::MAX / 1_000)),
6807 Err(TransportError::InvalidArgument)
6808 );
6809 }
6810
6811 /// Issue 1942 — the service half of the side channel round-trips each
6812 /// field's PRESENCE, not just its value: a field the backend left `None`
6813 /// reads back `None`, never as the zero it is packed over.
6814 #[cfg(feature = "alloc")]
6815 #[test]
6816 fn service_info_side_channel_keeps_absent_fields_absent() {
6817 let key = 0x1942_usize;
6818 let only_id = ServiceRequestInfo {
6819 request_id: Some(RequestId {
6820 writer_guid: [9; REQUEST_WRITER_GUID_SIZE],
6821 sequence_number: -3,
6822 }),
6823 ..ServiceRequestInfo::NOT_REPORTED
6824 };
6825 store_cffi_service_info(key, only_id);
6826 assert_eq!(take_cffi_service_info(key), only_id);
6827 // Consumed: a second read without a store reports nothing.
6828 assert_eq!(
6829 take_cffi_service_info(key),
6830 ServiceRequestInfo::NOT_REPORTED
6831 );
6832 clear_cffi_message_info(key);
6833 }
6834
6835 /// Issue 1942 — the presence byte lives in padding the slot already had,
6836 /// so the table (issue 0271's footprint concern) does not grow.
6837 #[cfg(not(all(feature = "alloc", feature = "safety-e2e")))]
6838 #[test]
6839 fn service_presence_does_not_widen_the_message_info_slot() {
6840 assert_eq!(
6841 core::mem::size_of::<MessageInfoSlot>(),
6842 core::mem::size_of::<MessageInfo>() + 2 * core::mem::size_of::<usize>()
6843 );
6844 }
6845
6846 #[test]
6847 fn service_server_no_data_maps_to_none() {
6848 use nros_rmw::ServiceTrait as _;
6849
6850 let mut server = CffiService {
6851 vtable: &STUB_VTABLE,
6852 service_name_buf: [0u8; NAME_BUF_LEN],
6853 type_name_buf: [0u8; NAME_BUF_LEN],
6854 backend_data: core::ptr::dangling_mut::<c_void>(),
6855 request_qos: qos_unknown_c(),
6856 response_qos: qos_unknown_c(),
6857 refused_len: None,
6858 entity_waker: WakerSlot::new(),
6859 request_info: ServiceRequestInfo::NOT_REPORTED,
6860 };
6861 let mut buf = [0u8; 16];
6862
6863 assert!(server.take_request(&mut buf).unwrap().is_none());
6864 }
6865
6866 // Issue 2081 — a C backend that fills `take_request_with_info` is HEARD.
6867
6868 const INFO_GUID: [i8; 16] = [1, -2, 3, -4, 5, -6, 7, -8, 9, 10, 11, 12, 13, 14, 15, 16];
6869
6870 unsafe extern "C" fn info_take_request(
6871 _: *const NrosRmwService,
6872 _: *mut crate::generated::rmw_mut_byte_span_t,
6873 _: *mut i64,
6874 _: *mut bool,
6875 ) -> NrosRmwRet {
6876 // Never reached: a backend with the info slot is taken through it.
6877 NROS_RMW_RET_ERROR
6878 }
6879
6880 unsafe extern "C" fn info_take_request_with_info(
6881 _: *const NrosRmwService,
6882 request: *mut crate::generated::rmw_mut_byte_span_t,
6883 seq_out: *mut i64,
6884 taken: *mut bool,
6885 info: *mut crate::generated::rmw_service_info_t,
6886 ) -> NrosRmwRet {
6887 unsafe {
6888 (*request).len = 4;
6889 *(*request).data = 0x00;
6890 *(*request).data.add(1) = 0x01;
6891 *seq_out = 7; // the backend's reply token, not the client's sequence
6892 *taken = true;
6893 (*info).source_timestamp = 1_700_000_000_000_000_001;
6894 (*info).received_timestamp = 0; // not stamped
6895 (*info).request_id.writer_guid = INFO_GUID;
6896 (*info).request_id.sequence_number = 42;
6897 }
6898 NROS_RMW_RET_OK
6899 }
6900
6901 unsafe extern "C" fn zero_take_request_with_info(
6902 _: *const NrosRmwService,
6903 request: *mut crate::generated::rmw_mut_byte_span_t,
6904 seq_out: *mut i64,
6905 taken: *mut bool,
6906 _: *mut crate::generated::rmw_service_info_t,
6907 ) -> NrosRmwRet {
6908 unsafe {
6909 (*request).len = 4;
6910 *seq_out = 1;
6911 *taken = true;
6912 }
6913 NROS_RMW_RET_OK
6914 }
6915
6916 static INFO_VTABLE: NrosRmwVtable = NrosRmwVtable {
6917 take_request: Some(info_take_request),
6918 take_request_with_info: Some(info_take_request_with_info),
6919 ..STUB_VTABLE
6920 };
6921 static ZERO_INFO_VTABLE: NrosRmwVtable = NrosRmwVtable {
6922 take_request_with_info: Some(zero_take_request_with_info),
6923 ..STUB_VTABLE
6924 };
6925
6926 fn info_server(vtable: &'static NrosRmwVtable) -> CffiService {
6927 CffiService {
6928 vtable,
6929 service_name_buf: [0u8; NAME_BUF_LEN],
6930 type_name_buf: [0u8; NAME_BUF_LEN],
6931 backend_data: 0x2081_0001usize as *mut c_void,
6932 request_qos: qos_unknown_c(),
6933 response_qos: qos_unknown_c(),
6934 refused_len: None,
6935 entity_waker: WakerSlot::new(),
6936 request_info: ServiceRequestInfo::NOT_REPORTED,
6937 }
6938 }
6939
6940 /// Issue 2081 — the slot is dispatched in place of `take_request`, its
6941 /// struct becomes `request_info()`, and the reply token stays the
6942 /// backend's (`seq_out`), separate from the client's sequence number.
6943 #[test]
6944 fn take_request_with_info_reports_the_requests_identity() {
6945 use nros_rmw::ServiceTrait as _;
6946 let mut server = info_server(&INFO_VTABLE);
6947 let mut buf = [0u8; 16];
6948 let req = server
6949 .take_request(&mut buf)
6950 .expect("the slot answers OK")
6951 .expect("a request was taken");
6952 assert_eq!(req.sequence_number, 7, "the reply token is the backend's");
6953 let info = server.request_info();
6954 let id = info.request_id.expect("a non-zero GUID is a reported id");
6955 let mut want = [0u8; REQUEST_WRITER_GUID_SIZE];
6956 for (d, s) in want.iter_mut().zip(INFO_GUID.iter()) {
6957 *d = *s as u8;
6958 }
6959 assert_eq!(id.writer_guid, want);
6960 assert_eq!(id.sequence_number, 42, "the CLIENT's sequence number");
6961 assert_eq!(
6962 info.source_timestamp,
6963 Some(nros_rmw::Time::from_nanos(1_700_000_000_000_000_001))
6964 );
6965 assert_eq!(
6966 info.received_timestamp, None,
6967 "0 is not stamped, never Some(0)"
6968 );
6969 }
6970
6971 /// Issue 2081 — an all-zero struct is "nothing reported", not a zero id.
6972 #[test]
6973 fn take_request_with_info_zero_struct_is_not_reported() {
6974 use nros_rmw::ServiceTrait as _;
6975 let mut server = info_server(&ZERO_INFO_VTABLE);
6976 let mut buf = [0u8; 16];
6977 assert!(server.take_request(&mut buf).unwrap().is_some());
6978 assert_eq!(server.request_info(), ServiceRequestInfo::NOT_REPORTED);
6979 }
6980
6981 // Issue 2136 — a C backend that fills `take_response_with_info` is HEARD
6982 // on the client side too.
6983
6984 unsafe extern "C" fn info_take_response(
6985 _: *const NrosRmwClient,
6986 _: *mut crate::generated::rmw_mut_byte_span_t,
6987 _: *mut i64,
6988 _: *mut bool,
6989 ) -> NrosRmwRet {
6990 // Never reached: a backend with the info slot is taken through it.
6991 NROS_RMW_RET_ERROR
6992 }
6993
6994 unsafe extern "C" fn info_take_response_with_info(
6995 _: *const NrosRmwClient,
6996 reply: *mut crate::generated::rmw_mut_byte_span_t,
6997 seq_out: *mut i64,
6998 taken: *mut bool,
6999 info: *mut crate::generated::rmw_service_info_t,
7000 ) -> NrosRmwRet {
7001 unsafe {
7002 (*reply).len = 4;
7003 *seq_out = 42; // the correlation id, as `take_response` reports it
7004 *taken = true;
7005 (*info).source_timestamp = 1_700_000_000_000_000_002; // server's send
7006 (*info).received_timestamp = 1_700_000_000_000_000_003; // our arrival
7007 (*info).request_id.writer_guid = INFO_GUID;
7008 (*info).request_id.sequence_number = 42;
7009 }
7010 NROS_RMW_RET_OK
7011 }
7012
7013 unsafe extern "C" fn zero_take_response_with_info(
7014 _: *const NrosRmwClient,
7015 reply: *mut crate::generated::rmw_mut_byte_span_t,
7016 seq_out: *mut i64,
7017 taken: *mut bool,
7018 info: *mut crate::generated::rmw_service_info_t,
7019 ) -> NrosRmwRet {
7020 unsafe {
7021 (*reply).len = 4;
7022 *seq_out = 1;
7023 *taken = true;
7024 // A sequence number with no GUID is not a reported request id.
7025 (*info).request_id.sequence_number = 1;
7026 }
7027 NROS_RMW_RET_OK
7028 }
7029
7030 unsafe extern "C" fn plain_take_response(
7031 _: *const NrosRmwClient,
7032 reply: *mut crate::generated::rmw_mut_byte_span_t,
7033 seq_out: *mut i64,
7034 taken: *mut bool,
7035 ) -> NrosRmwRet {
7036 unsafe {
7037 (*reply).len = 4;
7038 *seq_out = 5;
7039 *taken = true;
7040 }
7041 NROS_RMW_RET_OK
7042 }
7043
7044 static RESPONSE_INFO_VTABLE: NrosRmwVtable = NrosRmwVtable {
7045 take_response: Some(info_take_response),
7046 take_response_with_info: Some(info_take_response_with_info),
7047 ..STUB_VTABLE
7048 };
7049 static ZERO_RESPONSE_INFO_VTABLE: NrosRmwVtable = NrosRmwVtable {
7050 take_response: Some(info_take_response),
7051 take_response_with_info: Some(zero_take_response_with_info),
7052 ..STUB_VTABLE
7053 };
7054 static PLAIN_RESPONSE_VTABLE: NrosRmwVtable = NrosRmwVtable {
7055 take_response: Some(plain_take_response),
7056 take_response_with_info: None,
7057 ..STUB_VTABLE
7058 };
7059
7060 fn info_client(vtable: &'static NrosRmwVtable) -> CffiClient {
7061 CffiClient {
7062 vtable,
7063 service_name_buf: [0u8; NAME_BUF_LEN],
7064 type_name_buf: [0u8; NAME_BUF_LEN],
7065 backend_data: 0x2136_0001usize as *mut c_void,
7066 request_qos: qos_unknown_c(),
7067 response_qos: qos_unknown_c(),
7068 refused_len: None,
7069 entity_waker: WakerSlot::new(),
7070 response_info: ServiceRequestInfo::NOT_REPORTED,
7071 }
7072 }
7073
7074 /// Issue 2136 — the slot is dispatched in place of `take_response`, and
7075 /// its struct becomes `response_info()`.
7076 #[test]
7077 fn take_response_with_info_reports_the_replys_metadata() {
7078 let mut client = info_client(&RESPONSE_INFO_VTABLE);
7079 let mut buf = [0u8; 16];
7080 let (len, seq) = client
7081 .take_response_raw(&mut buf)
7082 .expect("the slot answers OK")
7083 .expect("a reply was taken");
7084 assert_eq!((len, seq), (4, 42));
7085 let info = client.response_info();
7086 let id = info.request_id.expect("a non-zero GUID is a reported id");
7087 let mut want = [0u8; REQUEST_WRITER_GUID_SIZE];
7088 for (d, s) in want.iter_mut().zip(INFO_GUID.iter()) {
7089 *d = *s as u8;
7090 }
7091 assert_eq!(id.writer_guid, want);
7092 assert_eq!(id.sequence_number, 42);
7093 assert_eq!(
7094 info.source_timestamp,
7095 Some(nros_rmw::Time::from_nanos(1_700_000_000_000_000_002))
7096 );
7097 assert_eq!(
7098 info.received_timestamp,
7099 Some(nros_rmw::Time::from_nanos(1_700_000_000_000_000_003))
7100 );
7101 }
7102
7103 /// Issue 2136 — an all-zero struct (a bare sequence number included) is
7104 /// "nothing reported".
7105 #[test]
7106 fn take_response_with_info_zero_struct_is_not_reported() {
7107 let mut client = info_client(&ZERO_RESPONSE_INFO_VTABLE);
7108 let mut buf = [0u8; 16];
7109 assert!(client.take_response_raw(&mut buf).unwrap().is_some());
7110 assert_eq!(client.response_info(), ServiceRequestInfo::NOT_REPORTED);
7111 }
7112
7113 /// Issue 2136 — a backend without the slot reports nothing, and a reply
7114 /// taken after an informed one does not inherit its metadata.
7115 #[test]
7116 fn take_response_without_the_slot_reports_nothing() {
7117 let mut client = info_client(&PLAIN_RESPONSE_VTABLE);
7118 client.response_info = ServiceRequestInfo {
7119 source_timestamp: Some(nros_rmw::Time::from_nanos(9)),
7120 ..ServiceRequestInfo::NOT_REPORTED
7121 };
7122 let mut buf = [0u8; 16];
7123 assert_eq!(client.take_response_raw(&mut buf).unwrap(), Some((4, 5)));
7124 assert_eq!(client.response_info(), ServiceRequestInfo::NOT_REPORTED);
7125 }
7126
7127 #[test]
7128 fn typed_struct_roundtrip() {
7129 // Register the stub vtable under its canonical name.
7130 let ret = unsafe { nros_rmw_cffi_register_named(c"default".as_ptr(), &STUB_VTABLE) };
7131 assert_eq!(ret, NROS_RMW_RET_OK);
7132
7133 // Open a session.
7134 let cfg = RmwConfig {
7135 mode: SessionMode::Client,
7136 locator: "tcp/127.0.0.1:7447",
7137 domain_id: 0,
7138 node_name: "test_node",
7139 namespace: "",
7140 properties: &[],
7141 };
7142 let mut session = Rmw::open(CffiRmw, &cfg).expect("session open");
7143 assert!(unsafe { STUB_OPEN_CALLED });
7144 assert_eq!(session.node_name(), "test_node");
7145
7146 // Create a publisher; verify backend received the typed
7147 // struct with topic_name + qos populated.
7148 let topic = TopicInfo::new("/chatter", "std_msgs/msg/Int32", "RIHS01_abc");
7149 let qos = nros_rmw::QoSProfile::default();
7150 let publisher = session
7151 .create_publisher(&topic, qos)
7152 .expect("publisher create");
7153 assert!(unsafe { STUB_CREATE_PUB_CALLED });
7154 let topic_buf = unsafe { &STUB_LAST_TOPIC_NAME };
7155 assert_eq!(
7156 core::str::from_utf8(topic_buf)
7157 .unwrap_or("")
7158 .trim_end_matches('\0'),
7159 "/chatter"
7160 );
7161 let type_buf = unsafe { &STUB_LAST_TYPE_NAME };
7162 assert_eq!(
7163 core::str::from_utf8(type_buf)
7164 .unwrap_or("")
7165 .trim_end_matches('\0'),
7166 "std_msgs/msg/Int32"
7167 );
7168
7169 // Rust accessors read back the typed-struct fields.
7170 assert_eq!(publisher.topic_name(), "/chatter");
7171 assert_eq!(publisher.type_name(), "std_msgs/msg/Int32");
7172 // issue 0814 — `can_loan_messages` is DERIVED, so a backend cannot
7173 // over-claim it. `stub_create_publisher` writes `true` into the view
7174 // while `STUB_VTABLE` inherits `borrow_loaned_message: None` from
7175 // `EMPTY_VTABLE`; a backend that cannot be asked for a loan does not
7176 // advertise loans, whatever it wrote. This assertion read `true`
7177 // before the fix — it was the over-claim, believed.
7178 assert!(
7179 !publisher.can_loan_messages(),
7180 "the stub declared can_loan_messages=true with a NULL \
7181 borrow_loaned_message slot; the declaration must not win"
7182 );
7183
7184 // Publish — verify backend_data round-trips correctly via
7185 // the typed view.
7186 use nros_rmw::Publisher as _;
7187 publisher.publish_raw(&[1u8, 2, 3]).expect("publish");
7188 assert!(unsafe { STUB_PUBLISH_CALLED });
7189 }
7190
7191 // Issue 0332 — an incomplete vtable must be rejected at registration, not
7192 // panic mid-spin. (The stub tests above register a COMPLETE vtable, so they
7193 // are the "complete → accepted" guard: if the required-slot list ever
7194 // over-rejected, those tests would fail at registration.)
7195 #[test]
7196 fn register_rejects_incomplete_vtable() {
7197 // SAFETY: `NrosRmwVtable` is a plain struct of `Option<extern fn>` +
7198 // POD fields; an all-zero bit pattern is every slot `None` (null-ptr
7199 // niche) — a valid, empty vtable.
7200 let empty: NrosRmwVtable = unsafe { core::mem::zeroed() };
7201 assert_eq!(first_missing_vtable_slot(&empty), Some("create_session"));
7202
7203 let rc = unsafe { nros_rmw_cffi_register_named(c"incomplete_0332".as_ptr(), &empty) };
7204 assert_eq!(rc, NROS_RMW_RET_INVALID_ARGUMENT);
7205 }
7206
7207 // Issue 0349 — the other direction. The 0332 list used to include three
7208 // OPTIONAL capability slots, which refused the xrce backend outright (its
7209 // vtable NULLs all three deliberately). A backend that can publish,
7210 // subscribe, serve and call is a working backend.
7211 //
7212 // This test is the pair to `register_rejects_incomplete_vtable` above: one
7213 // asserts the gate still bites, this asserts it does not over-bite. Keep
7214 // ---- issue 1973: BEST_AVAILABLE resolves HERE, for every C backend ----
7215 //
7216 // The captured QoS is what the backend's create slot received. Each slot
7217 // writes its own static, and each test owns its statics, so the parallel
7218 // test runner cannot interleave them.
7219
7220 static mut BA_SUB_QOS: Option<NrosRmwQos> = None;
7221 static mut BA_PUB_QOS: Option<NrosRmwQos> = None;
7222 static mut BA_NULL_SUB_QOS: Option<NrosRmwQos> = None;
7223
7224 unsafe extern "C" fn ba_create_subscription(
7225 _: *const NrosRmwNode,
7226 _: *const generated::rmw_message_type_support_t,
7227 _: *const core::ffi::c_char,
7228 _: u32,
7229 qos: *const NrosRmwQos,
7230 _: *const rmw_subscription_options_t,
7231 out: *mut NrosRmwSubscription,
7232 ) -> NrosRmwRet {
7233 unsafe {
7234 BA_SUB_QOS = Some(*qos);
7235 (*out).backend_data = core::ptr::dangling_mut::<c_void>();
7236 }
7237 NROS_RMW_RET_OK
7238 }
7239
7240 unsafe extern "C" fn ba_null_create_subscription(
7241 _: *const NrosRmwNode,
7242 _: *const generated::rmw_message_type_support_t,
7243 _: *const core::ffi::c_char,
7244 _: u32,
7245 qos: *const NrosRmwQos,
7246 _: *const rmw_subscription_options_t,
7247 out: *mut NrosRmwSubscription,
7248 ) -> NrosRmwRet {
7249 unsafe {
7250 BA_NULL_SUB_QOS = Some(*qos);
7251 (*out).backend_data = core::ptr::dangling_mut::<c_void>();
7252 }
7253 NROS_RMW_RET_OK
7254 }
7255
7256 unsafe extern "C" fn ba_create_publisher(
7257 _: *const NrosRmwNode,
7258 _: *const generated::rmw_message_type_support_t,
7259 _: *const core::ffi::c_char,
7260 _: u32,
7261 qos: *const NrosRmwQos,
7262 _: *const rmw_publisher_options_t,
7263 out: *mut NrosRmwPublisher,
7264 ) -> NrosRmwRet {
7265 unsafe {
7266 BA_PUB_QOS = Some(*qos);
7267 (*out).backend_data = 0xBEEFusize as *mut c_void;
7268 }
7269 NROS_RMW_RET_OK
7270 }
7271
7272 /// One discovered endpoint for the stub graph slots.
7273 fn ba_endpoint(publisher: bool, qos: QoSProfile) -> generated::rmw_topic_endpoint_info_t {
7274 generated::rmw_topic_endpoint_info_t {
7275 node_name: c"peer".as_ptr(),
7276 node_namespace: c"/".as_ptr(),
7277 topic_type: c"std_msgs/msg/Int32".as_ptr(),
7278 endpoint_type: if publisher {
7279 generated::rmw_endpoint_type_t::RMW_ENDPOINT_PUBLISHER
7280 } else {
7281 generated::rmw_endpoint_type_t::RMW_ENDPOINT_SUBSCRIPTION
7282 },
7283 endpoint_gid: generated::rmw_gid_t {
7284 implementation_identifier: core::ptr::null(),
7285 data: [0u8; 24],
7286 },
7287 qos_profile: NrosRmwQos::try_from(qos).unwrap(),
7288 }
7289 }
7290
7291 /// Two publishers on the topic: both RELIABLE, only one TRANSIENT_LOCAL,
7292 /// deadlines 50 ms and 200 ms.
7293 unsafe extern "C" fn ba_publishers(
7294 _: *const NrosRmwSession,
7295 _: *const core::ffi::c_char,
7296 _: bool,
7297 visitor: generated::rmw_topic_endpoint_info_visitor_t,
7298 ) -> NrosRmwRet {
7299 let visit = visitor.visit.unwrap();
7300 let mut a = QoSProfile::QOS_PROFILE_DEFAULT.transient_local();
7301 a.deadline_ms = 50;
7302 let mut b = QoSProfile::QOS_PROFILE_DEFAULT;
7303 b.deadline_ms = 200;
7304 for q in [a, b] {
7305 let info = ba_endpoint(true, q);
7306 unsafe { visit(visitor.ctx, &info) };
7307 }
7308 NROS_RMW_RET_OK
7309 }
7310
7311 /// One subscription on the topic: MANUAL_BY_TOPIC with a 100 ms deadline.
7312 unsafe extern "C" fn ba_subscriptions(
7313 _: *const NrosRmwSession,
7314 _: *const core::ffi::c_char,
7315 _: bool,
7316 visitor: generated::rmw_topic_endpoint_info_visitor_t,
7317 ) -> NrosRmwRet {
7318 let visit = visitor.visit.unwrap();
7319 let mut q = QoSProfile::QOS_PROFILE_DEFAULT;
7320 q.liveliness_kind = QoSLivelinessPolicy::ManualByTopic;
7321 q.deadline_ms = 100;
7322 let info = ba_endpoint(false, q);
7323 unsafe { visit(visitor.ctx, &info) };
7324 NROS_RMW_RET_OK
7325 }
7326
7327 fn ba_session(vtable: &'static NrosRmwVtable, mask: nros_rmw::QoSPolicyMask) -> CffiSession {
7328 CffiSession {
7329 vtable,
7330 node_name_buf: [0u8; NAME_BUF_LEN],
7331 namespace_buf: [0u8; NAME_BUF_LEN],
7332 backend_data: core::ptr::dangling_mut::<c_void>(),
7333 domain_id: 0,
7334 qos_policies: mask,
7335 }
7336 }
7337
7338 /// issue 1973 — the backend's create slot receives the RESOLVED policy,
7339 /// folded from what its own graph slot reported: a subscription takes
7340 /// RELIABLE because every publisher offers it, VOLATILE because one does
7341 /// not offer TRANSIENT_LOCAL, and the LARGEST peer deadline; a publisher
7342 /// takes RELIABLE / TRANSIENT_LOCAL unconditionally, MANUAL_BY_TOPIC
7343 /// because a subscription asks for it, and the SMALLEST peer deadline.
7344 #[test]
7345 fn best_available_reaches_the_backend_resolved_against_its_graph() {
7346 static VT: NrosRmwVtable = NrosRmwVtable {
7347 create_subscription: Some(ba_create_subscription),
7348 create_publisher: Some(ba_create_publisher),
7349 get_publishers_info_by_topic: Some(ba_publishers),
7350 get_subscriptions_info_by_topic: Some(ba_subscriptions),
7351 ..STUB_VTABLE
7352 };
7353 let mut session = ba_session(&VT, nros_rmw::QoSPolicyMask(u32::MAX));
7354 let topic = TopicInfo::new("/chatter", "std_msgs/msg/Int32", "");
7355
7356 let _sub = session
7357 .create_subscription(&topic, QoSProfile::best_available())
7358 .expect("subscription");
7359 let got = qos_from_c(&unsafe { BA_SUB_QOS }.expect("create slot ran"));
7360 assert_eq!(got.reliability, QoSReliabilityPolicy::Reliable);
7361 assert_eq!(got.durability, QoSDurabilityPolicy::Volatile);
7362 assert_eq!(got.liveliness_kind, QoSLivelinessPolicy::Automatic);
7363 assert_eq!(got.deadline_ms, 200);
7364 assert_eq!(got.liveliness_lease_ms, 0);
7365 assert_eq!(got.depth, 10, "depth is stated, never resolved");
7366
7367 let _pub = session
7368 .create_publisher(&topic, QoSProfile::best_available())
7369 .expect("publisher");
7370 let got = qos_from_c(&unsafe { BA_PUB_QOS }.expect("create slot ran"));
7371 assert_eq!(got.reliability, QoSReliabilityPolicy::Reliable);
7372 assert_eq!(got.durability, QoSDurabilityPolicy::TransientLocal);
7373 assert_eq!(got.liveliness_kind, QoSLivelinessPolicy::ManualByTopic);
7374 assert_eq!(got.deadline_ms, 100);
7375 }
7376
7377 /// issue 1973 — a backend with NO graph slot (XRCE, uORB) has discovered
7378 /// nothing, and a subscription resolves to upstream's nothing-discovered
7379 /// answer — BEST_EFFORT / VOLATILE / AUTOMATIC — rather than being handed
7380 /// the request value. A policy the backend does not honour at all clamps
7381 /// to the SYSTEM_DEFAULT sentinel the backend then resolves itself.
7382 #[test]
7383 fn best_available_without_a_graph_slot_resolves_to_nothing_discovered() {
7384 static VT: NrosRmwVtable = NrosRmwVtable {
7385 create_subscription: Some(ba_null_create_subscription),
7386 ..STUB_VTABLE
7387 };
7388 let honoured =
7389 nros_rmw::QoSPolicyMask::RELIABILITY | nros_rmw::QoSPolicyMask::DURABILITY_VOLATILE;
7390 let mut session = ba_session(&VT, honoured);
7391 let topic = TopicInfo::new("/chatter", "std_msgs/msg/Int32", "");
7392 let _sub = session
7393 .create_subscription(&topic, QoSProfile::best_available())
7394 .expect("subscription");
7395 let got = qos_from_c(&unsafe { BA_NULL_SUB_QOS }.expect("create slot ran"));
7396 assert_eq!(got.reliability, QoSReliabilityPolicy::BestEffort);
7397 assert_eq!(got.durability, QoSDurabilityPolicy::Volatile);
7398 // No liveliness bit honoured: AUTOMATIC steps down to the sentinel.
7399 assert_eq!(got.liveliness_kind, QoSLivelinessPolicy::None);
7400 assert_eq!(got.deadline_ms, 0);
7401 assert_eq!(got.liveliness_lease_ms, 0);
7402 }
7403
7404 // both — dropping either turns the gate into a one-way ratchet.
7405 /// phase-381 W6 — a NULL graph slot must say UNSUPPORTED, not "empty".
7406 ///
7407 /// The distinction is the whole of W6. A C vtable is a designated
7408 /// initializer, so every graph slot a backend does not fill is NULL by
7409 /// omission (XRCE fills only `get_node_names` and the change edge, issue
7410 /// 2106). If a NULL slot produced `Ok(())` with no visits, a caller
7411 /// could not tell "this backend cannot answer" from "the graph is empty",
7412 /// and would conclude a peer is absent when it simply cannot be seen.
7413 ///
7414 /// This also guards the reverse defect, which nearly shipped: `CffiSession`
7415 /// had NO `get_node_names` at all, so it fell through to the trait default
7416 /// and returned `Unsupported` even for a backend whose slot WAS wired —
7417 /// cyclone's, once W5 filled it. The slot would have looked implemented
7418 /// while being dead code, which is issue 0800's overstatement one layer up.
7419 #[test]
7420 fn a_null_graph_slot_reports_unsupported_not_an_empty_graph() {
7421 use nros_rmw::{Session, TransportError};
7422
7423 // A vtable with every required slot and NO graph slots — the shape a C
7424 // backend gets from `.field = ...` designated init.
7425 let mut session = CffiSession {
7426 vtable: &STUB_VTABLE,
7427 node_name_buf: [0u8; NAME_BUF_LEN],
7428 namespace_buf: [0u8; NAME_BUF_LEN],
7429 backend_data: core::ptr::dangling_mut::<c_void>(),
7430 domain_id: 0,
7431 // Not exercised here: the QoS mask decides ADMISSION, which the
7432 // runtime layer does, and these tests script the vtable directly.
7433 qos_policies: nros_rmw::QoSPolicyMask::NONE,
7434 };
7435 let mut seen = 0usize;
7436 let mut visit = |_n: &str, _ns: &str, _e: Option<&str>| {
7437 seen += 1;
7438 true
7439 };
7440 let r = Session::get_node_names(&mut session, &mut visit);
7441 assert!(
7442 matches!(r, Err(TransportError::Unsupported)),
7443 "a NULL slot must report Unsupported, got {r:?}"
7444 );
7445 assert_eq!(seen, 0, "nothing may be visited when the slot is absent");
7446 }
7447
7448 #[test]
7449 fn register_accepts_vtable_without_optional_capability_slots() {
7450 let mut vt = STUB_VTABLE;
7451 vt.publisher_event_init = None;
7452 vt.subscription_event_init = None;
7453 vt.publisher_assert_liveliness = None;
7454
7455 assert_eq!(
7456 first_missing_vtable_slot(&vt),
7457 None,
7458 "QoS-event and liveliness slots are capabilities, not core transport"
7459 );
7460
7461 // Deliberately NOT calling `nros_rmw_cffi_register_named` here. The
7462 // registry is a process global with no removal, so a successful
7463 // registration leaks a second backend into every other test in this
7464 // binary and turns single-backend resolution into `Ambiguous`
7465 // (`typed_struct_roundtrip` goes red). `first_missing_vtable_slot` is
7466 // the pure function that decides acceptance, so asserting on it tests
7467 // the same decision without the shared state. The end-to-end
7468 // "this really does register now" proof is
7469 // `nros-rmw-xrce-cffi`'s `register_smoke`, which is exactly the
7470 // backend this over-strict list was refusing.
7471 }
7472
7473 // ------------------------------------------------------------------
7474 // issue 1327 — the four service/client `*_get_actual_qos` slots.
7475 //
7476 // Cyclonedds filled all four and NOTHING dispatched them, so the fix for
7477 // the bug issue 0823 describes sat unreached in the tree. These tests are
7478 // about the CONSUMER: that a `create_service` / `create_client` reaches
7479 // each direction's slot, that it hands the slot `UNKNOWN` rather than the
7480 // request or a zeroed struct, and — issue 1437 — that it KEEPS the answer,
7481 // because a read-back that is logged and dropped cannot be asked.
7482 //
7483 // The pre-load was the REQUEST until issue 1437, which inverted the slot's
7484 // own contract: `rmw_vtable.h` says a backend writes `*_UNKNOWN` for a
7485 // policy it cannot determine, so a field nobody overwrote read back as
7486 // GRANTED and the one consumer saw agreement exactly where the backend had
7487 // said nothing.
7488 //
7489 // They refuse to pass vacuously the same way 0823's ctest does: the
7490 // scripted backend writes values the requested profile cannot have, so an
7491 // implementation that echoes its input and one that zeroes it both fail.
7492 // ------------------------------------------------------------------
7493
7494 /// Four counters, indexed [service-request, service-response,
7495 /// client-request, client-response].
7496 #[cfg(feature = "alloc")]
7497 static mut QOS_READBACK_CALLS: [u32; 4] = [0; 4];
7498 /// What each slot was HANDED — the pre-loaded out-struct.
7499 #[cfg(feature = "alloc")]
7500 static mut QOS_READBACK_SAW: [Option<NrosRmwQos>; 4] = [None; 4];
7501
7502 /// A depth no request in these tests states, so reading it back proves the
7503 /// value came from the entity.
7504 #[cfg(feature = "alloc")]
7505 const GRANTED_DEPTH: u16 = 3;
7506
7507 #[cfg(feature = "alloc")]
7508 unsafe fn record_and_grant(idx: usize, qos: *mut NrosRmwQos) -> NrosRmwRet {
7509 unsafe {
7510 QOS_READBACK_CALLS[idx] += 1;
7511 QOS_READBACK_SAW[idx] = Some(*qos);
7512 // Grant something the caller did not ask for, on the two fields
7513 // `report_qos_downgrade` reads.
7514 (*qos).reliability = NROS_RMW_RELIABILITY_BEST_EFFORT as u8;
7515 (*qos).depth = GRANTED_DEPTH;
7516 }
7517 NROS_RMW_RET_OK
7518 }
7519
7520 #[cfg(feature = "alloc")]
7521 unsafe extern "C" fn stub_service_request_qos(
7522 _: *const NrosRmwService,
7523 qos: *mut NrosRmwQos,
7524 ) -> NrosRmwRet {
7525 unsafe { record_and_grant(0, qos) }
7526 }
7527 #[cfg(feature = "alloc")]
7528 unsafe extern "C" fn stub_service_response_qos(
7529 _: *const NrosRmwService,
7530 qos: *mut NrosRmwQos,
7531 ) -> NrosRmwRet {
7532 unsafe { record_and_grant(1, qos) }
7533 }
7534 #[cfg(feature = "alloc")]
7535 unsafe extern "C" fn stub_client_request_qos(
7536 _: *const NrosRmwClient,
7537 qos: *mut NrosRmwQos,
7538 ) -> NrosRmwRet {
7539 unsafe { record_and_grant(2, qos) }
7540 }
7541 #[cfg(feature = "alloc")]
7542 unsafe extern "C" fn stub_client_response_qos(
7543 _: *const NrosRmwClient,
7544 qos: *mut NrosRmwQos,
7545 ) -> NrosRmwRet {
7546 unsafe { record_and_grant(3, qos) }
7547 }
7548
7549 /// The two create slots plus all four read-backs, and nothing else — the
7550 /// shape a backend gets from designated init. `..EMPTY_VTABLE` keeps this
7551 /// from costing a line per slot the next time the struct grows.
7552 #[cfg(feature = "alloc")]
7553 static READBACK_VTABLE: NrosRmwVtable = NrosRmwVtable {
7554 destroy_session: Some(stub_destroy_session),
7555 create_service: Some(stub_create_service),
7556 destroy_service: Some(stub_destroy_service),
7557 create_client: Some(stub_create_client),
7558 destroy_client: Some(stub_destroy_client),
7559 service_request_subscription_get_actual_qos: Some(stub_service_request_qos),
7560 service_response_publisher_get_actual_qos: Some(stub_service_response_qos),
7561 client_request_publisher_get_actual_qos: Some(stub_client_request_qos),
7562 client_response_subscription_get_actual_qos: Some(stub_client_response_qos),
7563 ..EMPTY_VTABLE
7564 };
7565
7566 #[cfg(feature = "alloc")]
7567 #[test]
7568 fn service_and_client_create_read_the_granted_qos_back() {
7569 use nros_rmw::{ServiceInfo, Session};
7570
7571 let mut session = CffiSession {
7572 vtable: &READBACK_VTABLE,
7573 node_name_buf: [0u8; NAME_BUF_LEN],
7574 namespace_buf: [0u8; NAME_BUF_LEN],
7575 backend_data: core::ptr::dangling_mut::<c_void>(),
7576 domain_id: 0,
7577 // Not exercised here: the QoS mask decides ADMISSION, which the
7578 // runtime layer does, and these tests script the vtable directly.
7579 qos_policies: nros_rmw::QoSPolicyMask::NONE,
7580 };
7581
7582 unsafe {
7583 QOS_READBACK_CALLS = [0; 4];
7584 QOS_READBACK_SAW = [None; 4];
7585 }
7586
7587 // A request the scripted grant differs from on both reported fields.
7588 let requested = nros_rmw::QoSProfile::default().reliable().keep_last(10);
7589 let lowered = NrosRmwQos::try_from(requested).expect("profile lowers");
7590 assert_ne!(lowered.depth, GRANTED_DEPTH, "the test's own premise");
7591
7592 let info = ServiceInfo::new(
7593 "/add_two_ints",
7594 "example_interfaces/srv/AddTwoInts",
7595 "RIHS01",
7596 );
7597 let _srv = Session::create_service(&mut session, &info, requested).expect("service");
7598 let _cli = Session::create_client(&mut session, &info, requested).expect("client");
7599
7600 // 1327's acceptance: the four stop being inert.
7601 assert_eq!(
7602 unsafe { QOS_READBACK_CALLS },
7603 [1, 1, 1, 1],
7604 "every service/client direction's read-back must be dispatched once"
7605 );
7606
7607 // …and each was handed UNKNOWN, not the request and not a zeroed
7608 // struct. Both of the wrong pre-loads are a claim the backend did not
7609 // make: the request says "granted what you asked" for a policy nobody
7610 // read, and zero says "granted BEST_EFFORT / KEEP_LAST(0)".
7611 let unknown = qos_unknown_c();
7612 for (i, saw) in unsafe { QOS_READBACK_SAW }.iter().enumerate() {
7613 let saw = saw.expect("slot recorded nothing");
7614 assert_eq!(
7615 saw.reliability, unknown.reliability,
7616 "slot {i} was handed reliability {} rather than UNKNOWN {}",
7617 saw.reliability, unknown.reliability
7618 );
7619 assert_eq!(saw.durability, unknown.durability, "slot {i} durability");
7620 assert_eq!(saw.history, unknown.history, "slot {i} history");
7621 assert_ne!(
7622 saw.reliability, lowered.reliability,
7623 "slot {i} must not be handed the REQUEST — that is the inverted \
7624 contract issue 1437 fixed"
7625 );
7626 }
7627
7628 // issue 1437 — the answer is RETAINED, per direction. This is what an
7629 // accessor can be built on; before it, every one of these four reads
7630 // went into a log line and was dropped.
7631 use nros_rmw::{ClientTrait, ServiceTrait};
7632 assert_eq!(
7633 ServiceTrait::request_subscription_actual_qos(&_srv).depth,
7634 u32::from(GRANTED_DEPTH),
7635 "the service's request direction must report the GRANT"
7636 );
7637 assert_eq!(
7638 ServiceTrait::response_publisher_actual_qos(&_srv).reliability,
7639 nros_rmw::QoSReliabilityPolicy::BestEffort,
7640 "the service's response direction must report the GRANT"
7641 );
7642 assert_eq!(
7643 ClientTrait::request_publisher_actual_qos(&_cli).depth,
7644 u32::from(GRANTED_DEPTH),
7645 "the client's request direction must report the GRANT"
7646 );
7647 assert_ne!(
7648 ClientTrait::response_subscription_actual_qos(&_cli).depth,
7649 requested.depth,
7650 "reporting the request back is the bug, not the feature"
7651 );
7652 }
7653
7654 /// The helper the six sites share: it returns what the BACKEND answered.
7655 /// An implementation that echoed its input would return the request, and a
7656 /// zeroing one would return zeros; only a real read returns the grant.
7657 #[cfg(feature = "alloc")]
7658 #[test]
7659 fn the_read_back_helper_returns_the_grant_not_the_request() {
7660 unsafe {
7661 QOS_READBACK_CALLS = [0; 4];
7662 QOS_READBACK_SAW = [None; 4];
7663 }
7664 let requested =
7665 NrosRmwQos::try_from(nros_rmw::QoSProfile::default().reliable().keep_last(10))
7666 .expect("profile lowers");
7667 let entity = NrosRmwClient {
7668 service_name: core::ptr::null(),
7669 type_name: core::ptr::null(),
7670 _reserved: [0u8; 8],
7671 backend_data: core::ptr::null_mut(),
7672 };
7673 // SAFETY: the scripted slot reads and writes only `qos`.
7674 let granted = unsafe {
7675 granted_qos_of(
7676 "client request publisher",
7677 "/add_two_ints",
7678 &requested,
7679 &entity,
7680 Some(stub_client_request_qos),
7681 )
7682 };
7683 assert_eq!(granted.depth, GRANTED_DEPTH);
7684 assert_eq!(
7685 granted.reliability, NROS_RMW_RELIABILITY_BEST_EFFORT as u8,
7686 "the grant, not the request"
7687 );
7688 assert_ne!(granted.depth, requested.depth);
7689 }
7690
7691 /// A backend with NO read-back slot answers an ABSENCE, never the request.
7692 ///
7693 /// This is the arm that decides what XRCE and zenoh-pico report, and the
7694 /// one where returning the request would be most tempting and most wrong:
7695 /// there is no negotiation to read, so "you got what you asked for" is a
7696 /// claim nobody made.
7697 #[cfg(feature = "alloc")]
7698 #[test]
7699 fn a_null_read_back_slot_answers_unknown_not_the_request() {
7700 let requested =
7701 NrosRmwQos::try_from(nros_rmw::QoSProfile::default().reliable().keep_last(10))
7702 .expect("profile lowers");
7703 let entity = NrosRmwClient {
7704 service_name: core::ptr::null(),
7705 type_name: core::ptr::null(),
7706 _reserved: [0u8; 8],
7707 backend_data: core::ptr::null_mut(),
7708 };
7709 // SAFETY: the slot is NULL, so nothing dereferences `entity`.
7710 let granted = unsafe {
7711 granted_qos_of::<NrosRmwClient>(
7712 "client request publisher",
7713 "/add_two_ints",
7714 &requested,
7715 &entity,
7716 None,
7717 )
7718 };
7719 assert_eq!(granted.reliability, qos_unknown_c().reliability);
7720 assert_ne!(
7721 granted.reliability, requested.reliability,
7722 "a missing read-back must not be reported as a grant of the request"
7723 );
7724 assert!(
7725 qos_from_c(&granted).has_unknown(),
7726 "and it must read back as an absence in the Rust vocabulary too"
7727 );
7728 }
7729
7730 // ------------------------------------------------------------------
7731 // issue 1329 — the route answers the REGISTERED backend, not a union.
7732 // ------------------------------------------------------------------
7733
7734 unsafe extern "C" fn stub_supported_qos_policies(
7735 _: *const NrosRmwSession,
7736 out_mask: *mut u32,
7737 ) -> NrosRmwRet {
7738 // A mask no union in the tree ever produced, so passing this cannot be
7739 // an accident of the old constant still being returned.
7740 unsafe {
7741 *out_mask = (NROS_RMW_QOS_POLICY_RELIABILITY | NROS_RMW_QOS_POLICY_LIFESPAN) as u32
7742 };
7743 NROS_RMW_RET_OK
7744 }
7745
7746 /// Only what `open_with_vtable` and `Drop` reach, plus the slot under
7747 /// test — the shape a C backend gets from designated init.
7748 static QOS_ROUTE_VTABLE: NrosRmwVtable = NrosRmwVtable {
7749 create_session: Some(stub_create_session),
7750 destroy_session: Some(stub_destroy_session),
7751 supported_qos_policies: Some(stub_supported_qos_policies),
7752 ..EMPTY_VTABLE
7753 };
7754
7755 /// The same, with the slot left NULL.
7756 static QOS_NO_SLOT_VTABLE: NrosRmwVtable = NrosRmwVtable {
7757 create_session: Some(stub_create_session),
7758 destroy_session: Some(stub_destroy_session),
7759 ..EMPTY_VTABLE
7760 };
7761
7762 #[test]
7763 fn the_route_returns_the_registered_backends_mask() {
7764 use nros_rmw::{QoSPolicyMask, Session};
7765
7766 let session =
7767 CffiSession::open_with_vtable(&QOS_ROUTE_VTABLE, "", 0, 0, "n", "", core::ptr::null())
7768 .expect("session open");
7769 assert_eq!(
7770 Session::supported_qos_policies(&session),
7771 QoSPolicyMask::RELIABILITY | QoSPolicyMask::LIFESPAN,
7772 "the route must report what the backend said, not a union over every backend"
7773 );
7774 }
7775
7776 /// A NULL slot is the backend declining to say, and the ABI reads that as
7777 /// honouring nothing. Asserted rather than assumed, because the two
7778 /// tempting alternatives — the union, or "skip validation" — are both the
7779 /// bug, and only a test distinguishes this answer from them.
7780 #[test]
7781 fn a_backend_that_fills_no_mask_slot_honours_nothing() {
7782 use nros_rmw::{QoSPolicyMask, Session};
7783
7784 let session = CffiSession::open_with_vtable(
7785 &QOS_NO_SLOT_VTABLE,
7786 "",
7787 0,
7788 0,
7789 "n",
7790 "",
7791 core::ptr::null(),
7792 )
7793 .expect("session open");
7794 assert_eq!(
7795 Session::supported_qos_policies(&session),
7796 QoSPolicyMask::NONE,
7797 "a NULL slot is `has not said`, which is not `honours everything`"
7798 );
7799 }
7800
7801 /// A NULL slot is a declared absence — no read, no report, no error. The
7802 /// caller turns that `None` into UNKNOWN; see
7803 /// `a_null_read_back_slot_answers_unknown_not_the_request`.
7804 #[cfg(feature = "alloc")]
7805 #[test]
7806 fn a_null_read_back_slot_reports_nothing() {
7807 let entity = NrosRmwClient {
7808 service_name: core::ptr::null(),
7809 type_name: core::ptr::null(),
7810 _reserved: [0u8; 8],
7811 backend_data: core::ptr::null_mut(),
7812 };
7813 // SAFETY: no slot is called.
7814 let granted = unsafe {
7815 read_granted_qos(
7816 &entity,
7817 None::<unsafe extern "C" fn(*const NrosRmwClient, *mut NrosRmwQos) -> NrosRmwRet>,
7818 )
7819 };
7820 assert!(granted.is_none());
7821 }
7822
7823 // And a required slot must STILL be refused even when everything else is
7824 // present — so the fix cannot be mistaken for "the gate was weakened".
7825 #[test]
7826 fn register_still_rejects_a_missing_required_slot() {
7827 let mut vt = STUB_VTABLE;
7828 vt.publish = None;
7829
7830 assert_eq!(first_missing_vtable_slot(&vt), Some("publish"));
7831
7832 let rc = unsafe { nros_rmw_cffi_register_named(c"no_publish_0349".as_ptr(), &vt) };
7833 assert_eq!(rc, NROS_RMW_RET_INVALID_ARGUMENT);
7834 }
7835}