Skip to main content

rustorb_ffi/
pi.rs

1//! Portable Interceptors and `IOP::Codec` (docs/portable-interceptors.md).
2//!
3//! Interceptors and ORB initializers are the caller's objects behind a
4//! table of callbacks, reference counted like servant managers. Each point
5//! gets a handle of the core's info object, valid only during the callback
6//! (the bindings check that themselves), and returns a status, after
7//! `rorb_pi_error_*` when it raises.
8
9use std::ffi::{c_char, c_int, c_void};
10use std::sync::Arc;
11
12use rustorb_core::iop::{Codec, CodecError, Encoding, ServiceContext, TaggedComponent};
13use rustorb_core::pi::{
14    ClientRequestInfo, ClientRequestInterceptor, InterceptError, Interceptor, IorInfo,
15    IorInterceptor, OrbInitInfo, OrbInitializer, Parameter, PiCurrent, ServerRequestInfo,
16    ServerRequestInterceptor,
17};
18use rustorb_core::{
19    Any, CompletionStatus, ObjectRef, Orb, OrbOptions, PolicyValue, ResolveError, SystemException,
20    SystemExceptionKind, TypeCode,
21};
22
23use crate::{
24    Bytes, Exception, OK, Status, completion_status, guard, into_handle, local, set_local,
25    set_system, str_arg, sys,
26};
27
28// --- errors of the caller's points -------------------------------------------
29
30/// `rorb_pi_error`: what a point raised.
31#[derive(Debug, Default)]
32pub struct PiError(Option<InterceptError>);
33
34#[unsafe(no_mangle)]
35pub unsafe extern "C" fn rorb_pi_error_forward(error: *mut PiError, obj: *mut ObjectRef) {
36    let error = unsafe { &mut *error };
37    error.0 = Some(match unsafe { obj.as_ref() } {
38        Some(obj) => InterceptError::ForwardRequest(obj.clone()),
39        None => {
40            InterceptError::System(sys(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No))
41        }
42    });
43}
44
45#[unsafe(no_mangle)]
46pub unsafe extern "C" fn rorb_pi_error_system(
47    error: *mut PiError,
48    id: *const c_char,
49    len: usize,
50    minor: u32,
51    completed: u32,
52) {
53    let error = unsafe { &mut *error };
54    let id = unsafe { str_arg(id, len) }.unwrap_or("IDL:omg.org/CORBA/UNKNOWN:1.0");
55    error.0 = Some(InterceptError::System(SystemException {
56        repository_id: id.to_owned(),
57        minor,
58        completed: completion_status(completed),
59    }));
60}
61
62/// What a point that returned `status` raised.
63fn raised(status: Status, error: PiError) -> Result<(), InterceptError> {
64    if status == OK {
65        return Ok(());
66    }
67    Err(error.0.unwrap_or_else(|| {
68        InterceptError::System(sys(
69            SystemExceptionKind::UNKNOWN,
70            0,
71            CompletionStatus::Maybe,
72        ))
73    }))
74}
75
76fn invalid_point() -> SystemException {
77    sys(
78        SystemExceptionKind::BAD_INV_ORDER,
79        rustorb_core::pi::minor::INVALID_POINT,
80        CompletionStatus::No,
81    )
82}
83
84/// `ForwardRequest` where the point cannot raise it is `BAD_INV_ORDER`.
85fn system_only(r: Result<(), InterceptError>) -> Result<(), SystemException> {
86    match r {
87        Ok(()) => Ok(()),
88        Err(InterceptError::System(e)) => Err(e),
89        Err(InterceptError::ForwardRequest(_)) => Err(invalid_point()),
90    }
91}
92
93// --- the caller's objects ------------------------------------------------------
94
95/// The info objects as the callbacks see them.
96pub type ClientInfo = ClientRequestInfo<'static>;
97pub type ServerInfo = ServerRequestInfo<'static>;
98pub type IorInfoHandle = IorInfo<'static>;
99pub type InitInfo = OrbInitInfo<'static>;
100
101type Point<I> = Option<extern "C" fn(*mut c_void, *const I, *mut PiError) -> Status>;
102
103/// `rorb_client_interceptor_vtable`.
104#[repr(C)]
105#[derive(Debug)]
106pub struct ClientVtable {
107    pub send_request: Point<ClientInfo>,
108    pub receive_reply: Point<ClientInfo>,
109    pub receive_exception: Point<ClientInfo>,
110    pub receive_other: Point<ClientInfo>,
111    pub destroy: Option<extern "C" fn(*mut c_void)>,
112    pub add_ref: extern "C" fn(*mut c_void),
113    pub remove_ref: extern "C" fn(*mut c_void),
114}
115
116/// `rorb_server_interceptor_vtable`.
117#[repr(C)]
118#[derive(Debug)]
119pub struct ServerVtable {
120    pub receive_request_service_contexts: Point<ServerInfo>,
121    pub receive_request: Point<ServerInfo>,
122    pub send_reply: Point<ServerInfo>,
123    pub send_exception: Point<ServerInfo>,
124    pub send_other: Point<ServerInfo>,
125    pub destroy: Option<extern "C" fn(*mut c_void)>,
126    pub add_ref: extern "C" fn(*mut c_void),
127    pub remove_ref: extern "C" fn(*mut c_void),
128}
129
130/// `rorb_ior_interceptor_vtable`.
131#[repr(C)]
132#[derive(Debug)]
133pub struct IorVtable {
134    pub establish_components: Point<IorInfoHandle>,
135    pub destroy: Option<extern "C" fn(*mut c_void)>,
136    pub add_ref: extern "C" fn(*mut c_void),
137    pub remove_ref: extern "C" fn(*mut c_void),
138}
139
140/// `rorb_orb_initializer_vtable`.
141#[repr(C)]
142#[derive(Debug)]
143pub struct InitializerVtable {
144    pub pre_init: Option<extern "C" fn(*mut c_void, *mut InitInfo, *mut PiError) -> Status>,
145    pub post_init: Option<extern "C" fn(*mut c_void, *mut InitInfo, *mut PiError) -> Status>,
146    pub add_ref: extern "C" fn(*mut c_void),
147    pub remove_ref: extern "C" fn(*mut c_void),
148}
149
150/// `rorb_orb_initializer`: an initializer of `rorb_orb_init_pi`.
151#[repr(C)]
152#[derive(Debug)]
153pub struct InitializerEntry {
154    pub this: *mut c_void,
155    pub vtable: *const InitializerVtable,
156}
157
158trait Refs {
159    fn add_ref(&self) -> extern "C" fn(*mut c_void);
160    fn remove_ref(&self) -> extern "C" fn(*mut c_void);
161}
162
163macro_rules! refs {
164    ($($vt:ty),*) => {$(
165        impl Refs for $vt {
166            fn add_ref(&self) -> extern "C" fn(*mut c_void) {
167                self.add_ref
168            }
169            fn remove_ref(&self) -> extern "C" fn(*mut c_void) {
170                self.remove_ref
171            }
172        }
173    )*};
174}
175
176refs!(ClientVtable, ServerVtable, IorVtable, InitializerVtable);
177
178/// One of the caller's objects with its callbacks and, for an
179/// interceptor, its name.
180struct Caller<V: Refs> {
181    this: *mut c_void,
182    vtable: *const V,
183    name: String,
184}
185
186// The caller's objects are called from any thread, as the header says.
187unsafe impl<V: Refs> Send for Caller<V> {}
188unsafe impl<V: Refs> Sync for Caller<V> {}
189
190impl<V: Refs> Caller<V> {
191    fn new(this: *mut c_void, vtable: *const V, name: String) -> Arc<Self> {
192        (unsafe { &*vtable }.add_ref())(this);
193        Arc::new(Caller { this, vtable, name })
194    }
195
196    fn vtable(&self) -> &V {
197        unsafe { &*self.vtable }
198    }
199}
200
201impl<V: Refs> Drop for Caller<V> {
202    fn drop(&mut self) {
203        (self.vtable().remove_ref())(self.this);
204    }
205}
206
207fn call<I>(this: *mut c_void, point: Point<I>, info: &I) -> Result<(), InterceptError> {
208    let Some(point) = point else {
209        return Ok(());
210    };
211    let mut error = PiError::default();
212    let status = point(this, info, &mut error);
213    raised(status, error)
214}
215
216/// The info as the `'static` type of the callbacks: valid only during
217/// them, as the header says.
218fn erase<T, U>(info: &T) -> &U {
219    unsafe { &*(info as *const T).cast::<U>() }
220}
221
222macro_rules! interceptor {
223    ($vt:ty) => {
224        impl Interceptor for Caller<$vt> {
225            fn name(&self) -> &str {
226                &self.name
227            }
228
229            fn destroy(&self) {
230                if let Some(destroy) = self.vtable().destroy {
231                    destroy(self.this);
232                }
233            }
234        }
235    };
236}
237
238interceptor!(ClientVtable);
239interceptor!(ServerVtable);
240interceptor!(IorVtable);
241
242impl ClientRequestInterceptor for Caller<ClientVtable> {
243    fn send_request(&self, ri: &ClientRequestInfo<'_>) -> Result<(), InterceptError> {
244        call(self.this, self.vtable().send_request, erase(ri))
245    }
246
247    fn receive_reply(&self, ri: &ClientRequestInfo<'_>) -> Result<(), SystemException> {
248        system_only(call(self.this, self.vtable().receive_reply, erase(ri)))
249    }
250
251    fn receive_exception(&self, ri: &ClientRequestInfo<'_>) -> Result<(), InterceptError> {
252        call(self.this, self.vtable().receive_exception, erase(ri))
253    }
254
255    fn receive_other(&self, ri: &ClientRequestInfo<'_>) -> Result<(), InterceptError> {
256        call(self.this, self.vtable().receive_other, erase(ri))
257    }
258}
259
260impl ServerRequestInterceptor for Caller<ServerVtable> {
261    fn receive_request_service_contexts(
262        &self,
263        ri: &ServerRequestInfo<'_>,
264    ) -> Result<(), InterceptError> {
265        call(
266            self.this,
267            self.vtable().receive_request_service_contexts,
268            erase(ri),
269        )
270    }
271
272    fn receive_request(&self, ri: &ServerRequestInfo<'_>) -> Result<(), InterceptError> {
273        call(self.this, self.vtable().receive_request, erase(ri))
274    }
275
276    fn send_reply(&self, ri: &ServerRequestInfo<'_>) -> Result<(), SystemException> {
277        system_only(call(self.this, self.vtable().send_reply, erase(ri)))
278    }
279
280    fn send_exception(&self, ri: &ServerRequestInfo<'_>) -> Result<(), InterceptError> {
281        call(self.this, self.vtable().send_exception, erase(ri))
282    }
283
284    fn send_other(&self, ri: &ServerRequestInfo<'_>) -> Result<(), InterceptError> {
285        call(self.this, self.vtable().send_other, erase(ri))
286    }
287}
288
289impl IorInterceptor for Caller<IorVtable> {
290    fn establish_components(&self, info: &IorInfo<'_>) -> Result<(), SystemException> {
291        system_only(call(
292            self.this,
293            self.vtable().establish_components,
294            erase(info),
295        ))
296    }
297}
298
299impl Caller<InitializerVtable> {
300    fn init(
301        &self,
302        point: Option<extern "C" fn(*mut c_void, *mut InitInfo, *mut PiError) -> Status>,
303        info: &mut OrbInitInfo<'_>,
304    ) -> Result<(), SystemException> {
305        let Some(point) = point else {
306            return Ok(());
307        };
308        let mut error = PiError::default();
309        let ptr = (info as *mut OrbInitInfo<'_>).cast::<InitInfo>();
310        let status = point(self.this, ptr, &mut error);
311        system_only(raised(status, error))
312    }
313}
314
315impl OrbInitializer for Caller<InitializerVtable> {
316    fn pre_init(&self, info: &mut OrbInitInfo<'_>) -> Result<(), SystemException> {
317        self.init(self.vtable().pre_init, info)
318    }
319
320    fn post_init(&self, info: &mut OrbInitInfo<'_>) -> Result<(), SystemException> {
321        self.init(self.vtable().post_init, info)
322    }
323}
324
325/// `PortableInterceptor::register_orb_initializer`: for the ORBs created
326/// after it in this process. The vtable must outlive them.
327#[unsafe(no_mangle)]
328pub unsafe extern "C" fn rorb_register_orb_initializer(
329    this: *mut c_void,
330    vtable: *const InitializerVtable,
331) {
332    rustorb_core::pi::register_orb_initializer(Caller::new(this, vtable, String::new()));
333}
334
335/// `ORB_init` with ORB id `orb_id` (which `-ORBid` overrides) and these
336/// initializers, run after the registered ones.
337#[unsafe(no_mangle)]
338pub unsafe extern "C" fn rorb_orb_init_pi(
339    argc: *mut c_int,
340    argv: *mut *mut c_char,
341    orb_id: *const c_char,
342    orb_id_len: usize,
343    initializers: *const InitializerEntry,
344    count: usize,
345    orb: *mut *mut Orb,
346    exc: *mut Exception,
347) -> Status {
348    let orb_id = match unsafe { str_arg(orb_id, orb_id_len) } {
349        Ok(id) => id.to_owned(),
350        Err(e) => return unsafe { set_system(exc, &e) },
351    };
352    let entries: &[InitializerEntry] = if initializers.is_null() || count == 0 {
353        &[]
354    } else {
355        unsafe { std::slice::from_raw_parts(initializers, count) }
356    };
357    let inits: Vec<Arc<dyn OrbInitializer>> = entries
358        .iter()
359        .map(|e| Caller::new(e.this, e.vtable, String::new()) as Arc<dyn OrbInitializer>)
360        .collect();
361    unsafe {
362        crate::orb::init_with(argc, argv, orb, exc, move |args| {
363            let mut options = OrbOptions {
364                arguments: args.clone(),
365                orb_id,
366                initializers: inits,
367                ..OrbOptions::default()
368            };
369            options.parse_args(args)?;
370            Orb::with_options(options)
371        })
372    }
373}
374
375// --- helpers of the accessors --------------------------------------------------
376
377/// Called with each string of a list.
378pub type EachString = extern "C" fn(*mut c_void, *const c_char, usize);
379/// Called with each tagged component (or service context) of a list.
380pub type EachBytes = extern "C" fn(*mut c_void, u32, *const u8, usize);
381/// Called with each parameter: an any handle the callee takes, and the
382/// mode (0 in, 1 out, 2 inout).
383pub type EachParameter = extern "C" fn(*mut c_void, *mut Any, u32);
384/// Called with each TypeCode, a handle the callee takes.
385pub type EachTypeCode = extern "C" fn(*mut c_void, *mut TypeCode);
386
387fn result<T>(exc: *mut Exception, r: Result<T, SystemException>, out: impl FnOnce(T)) -> Status {
388    match r {
389        Ok(v) => {
390            out(v);
391            OK
392        }
393        Err(e) => unsafe { set_system(exc, &e) },
394    }
395}
396
397fn each_string(context: *mut c_void, each: EachString, list: &[String]) {
398    for s in list {
399        each(context, s.as_ptr() as *const c_char, s.len());
400    }
401}
402
403fn each_parameter(context: *mut c_void, each: EachParameter, list: Vec<Parameter>) {
404    for p in list {
405        let mode = match p.mode {
406            rustorb_core::dii::ArgMode::In => 0,
407            rustorb_core::dii::ArgMode::Out => 1,
408            rustorb_core::dii::ArgMode::InOut => 2,
409        };
410        each(context, into_handle(p.argument), mode);
411    }
412}
413
414fn policy_out(p: PolicyValue, raw: *mut u64) {
415    unsafe { *raw = p.raw_value() };
416}
417
418unsafe fn bytes_out(out: *mut Bytes, v: Vec<u8>) {
419    unsafe { *out = Bytes::new(v) };
420}
421
422fn invalid_slot(exc: *mut Exception) -> Status {
423    unsafe { set_local(exc, local::INVALID_SLOT, 0) }
424}
425
426/// Accessors that both request infos have, as `rorb_cri_*` and
427/// `rorb_sri_*`.
428macro_rules! request_info {
429    ($info:ty, $request_id:ident, $operation:ident, $response_expected:ident,
430     $sync_scope:ident, $reply_status:ident, $forward_reference:ident, $get_slot:ident,
431     $get_request_sc:ident, $get_reply_sc:ident, $arguments:ident, $exceptions:ident,
432     $result:ident) => {
433        #[unsafe(no_mangle)]
434        pub unsafe extern "C" fn $request_id(ri: *const $info) -> u32 {
435            unsafe { &*ri }.request_id()
436        }
437
438        #[unsafe(no_mangle)]
439        pub unsafe extern "C" fn $operation(ri: *const $info, len: *mut usize) -> *const c_char {
440            let op = unsafe { &*ri }.operation();
441            unsafe { *len = op.len() };
442            op.as_ptr() as *const c_char
443        }
444
445        #[unsafe(no_mangle)]
446        pub unsafe extern "C" fn $response_expected(ri: *const $info) -> i32 {
447            i32::from(unsafe { &*ri }.response_expected())
448        }
449
450        #[unsafe(no_mangle)]
451        pub unsafe extern "C" fn $sync_scope(ri: *const $info) -> i16 {
452            unsafe { &*ri }.sync_scope()
453        }
454
455        #[unsafe(no_mangle)]
456        pub unsafe extern "C" fn $reply_status(
457            ri: *const $info,
458            status: *mut i16,
459            exc: *mut Exception,
460        ) -> Status {
461            guard(exc, || {
462                result(exc, unsafe { &*ri }.reply_status(), |s| unsafe {
463                    *status = s
464                })
465            })
466        }
467
468        #[unsafe(no_mangle)]
469        pub unsafe extern "C" fn $forward_reference(
470            ri: *const $info,
471            obj: *mut *mut ObjectRef,
472            exc: *mut Exception,
473        ) -> Status {
474            guard(exc, || {
475                result(exc, unsafe { &*ri }.forward_reference(), |o| unsafe {
476                    *obj = into_handle(o)
477                })
478            })
479        }
480
481        #[unsafe(no_mangle)]
482        pub unsafe extern "C" fn $get_slot(
483            ri: *const $info,
484            id: u32,
485            any: *mut *mut Any,
486            exc: *mut Exception,
487        ) -> Status {
488            guard(exc, || match unsafe { &*ri }.get_slot(id) {
489                Ok(a) => {
490                    unsafe { *any = into_handle(a) };
491                    OK
492                }
493                Err(_) => invalid_slot(exc),
494            })
495        }
496
497        #[unsafe(no_mangle)]
498        pub unsafe extern "C" fn $get_request_sc(
499            ri: *const $info,
500            id: u32,
501            data: *mut Bytes,
502            exc: *mut Exception,
503        ) -> Status {
504            guard(exc, || {
505                result(
506                    exc,
507                    unsafe { &*ri }.get_request_service_context(id),
508                    |sc| unsafe { bytes_out(data, sc.context_data) },
509                )
510            })
511        }
512
513        #[unsafe(no_mangle)]
514        pub unsafe extern "C" fn $get_reply_sc(
515            ri: *const $info,
516            id: u32,
517            data: *mut Bytes,
518            exc: *mut Exception,
519        ) -> Status {
520            guard(exc, || {
521                result(
522                    exc,
523                    unsafe { &*ri }.get_reply_service_context(id),
524                    |sc| unsafe { bytes_out(data, sc.context_data) },
525                )
526            })
527        }
528
529        #[unsafe(no_mangle)]
530        pub unsafe extern "C" fn $arguments(
531            ri: *const $info,
532            context: *mut c_void,
533            each: EachParameter,
534            exc: *mut Exception,
535        ) -> Status {
536            guard(exc, || {
537                result(exc, unsafe { &*ri }.arguments(), |list| {
538                    each_parameter(context, each, list)
539                })
540            })
541        }
542
543        #[unsafe(no_mangle)]
544        pub unsafe extern "C" fn $exceptions(
545            ri: *const $info,
546            context: *mut c_void,
547            each: EachTypeCode,
548            exc: *mut Exception,
549        ) -> Status {
550            guard(exc, || {
551                result(exc, unsafe { &*ri }.exceptions(), |list| {
552                    for tc in list {
553                        each(context, into_handle(tc));
554                    }
555                })
556            })
557        }
558
559        #[unsafe(no_mangle)]
560        pub unsafe extern "C" fn $result(
561            ri: *const $info,
562            any: *mut *mut Any,
563            exc: *mut Exception,
564        ) -> Status {
565            guard(exc, || {
566                result(exc, unsafe { &*ri }.result(), |a| unsafe {
567                    *any = into_handle(a)
568                })
569            })
570        }
571    };
572}
573
574request_info!(
575    ClientInfo,
576    rorb_cri_request_id,
577    rorb_cri_operation,
578    rorb_cri_response_expected,
579    rorb_cri_sync_scope,
580    rorb_cri_reply_status,
581    rorb_cri_forward_reference,
582    rorb_cri_get_slot,
583    rorb_cri_get_request_service_context,
584    rorb_cri_get_reply_service_context,
585    rorb_cri_arguments,
586    rorb_cri_exceptions,
587    rorb_cri_result
588);
589
590request_info!(
591    ServerInfo,
592    rorb_sri_request_id,
593    rorb_sri_operation,
594    rorb_sri_response_expected,
595    rorb_sri_sync_scope,
596    rorb_sri_reply_status,
597    rorb_sri_forward_reference,
598    rorb_sri_get_slot,
599    rorb_sri_get_request_service_context,
600    rorb_sri_get_reply_service_context,
601    rorb_sri_arguments,
602    rorb_sri_exceptions,
603    rorb_sri_result
604);
605
606// --- ClientRequestInfo ------------------------------------------------------------
607
608#[unsafe(no_mangle)]
609pub unsafe extern "C" fn rorb_cri_target(ri: *const ClientInfo) -> *mut ObjectRef {
610    into_handle(unsafe { &*ri }.target().clone())
611}
612
613#[unsafe(no_mangle)]
614pub unsafe extern "C" fn rorb_cri_effective_target(ri: *const ClientInfo) -> *mut ObjectRef {
615    into_handle(unsafe { &*ri }.effective_target().clone())
616}
617
618/// The tag, and the profile data in `*data`.
619#[unsafe(no_mangle)]
620pub unsafe extern "C" fn rorb_cri_effective_profile(
621    ri: *const ClientInfo,
622    data: *mut Bytes,
623) -> u32 {
624    let p = unsafe { &*ri }.effective_profile();
625    unsafe { bytes_out(data, p.profile_data.clone()) };
626    p.tag
627}
628
629#[unsafe(no_mangle)]
630pub unsafe extern "C" fn rorb_cri_received_exception(
631    ri: *const ClientInfo,
632    any: *mut *mut Any,
633    exc: *mut Exception,
634) -> Status {
635    guard(exc, || {
636        result(exc, unsafe { &*ri }.received_exception(), |a| unsafe {
637            *any = into_handle(a)
638        })
639    })
640}
641
642#[unsafe(no_mangle)]
643pub unsafe extern "C" fn rorb_cri_received_exception_id(
644    ri: *const ClientInfo,
645    id: *mut Bytes,
646    exc: *mut Exception,
647) -> Status {
648    guard(exc, || {
649        result(exc, unsafe { &*ri }.received_exception_id(), |s| unsafe {
650            bytes_out(id, s.into_bytes())
651        })
652    })
653}
654
655#[unsafe(no_mangle)]
656pub unsafe extern "C" fn rorb_cri_get_effective_component(
657    ri: *const ClientInfo,
658    tag: u32,
659    data: *mut Bytes,
660    exc: *mut Exception,
661) -> Status {
662    guard(exc, || {
663        result(
664            exc,
665            unsafe { &*ri }.get_effective_component(tag),
666            |c| unsafe { bytes_out(data, c.component_data) },
667        )
668    })
669}
670
671#[unsafe(no_mangle)]
672pub unsafe extern "C" fn rorb_cri_get_effective_components(
673    ri: *const ClientInfo,
674    tag: u32,
675    context: *mut c_void,
676    each: EachBytes,
677    exc: *mut Exception,
678) -> Status {
679    guard(exc, || {
680        result(exc, unsafe { &*ri }.get_effective_components(tag), |list| {
681            for c in list {
682                each(
683                    context,
684                    c.tag,
685                    c.component_data.as_ptr(),
686                    c.component_data.len(),
687                );
688            }
689        })
690    })
691}
692
693/// 1 with `*raw` set when a policy of the type is in effect, else 0.
694#[unsafe(no_mangle)]
695pub unsafe extern "C" fn rorb_cri_get_request_policy(
696    ri: *const ClientInfo,
697    policy_type: u32,
698    found: *mut i32,
699    raw: *mut u64,
700    exc: *mut Exception,
701) -> Status {
702    guard(exc, || {
703        result(exc, unsafe { &*ri }.get_request_policy(policy_type), |p| {
704            unsafe { *found = i32::from(p.is_some()) };
705            if let Some(p) = p {
706                policy_out(p, raw);
707            }
708        })
709    })
710}
711
712#[unsafe(no_mangle)]
713pub unsafe extern "C" fn rorb_cri_add_request_service_context(
714    ri: *const ClientInfo,
715    id: u32,
716    data: *const u8,
717    len: usize,
718    replace: i32,
719    exc: *mut Exception,
720) -> Status {
721    guard(exc, || {
722        let sc = ServiceContext {
723            context_id: id,
724            context_data: unsafe { crate::bytes_arg(data, len) }.to_vec(),
725        };
726        result(
727            exc,
728            unsafe { &*ri }.add_request_service_context(sc, replace != 0),
729            |()| (),
730        )
731    })
732}
733
734// --- ServerRequestInfo ------------------------------------------------------------
735
736#[unsafe(no_mangle)]
737pub unsafe extern "C" fn rorb_sri_set_slot(
738    ri: *const ServerInfo,
739    id: u32,
740    any: *const Any,
741    exc: *mut Exception,
742) -> Status {
743    guard(exc, || {
744        let value = unsafe { any.as_ref() }.cloned().unwrap_or_default();
745        match unsafe { &*ri }.set_slot(id, value) {
746            Ok(()) => OK,
747            Err(_) => invalid_slot(exc),
748        }
749    })
750}
751
752#[unsafe(no_mangle)]
753pub unsafe extern "C" fn rorb_sri_add_reply_service_context(
754    ri: *const ServerInfo,
755    id: u32,
756    data: *const u8,
757    len: usize,
758    replace: i32,
759    exc: *mut Exception,
760) -> Status {
761    guard(exc, || {
762        let sc = ServiceContext {
763            context_id: id,
764            context_data: unsafe { crate::bytes_arg(data, len) }.to_vec(),
765        };
766        result(
767            exc,
768            unsafe { &*ri }.add_reply_service_context(sc, replace != 0),
769            |()| (),
770        )
771    })
772}
773
774#[unsafe(no_mangle)]
775pub unsafe extern "C" fn rorb_sri_sending_exception(
776    ri: *const ServerInfo,
777    any: *mut *mut Any,
778    exc: *mut Exception,
779) -> Status {
780    guard(exc, || {
781        result(exc, unsafe { &*ri }.sending_exception(), |a| unsafe {
782            *any = into_handle(a)
783        })
784    })
785}
786
787#[unsafe(no_mangle)]
788pub unsafe extern "C" fn rorb_sri_sending_exception_id(
789    ri: *const ServerInfo,
790    id: *mut Bytes,
791    exc: *mut Exception,
792) -> Status {
793    guard(exc, || {
794        result(exc, unsafe { &*ri }.sending_exception_id(), |s| unsafe {
795            bytes_out(id, s.into_bytes())
796        })
797    })
798}
799
800#[unsafe(no_mangle)]
801pub unsafe extern "C" fn rorb_sri_object_id(
802    ri: *const ServerInfo,
803    id: *mut Bytes,
804    exc: *mut Exception,
805) -> Status {
806    guard(exc, || {
807        result(exc, unsafe { &*ri }.object_id(), |v| unsafe {
808            bytes_out(id, v)
809        })
810    })
811}
812
813#[unsafe(no_mangle)]
814pub unsafe extern "C" fn rorb_sri_adapter_id(
815    ri: *const ServerInfo,
816    id: *mut Bytes,
817    exc: *mut Exception,
818) -> Status {
819    guard(exc, || {
820        result(exc, unsafe { &*ri }.adapter_id(), |v| unsafe {
821            bytes_out(id, v)
822        })
823    })
824}
825
826#[unsafe(no_mangle)]
827pub unsafe extern "C" fn rorb_sri_adapter_name(
828    ri: *const ServerInfo,
829    context: *mut c_void,
830    each: EachString,
831    exc: *mut Exception,
832) -> Status {
833    guard(exc, || {
834        result(exc, unsafe { &*ri }.adapter_name(), |names| {
835            each_string(context, each, &names)
836        })
837    })
838}
839
840#[unsafe(no_mangle)]
841pub unsafe extern "C" fn rorb_sri_orb_id(ri: *const ServerInfo, len: *mut usize) -> *const c_char {
842    let s = unsafe { &*ri }.orb_id();
843    unsafe { *len = s.len() };
844    s.as_ptr() as *const c_char
845}
846
847#[unsafe(no_mangle)]
848pub unsafe extern "C" fn rorb_sri_server_id(
849    ri: *const ServerInfo,
850    len: *mut usize,
851) -> *const c_char {
852    let s = unsafe { &*ri }.server_id();
853    unsafe { *len = s.len() };
854    s.as_ptr() as *const c_char
855}
856
857#[unsafe(no_mangle)]
858pub unsafe extern "C" fn rorb_sri_target_most_derived_interface(
859    ri: *const ServerInfo,
860    id: *mut Bytes,
861    exc: *mut Exception,
862) -> Status {
863    guard(exc, || {
864        result(
865            exc,
866            unsafe { &*ri }.target_most_derived_interface(),
867            |s| unsafe { bytes_out(id, s.into_bytes()) },
868        )
869    })
870}
871
872#[unsafe(no_mangle)]
873pub unsafe extern "C" fn rorb_sri_target_is_a(
874    ri: *const ServerInfo,
875    id: *const c_char,
876    len: usize,
877    is_a: *mut i32,
878    exc: *mut Exception,
879) -> Status {
880    guard(exc, || {
881        let id = match unsafe { str_arg(id, len) } {
882            Ok(id) => id,
883            Err(e) => return unsafe { set_system(exc, &e) },
884        };
885        result(exc, unsafe { &*ri }.target_is_a(id), |b| unsafe {
886            *is_a = i32::from(b)
887        })
888    })
889}
890
891#[unsafe(no_mangle)]
892pub unsafe extern "C" fn rorb_sri_get_server_policy(
893    ri: *const ServerInfo,
894    policy_type: u32,
895    raw: *mut u64,
896    exc: *mut Exception,
897) -> Status {
898    guard(exc, || {
899        result(exc, unsafe { &*ri }.get_server_policy(policy_type), |p| {
900            policy_out(p, raw)
901        })
902    })
903}
904
905// --- IORInfo ----------------------------------------------------------------------
906
907#[unsafe(no_mangle)]
908pub unsafe extern "C" fn rorb_ior_info_get_effective_policy(
909    info: *const IorInfoHandle,
910    policy_type: u32,
911    raw: *mut u64,
912    exc: *mut Exception,
913) -> Status {
914    guard(exc, || {
915        result(
916            exc,
917            unsafe { &*info }.get_effective_policy(policy_type),
918            |p| policy_out(p, raw),
919        )
920    })
921}
922
923#[unsafe(no_mangle)]
924pub unsafe extern "C" fn rorb_ior_info_adapter_name(
925    info: *const IorInfoHandle,
926    context: *mut c_void,
927    each: EachString,
928) {
929    each_string(context, each, unsafe { &*info }.adapter_name());
930}
931
932#[unsafe(no_mangle)]
933pub unsafe extern "C" fn rorb_ior_info_add_ior_component(
934    info: *const IorInfoHandle,
935    tag: u32,
936    data: *const u8,
937    len: usize,
938) {
939    unsafe { &*info }.add_ior_component(TaggedComponent {
940        tag,
941        component_data: unsafe { crate::bytes_arg(data, len) }.to_vec(),
942    });
943}
944
945#[unsafe(no_mangle)]
946pub unsafe extern "C" fn rorb_ior_info_add_ior_component_to_profile(
947    info: *const IorInfoHandle,
948    tag: u32,
949    data: *const u8,
950    len: usize,
951    profile_id: u32,
952    exc: *mut Exception,
953) -> Status {
954    guard(exc, || {
955        let c = TaggedComponent {
956            tag,
957            component_data: unsafe { crate::bytes_arg(data, len) }.to_vec(),
958        };
959        result(
960            exc,
961            unsafe { &*info }.add_ior_component_to_profile(c, profile_id),
962            |()| (),
963        )
964    })
965}
966
967// --- ORBInitInfo ------------------------------------------------------------------
968
969#[unsafe(no_mangle)]
970pub unsafe extern "C" fn rorb_init_info_arguments(
971    info: *const InitInfo,
972    context: *mut c_void,
973    each: EachString,
974) {
975    each_string(context, each, unsafe { &*info }.arguments());
976}
977
978#[unsafe(no_mangle)]
979pub unsafe extern "C" fn rorb_init_info_orb_id(
980    info: *const InitInfo,
981    len: *mut usize,
982) -> *const c_char {
983    let s = unsafe { &*info }.orb_id();
984    unsafe { *len = s.len() };
985    s.as_ptr() as *const c_char
986}
987
988/// The ORB being created (a new handle). Calls on it may not work yet.
989#[unsafe(no_mangle)]
990pub unsafe extern "C" fn rorb_init_info_orb(info: *const InitInfo) -> *mut Orb {
991    into_handle(unsafe { &*info }.orb().clone())
992}
993
994#[unsafe(no_mangle)]
995pub unsafe extern "C" fn rorb_init_info_register_initial_reference(
996    info: *const InitInfo,
997    name: *const c_char,
998    len: usize,
999    obj: *mut ObjectRef,
1000    exc: *mut Exception,
1001) -> Status {
1002    guard(exc, || {
1003        let Ok(name) = (unsafe { str_arg(name, len) }) else {
1004            return unsafe { set_local(exc, local::INVALID_NAME, 0) };
1005        };
1006        match unsafe { &*info }.register_initial_reference(name, unsafe { obj.as_ref() }) {
1007            Ok(()) => OK,
1008            Err(ResolveError::InvalidName(_)) => unsafe { set_local(exc, local::INVALID_NAME, 0) },
1009            Err(ResolveError::System(e)) => unsafe { set_system(exc, &e) },
1010        }
1011    })
1012}
1013
1014/// Only in post_init (BAD_INV_ORDER in pre_init).
1015#[unsafe(no_mangle)]
1016pub unsafe extern "C" fn rorb_init_info_resolve_initial_references(
1017    info: *const InitInfo,
1018    name: *const c_char,
1019    len: usize,
1020    obj: *mut *mut ObjectRef,
1021    exc: *mut Exception,
1022) -> Status {
1023    guard(exc, || {
1024        let Ok(name) = (unsafe { str_arg(name, len) }) else {
1025            return unsafe { set_local(exc, local::INVALID_NAME, 0) };
1026        };
1027        match unsafe { &*info }.resolve_initial_references(name) {
1028            Ok(o) => {
1029                unsafe { *obj = into_handle(o) };
1030                OK
1031            }
1032            Err(ResolveError::InvalidName(_)) => unsafe { set_local(exc, local::INVALID_NAME, 0) },
1033            Err(ResolveError::System(e)) => unsafe { set_system(exc, &e) },
1034        }
1035    })
1036}
1037
1038fn added(exc: *mut Exception, r: Result<(), rustorb_core::pi::DuplicateName>) -> Status {
1039    match r {
1040        Ok(()) => OK,
1041        Err(_) => unsafe { set_local(exc, local::DUPLICATE_NAME, 0) },
1042    }
1043}
1044
1045#[unsafe(no_mangle)]
1046pub unsafe extern "C" fn rorb_init_info_add_client_request_interceptor(
1047    info: *mut InitInfo,
1048    name: *const c_char,
1049    len: usize,
1050    this: *mut c_void,
1051    vtable: *const ClientVtable,
1052    exc: *mut Exception,
1053) -> Status {
1054    guard(exc, || {
1055        let name = match unsafe { str_arg(name, len) } {
1056            Ok(n) => n.to_owned(),
1057            Err(e) => return unsafe { set_system(exc, &e) },
1058        };
1059        let i = Caller::new(this, vtable, name);
1060        added(exc, unsafe { &mut *info }.add_client_request_interceptor(i))
1061    })
1062}
1063
1064#[unsafe(no_mangle)]
1065pub unsafe extern "C" fn rorb_init_info_add_server_request_interceptor(
1066    info: *mut InitInfo,
1067    name: *const c_char,
1068    len: usize,
1069    this: *mut c_void,
1070    vtable: *const ServerVtable,
1071    exc: *mut Exception,
1072) -> Status {
1073    guard(exc, || {
1074        let name = match unsafe { str_arg(name, len) } {
1075            Ok(n) => n.to_owned(),
1076            Err(e) => return unsafe { set_system(exc, &e) },
1077        };
1078        let i = Caller::new(this, vtable, name);
1079        added(exc, unsafe { &mut *info }.add_server_request_interceptor(i))
1080    })
1081}
1082
1083#[unsafe(no_mangle)]
1084pub unsafe extern "C" fn rorb_init_info_add_ior_interceptor(
1085    info: *mut InitInfo,
1086    name: *const c_char,
1087    len: usize,
1088    this: *mut c_void,
1089    vtable: *const IorVtable,
1090    exc: *mut Exception,
1091) -> Status {
1092    guard(exc, || {
1093        let name = match unsafe { str_arg(name, len) } {
1094            Ok(n) => n.to_owned(),
1095            Err(e) => return unsafe { set_system(exc, &e) },
1096        };
1097        let i = Caller::new(this, vtable, name);
1098        added(exc, unsafe { &mut *info }.add_ior_interceptor(i))
1099    })
1100}
1101
1102#[unsafe(no_mangle)]
1103pub unsafe extern "C" fn rorb_init_info_allocate_slot_id(info: *mut InitInfo) -> u32 {
1104    unsafe { &mut *info }.allocate_slot_id()
1105}
1106
1107/// PICurrent with the slots allocated so far.
1108#[unsafe(no_mangle)]
1109pub unsafe extern "C" fn rorb_init_info_pi_current(info: *const InitInfo) -> *mut PiCurrent {
1110    into_handle(unsafe { &*info }.pi_current())
1111}
1112
1113// --- PICurrent ----------------------------------------------------------------------
1114
1115#[unsafe(no_mangle)]
1116pub unsafe extern "C" fn rorb_orb_pi_current(orb: *mut Orb) -> *mut PiCurrent {
1117    into_handle(unsafe { &*orb }.pi_current())
1118}
1119
1120#[unsafe(no_mangle)]
1121pub unsafe extern "C" fn rorb_pi_current_release(current: *mut PiCurrent) {
1122    unsafe { crate::release_handle(current) }
1123}
1124
1125#[unsafe(no_mangle)]
1126pub unsafe extern "C" fn rorb_pi_current_get_slot(
1127    current: *const PiCurrent,
1128    id: u32,
1129    any: *mut *mut Any,
1130    exc: *mut Exception,
1131) -> Status {
1132    guard(exc, || match unsafe { &*current }.get_slot(id) {
1133        Ok(a) => {
1134            unsafe { *any = into_handle(a) };
1135            OK
1136        }
1137        Err(_) => invalid_slot(exc),
1138    })
1139}
1140
1141#[unsafe(no_mangle)]
1142pub unsafe extern "C" fn rorb_pi_current_set_slot(
1143    current: *const PiCurrent,
1144    id: u32,
1145    any: *const Any,
1146    exc: *mut Exception,
1147) -> Status {
1148    guard(exc, || {
1149        let value = unsafe { any.as_ref() }.cloned().unwrap_or_default();
1150        match unsafe { &*current }.set_slot(id, value) {
1151            Ok(()) => OK,
1152            Err(_) => invalid_slot(exc),
1153        }
1154    })
1155}
1156
1157// --- Codec ----------------------------------------------------------------------------
1158
1159fn codec_of(
1160    factory: rustorb_core::iop::CodecFactory,
1161    format: i16,
1162    major: u8,
1163    minor: u8,
1164    codec: *mut *mut Codec,
1165    exc: *mut Exception,
1166) -> Status {
1167    let encoding = Encoding {
1168        format,
1169        major_version: major,
1170        minor_version: minor,
1171    };
1172    match factory.create_codec(encoding) {
1173        Ok(c) => {
1174            unsafe { *codec = into_handle(c) };
1175            OK
1176        }
1177        Err(_) => unsafe { set_local(exc, local::UNKNOWN_ENCODING, 0) },
1178    }
1179}
1180
1181/// `CodecFactory::create_codec` of the ORB; RORB_UNKNOWN_ENCODING but for
1182/// ENCODING_CDR_ENCAPS 1.0 to 1.2.
1183#[unsafe(no_mangle)]
1184pub unsafe extern "C" fn rorb_orb_create_codec(
1185    orb: *mut Orb,
1186    format: i16,
1187    major: u8,
1188    minor: u8,
1189    codec: *mut *mut Codec,
1190    exc: *mut Exception,
1191) -> Status {
1192    guard(exc, || {
1193        codec_of(
1194            unsafe { &*orb }.codec_factory(),
1195            format,
1196            major,
1197            minor,
1198            codec,
1199            exc,
1200        )
1201    })
1202}
1203
1204#[unsafe(no_mangle)]
1205pub unsafe extern "C" fn rorb_init_info_create_codec(
1206    info: *const InitInfo,
1207    format: i16,
1208    major: u8,
1209    minor: u8,
1210    codec: *mut *mut Codec,
1211    exc: *mut Exception,
1212) -> Status {
1213    guard(exc, || {
1214        codec_of(
1215            unsafe { &*info }.codec_factory(),
1216            format,
1217            major,
1218            minor,
1219            codec,
1220            exc,
1221        )
1222    })
1223}
1224
1225#[unsafe(no_mangle)]
1226pub unsafe extern "C" fn rorb_codec_release(codec: *mut Codec) {
1227    unsafe { crate::release_handle(codec) }
1228}
1229
1230fn codec_err(exc: *mut Exception, e: CodecError) -> Status {
1231    let code = match e {
1232        CodecError::InvalidTypeForEncoding => local::CODEC_INVALID_TYPE_FOR_ENCODING,
1233        CodecError::FormatMismatch => local::CODEC_FORMAT_MISMATCH,
1234        CodecError::TypeMismatch => local::CODEC_TYPE_MISMATCH,
1235    };
1236    unsafe { set_local(exc, code, 0) }
1237}
1238
1239#[unsafe(no_mangle)]
1240pub unsafe extern "C" fn rorb_codec_encode(
1241    codec: *const Codec,
1242    any: *const Any,
1243    value_only: i32,
1244    data: *mut Bytes,
1245    exc: *mut Exception,
1246) -> Status {
1247    guard(exc, || {
1248        let codec = unsafe { &*codec };
1249        let any = unsafe { &*any };
1250        let r = if value_only != 0 {
1251            codec.encode_value(any)
1252        } else {
1253            codec.encode(any)
1254        };
1255        match r {
1256            Ok(v) => {
1257                unsafe { bytes_out(data, v) };
1258                OK
1259            }
1260            Err(e) => codec_err(exc, e),
1261        }
1262    })
1263}
1264
1265/// `decode` with `tc` NULL, else `decode_value` of a value of type `tc`.
1266#[unsafe(no_mangle)]
1267pub unsafe extern "C" fn rorb_codec_decode(
1268    codec: *const Codec,
1269    data: *const u8,
1270    len: usize,
1271    tc: *const TypeCode,
1272    any: *mut *mut Any,
1273    exc: *mut Exception,
1274) -> Status {
1275    guard(exc, || {
1276        let codec = unsafe { &*codec };
1277        let data = unsafe { crate::bytes_arg(data, len) };
1278        let r = match unsafe { tc.as_ref() } {
1279            Some(tc) => codec.decode_value(data, tc),
1280            None => codec.decode(data),
1281        };
1282        match r {
1283            Ok(a) => {
1284                unsafe { *any = into_handle(a) };
1285                OK
1286            }
1287            Err(e) => codec_err(exc, e),
1288        }
1289    })
1290}