Skip to main content

rustorb_ffi/
orb.rs

1//! `CORBA::ORB`: `rorb_orb` is a boxed [`Orb`].
2
3use std::ffi::{CStr, c_char, c_int, c_void};
4use std::sync::Mutex;
5use std::time::Duration;
6
7use rustorb_core::{ObjectRef, Orb, Poa, ResolveError};
8
9use crate::{
10    Bytes, Exception, OK, Status, guard, into_handle, local, release_handle, set_local, set_system,
11    str_arg,
12};
13
14/// The first ORB initialised and not destroyed: its RootPOA is the
15/// default POA of servants.
16static DEFAULT_ORB: Mutex<Option<Orb>> = Mutex::new(None);
17
18/// The first ORB initialised and not destroyed, if any.
19pub(crate) fn default_orb() -> Option<Orb> {
20    DEFAULT_ORB.lock().unwrap().clone()
21}
22
23#[unsafe(no_mangle)]
24pub unsafe extern "C" fn rorb_orb_init(
25    argc: *mut c_int,
26    argv: *mut *mut c_char,
27    orb: *mut *mut Orb,
28    exc: *mut Exception,
29) -> Status {
30    unsafe { init_with(argc, argv, orb, exc, Orb::init) }
31}
32
33/// `ORB_init` with the ORB made by `make` from the arguments (without
34/// `argv[0]`), which it leaves without the ORB options.
35pub(crate) unsafe fn init_with(
36    argc: *mut c_int,
37    argv: *mut *mut c_char,
38    orb: *mut *mut Orb,
39    exc: *mut Exception,
40    make: impl FnOnce(&mut Vec<String>) -> Result<Orb, rustorb_core::SystemException>,
41) -> Status {
42    guard(exc, || {
43        let count = if argc.is_null() || argv.is_null() {
44            0
45        } else {
46            usize::try_from(unsafe { *argc }).unwrap_or(0)
47        };
48        let ptrs: Vec<*mut c_char> = (0..count).map(|i| unsafe { *argv.add(i) }).collect();
49        let strings: Vec<String> = ptrs
50            .iter()
51            .map(|&p| {
52                if p.is_null() {
53                    String::new()
54                } else {
55                    unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
56                }
57            })
58            .collect();
59        // Keep argv[0] out of the parser, which would keep it anyway.
60        let mut args: Vec<String> = strings.iter().skip(1).cloned().collect();
61        let new_orb = match make(&mut args) {
62            Ok(o) => o,
63            Err(e) => return unsafe { set_system(exc, &e) },
64        };
65        if count > 0 {
66            // The arguments left are a subsequence of the original ones.
67            let mut kept = vec![ptrs[0]];
68            let mut rest = args.iter().peekable();
69            for (i, s) in strings.iter().enumerate().skip(1) {
70                if rest.peek().is_some_and(|r| *r == s) {
71                    kept.push(ptrs[i]);
72                    rest.next();
73                }
74            }
75            for (i, p) in kept.iter().enumerate() {
76                unsafe { *argv.add(i) = *p };
77            }
78            if kept.len() < count {
79                unsafe { *argv.add(kept.len()) = std::ptr::null_mut() };
80            }
81            unsafe { *argc = c_int::try_from(kept.len()).unwrap_or(0) };
82        }
83        let mut default = DEFAULT_ORB.lock().unwrap();
84        if default.is_none() {
85            *default = Some(new_orb.clone());
86        }
87        unsafe { *orb = into_handle(new_orb) };
88        OK
89    })
90}
91
92#[unsafe(no_mangle)]
93pub unsafe extern "C" fn rorb_orb_clone(orb: *mut Orb) -> *mut Orb {
94    into_handle(unsafe { &*orb }.clone())
95}
96
97#[unsafe(no_mangle)]
98pub unsafe extern "C" fn rorb_orb_release(orb: *mut Orb) {
99    unsafe { release_handle(orb) }
100}
101
102/// A nullable object handle for C.
103pub(crate) fn object_handle(obj: Option<ObjectRef>) -> *mut ObjectRef {
104    obj.map_or(std::ptr::null_mut(), into_handle)
105}
106
107#[unsafe(no_mangle)]
108pub unsafe extern "C" fn rorb_orb_string_to_object(
109    orb: *mut Orb,
110    s: *const c_char,
111    len: usize,
112    obj: *mut *mut ObjectRef,
113    exc: *mut Exception,
114) -> Status {
115    guard(exc, || {
116        let orb = unsafe { &*orb };
117        let result = unsafe { str_arg(s, len) }.and_then(|s| orb.string_to_object(s));
118        match result {
119            Ok(o) => {
120                unsafe { *obj = object_handle(o) };
121                OK
122            }
123            Err(e) => unsafe { set_system(exc, &e) },
124        }
125    })
126}
127
128#[unsafe(no_mangle)]
129pub unsafe extern "C" fn rorb_orb_object_to_string(
130    orb: *mut Orb,
131    obj: *mut ObjectRef,
132    s: *mut Bytes,
133    exc: *mut Exception,
134) -> Status {
135    guard(exc, || {
136        let orb = unsafe { &*orb };
137        match orb.object_to_string(unsafe { obj.as_ref() }) {
138            Ok(text) => {
139                unsafe { *s = Bytes::new(text.into_bytes()) };
140                OK
141            }
142            Err(e) => unsafe { set_system(exc, &e) },
143        }
144    })
145}
146
147#[unsafe(no_mangle)]
148pub unsafe extern "C" fn rorb_orb_resolve_initial_references(
149    orb: *mut Orb,
150    name: *const c_char,
151    len: usize,
152    obj: *mut *mut ObjectRef,
153    exc: *mut Exception,
154) -> Status {
155    guard(exc, || {
156        let orb = unsafe { &*orb };
157        let name = match unsafe { str_arg(name, len) } {
158            Ok(n) => n,
159            Err(_) => return unsafe { set_local(exc, local::INVALID_NAME, 0) },
160        };
161        match orb.resolve_initial_references(name) {
162            Ok(o) => {
163                unsafe { *obj = into_handle(o) };
164                OK
165            }
166            Err(ResolveError::InvalidName(_)) => unsafe { set_local(exc, local::INVALID_NAME, 0) },
167            Err(ResolveError::System(e)) => unsafe { set_system(exc, &e) },
168        }
169    })
170}
171
172#[unsafe(no_mangle)]
173pub unsafe extern "C" fn rorb_orb_list_initial_services(
174    orb: *mut Orb,
175    context: *mut c_void,
176    each: extern "C" fn(*mut c_void, *const c_char, usize),
177) {
178    let orb = unsafe { &*orb };
179    for name in orb.list_initial_services() {
180        each(context, name.as_ptr() as *const c_char, name.len());
181    }
182}
183
184#[unsafe(no_mangle)]
185pub unsafe extern "C" fn rorb_orb_root_poa(
186    orb: *mut Orb,
187    poa: *mut *mut Poa,
188    exc: *mut Exception,
189) -> Status {
190    guard(exc, || match unsafe { &*orb }.root_poa() {
191        Ok(p) => {
192            unsafe { *poa = into_handle(p) };
193            OK
194        }
195        Err(e) => unsafe { set_system(exc, &e) },
196    })
197}
198
199#[unsafe(no_mangle)]
200pub unsafe extern "C" fn rorb_default_root_poa(poa: *mut *mut Poa, exc: *mut Exception) -> Status {
201    guard(exc, || {
202        let orb = DEFAULT_ORB.lock().unwrap().clone();
203        let Some(orb) = orb else {
204            return unsafe {
205                set_system(
206                    exc,
207                    &crate::sys(
208                        rustorb_core::SystemExceptionKind::OBJ_ADAPTER,
209                        0,
210                        rustorb_core::CompletionStatus::No,
211                    ),
212                )
213            };
214        };
215        match orb.root_poa() {
216            Ok(p) => {
217                unsafe { *poa = into_handle(p) };
218                OK
219            }
220            Err(e) => unsafe { set_system(exc, &e) },
221        }
222    })
223}
224
225#[unsafe(no_mangle)]
226pub unsafe extern "C" fn rorb_orb_run(orb: *mut Orb) {
227    let orb = unsafe { &*orb };
228    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| orb.run()));
229}
230
231#[unsafe(no_mangle)]
232pub unsafe extern "C" fn rorb_orb_work_pending(
233    orb: *mut Orb,
234    pending: *mut i32,
235    exc: *mut Exception,
236) -> Status {
237    guard(exc, || match unsafe { &*orb }.work_pending() {
238        Ok(p) => {
239            unsafe { *pending = i32::from(p) };
240            OK
241        }
242        Err(e) => unsafe { set_system(exc, &e) },
243    })
244}
245
246#[unsafe(no_mangle)]
247pub unsafe extern "C" fn rorb_orb_perform_work(orb: *mut Orb, exc: *mut Exception) -> Status {
248    guard(exc, || match unsafe { &*orb }.perform_work() {
249        Ok(()) => OK,
250        Err(e) => unsafe { set_system(exc, &e) },
251    })
252}
253
254#[unsafe(no_mangle)]
255pub unsafe extern "C" fn rorb_orb_shutdown(
256    orb: *mut Orb,
257    wait_for_completion: i32,
258    exc: *mut Exception,
259) -> Status {
260    guard(exc, || {
261        match unsafe { &*orb }.shutdown(wait_for_completion != 0) {
262            Ok(()) => OK,
263            Err(e) => unsafe { set_system(exc, &e) },
264        }
265    })
266}
267
268#[unsafe(no_mangle)]
269pub unsafe extern "C" fn rorb_orb_destroy(orb: *mut Orb, exc: *mut Exception) -> Status {
270    guard(exc, || {
271        let orb = unsafe { &*orb };
272        match orb.destroy() {
273            Ok(()) => {
274                let mut default = DEFAULT_ORB.lock().unwrap();
275                if default.as_ref() == Some(orb) {
276                    *default = None;
277                }
278                OK
279            }
280            Err(e) => unsafe { set_system(exc, &e) },
281        }
282    })
283}
284
285/// Microseconds of the C ABI: 0 for no limit, negative clamped to 0.
286pub(crate) fn duration_us(us: i64) -> Option<Duration> {
287    (us > 0).then(|| Duration::from_micros(us.unsigned_abs()))
288}
289
290pub(crate) fn us_of(timeout: Option<Duration>) -> i64 {
291    timeout.map_or(0, |t| {
292        i64::try_from(t.as_micros()).unwrap_or(i64::MAX).max(1)
293    })
294}
295
296/// The three-state setting of a thread or a reference: negative unsets it.
297pub(crate) fn setting_us(us: i64) -> Option<Option<Duration>> {
298    (us >= 0).then(|| duration_us(us))
299}
300
301pub(crate) fn us_of_setting(setting: Option<Option<Duration>>) -> i64 {
302    setting.map_or(-1, us_of)
303}
304
305/// A new handle of the default ORB, or NULL before `rorb_orb_init`.
306#[unsafe(no_mangle)]
307pub extern "C" fn rorb_default_orb() -> *mut Orb {
308    default_orb().map_or(std::ptr::null_mut(), into_handle)
309}
310
311#[unsafe(no_mangle)]
312pub unsafe extern "C" fn rorb_orb_set_call_timeout(orb: *mut Orb, us: i64) {
313    unsafe { &*orb }.set_call_timeout(duration_us(us));
314}
315
316#[unsafe(no_mangle)]
317pub unsafe extern "C" fn rorb_orb_call_timeout(orb: *mut Orb) -> i64 {
318    us_of(unsafe { &*orb }.call_timeout())
319}
320
321#[unsafe(no_mangle)]
322pub unsafe extern "C" fn rorb_orb_set_connect_timeout(orb: *mut Orb, us: i64) {
323    unsafe { &*orb }.set_connect_timeout(duration_us(us));
324}
325
326#[unsafe(no_mangle)]
327pub unsafe extern "C" fn rorb_orb_connect_timeout(orb: *mut Orb) -> i64 {
328    us_of(unsafe { &*orb }.connect_timeout())
329}
330
331#[unsafe(no_mangle)]
332pub extern "C" fn rorb_set_thread_call_timeout(us: i64) {
333    rustorb_core::set_thread_call_timeout(setting_us(us));
334}
335
336#[unsafe(no_mangle)]
337pub extern "C" fn rorb_thread_call_timeout() -> i64 {
338    us_of_setting(rustorb_core::thread_call_timeout())
339}