Skip to main content

rustorb_ffi/
object.rs

1//! Object references (`rorb_object` is a boxed [`ObjectRef`]) and
2//! invocations.
3
4use std::cell::Cell;
5use std::collections::hash_map::DefaultHasher;
6use std::ffi::{c_char, c_void};
7use std::hash::{Hash, Hasher};
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::time::Duration;
11
12use rustorb_core::{
13    CompletionStatus, Exception as CoreException, ObjectRef, Orb, OutStream, SystemException,
14    SystemExceptionKind, minor,
15};
16
17use crate::stream::{In, Out, RorbIn, RorbOut};
18use crate::{
19    CALLBACK_FAILED, Exception, OK, SYSTEM_EXCEPTION, Status, USER_EXCEPTION, guard, into_handle,
20    release_handle, set_system, str_arg, sys,
21};
22
23#[unsafe(no_mangle)]
24pub unsafe extern "C" fn rorb_object_clone(obj: *mut ObjectRef) -> *mut ObjectRef {
25    into_handle(unsafe { &*obj }.clone())
26}
27
28#[unsafe(no_mangle)]
29pub unsafe extern "C" fn rorb_object_release(obj: *mut ObjectRef) {
30    unsafe { release_handle(obj) }
31}
32
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn rorb_object_orb(obj: *mut ObjectRef) -> *mut Orb {
35    into_handle(unsafe { &*obj }.orb().clone())
36}
37
38#[unsafe(no_mangle)]
39pub unsafe extern "C" fn rorb_object_type_id(
40    obj: *mut ObjectRef,
41    len: *mut usize,
42) -> *const c_char {
43    let id = unsafe { &*obj }.type_id();
44    unsafe { *len = id.len() };
45    id.as_ptr() as *const c_char
46}
47
48/// A user exception where the caller expected none is `UNKNOWN`.
49fn unlisted() -> SystemException {
50    sys(
51        SystemExceptionKind::UNKNOWN,
52        minor::UNLISTED_USER_EXCEPTION,
53        CompletionStatus::Yes,
54    )
55}
56
57fn system(e: CoreException) -> SystemException {
58    match e {
59        CoreException::System(e) => e,
60        CoreException::User(_) => unlisted(),
61    }
62}
63
64#[unsafe(no_mangle)]
65pub unsafe extern "C" fn rorb_object_is_a(
66    obj: *mut ObjectRef,
67    id: *const c_char,
68    len: usize,
69    result: *mut i32,
70    exc: *mut Exception,
71) -> Status {
72    guard(exc, || {
73        let obj = unsafe { &*obj };
74        let r = unsafe { str_arg(id, len) }.and_then(|id| obj.is_a(id).map_err(system));
75        match r {
76            Ok(v) => {
77                unsafe { *result = i32::from(v) };
78                OK
79            }
80            Err(e) => unsafe { set_system(exc, &e) },
81        }
82    })
83}
84
85#[unsafe(no_mangle)]
86pub unsafe extern "C" fn rorb_object_non_existent(
87    obj: *mut ObjectRef,
88    result: *mut i32,
89    exc: *mut Exception,
90) -> Status {
91    guard(exc, || match unsafe { &*obj }.non_existent() {
92        Ok(v) => {
93            unsafe { *result = i32::from(v) };
94            OK
95        }
96        Err(e) => unsafe { set_system(exc, &system(e)) },
97    })
98}
99
100#[unsafe(no_mangle)]
101pub unsafe extern "C" fn rorb_object_is_equivalent(a: *mut ObjectRef, b: *mut ObjectRef) -> i32 {
102    match (unsafe { a.as_ref() }, unsafe { b.as_ref() }) {
103        (Some(a), Some(b)) => i32::from(a.is_equivalent(b)),
104        (None, None) => 1,
105        _ => 0,
106    }
107}
108
109#[unsafe(no_mangle)]
110pub unsafe extern "C" fn rorb_object_hash(obj: *mut ObjectRef, maximum: u32) -> u32 {
111    let mut h = DefaultHasher::new();
112    for p in &unsafe { &*obj }.ior().profiles {
113        p.tag.hash(&mut h);
114        p.profile_data.hash(&mut h);
115    }
116    let maximum = u64::from(maximum).max(1);
117    u32::try_from(h.finish() % maximum).unwrap_or(0)
118}
119
120#[unsafe(no_mangle)]
121pub unsafe extern "C" fn rorb_object_set_call_timeout(obj: *mut ObjectRef, us: i64) {
122    unsafe { &*obj }.set_call_timeout(crate::orb::setting_us(us));
123}
124
125#[unsafe(no_mangle)]
126pub unsafe extern "C" fn rorb_object_call_timeout(obj: *mut ObjectRef) -> i64 {
127    crate::orb::us_of_setting(unsafe { &*obj }.call_timeout())
128}
129
130type WriteFn = extern "C" fn(*mut c_void, *mut RorbOut) -> Status;
131type ReadFn = extern "C" fn(*mut c_void, *mut RorbIn) -> Status;
132type UserExceptionFn = extern "C" fn(*mut c_void, *const c_char, usize, *mut RorbIn) -> Status;
133
134/// `rorb_invocation`.
135#[repr(C)]
136#[derive(Debug, Clone, Copy)]
137pub struct Invocation {
138    pub operation: *const c_char,
139    pub operation_len: usize,
140    pub oneway: i32,
141    pub timeout_us: i64,
142    pub context: *mut c_void,
143    pub write_args: Option<WriteFn>,
144    pub read_reply: Option<ReadFn>,
145    pub read_user_exception: Option<UserExceptionFn>,
146}
147
148/// What [`send`] got back.
149pub(crate) enum Sent {
150    Oneway,
151    Reply(rustorb_core::Reply),
152    User(rustorb_core::UserException),
153}
154
155/// Sends the request of `inv`, its arguments written by `write_args`.
156/// `Err` is the status to return: a system exception (set in `exc`), or
157/// `CALLBACK_FAILED` when the callback failed.
158pub(crate) unsafe fn send(
159    obj: &ObjectRef,
160    inv: &Invocation,
161    exc: *mut Exception,
162) -> Result<Sent, Status> {
163    let operation = match unsafe { str_arg(inv.operation, inv.operation_len) } {
164        Ok(op) => op,
165        Err(e) => return Err(unsafe { set_system(exc, &e) }),
166    };
167    // Set when a callback failed, so that its placeholder exception is
168    // not reported.
169    let failed = Cell::new(false);
170    let write = |out: &mut OutStream<'_>| -> Result<(), SystemException> {
171        let Some(write_args) = inv.write_args else {
172            return Ok(());
173        };
174        let mut o = Out::new(out);
175        crate::stack::commit();
176        if write_args(inv.context, o.as_ptr()) != OK {
177            failed.set(true);
178            return Err(sys(SystemExceptionKind::UNKNOWN, 0, CompletionStatus::No));
179        }
180        match o.error {
181            Some(e) => Err(e),
182            None => Ok(()),
183        }
184    };
185    let mut request = obj.request(operation).args(write);
186    if inv.timeout_us >= 0 {
187        let timeout = u64::try_from(inv.timeout_us).unwrap_or(0);
188        request = request.timeout((timeout > 0).then(|| Duration::from_micros(timeout)));
189    }
190    if inv.oneway != 0 {
191        return match request.send_oneway() {
192            Ok(()) => Ok(Sent::Oneway),
193            Err(_) if failed.get() => Err(CALLBACK_FAILED),
194            Err(e) => Err(unsafe { set_system(exc, &e) }),
195        };
196    }
197    match request.invoke() {
198        Ok(reply) => Ok(Sent::Reply(reply)),
199        Err(CoreException::System(_)) if failed.get() => Err(CALLBACK_FAILED),
200        Err(CoreException::System(e)) => Err(unsafe { set_system(exc, &e) }),
201        Err(CoreException::User(u)) => Ok(Sent::User(u)),
202    }
203}
204
205#[unsafe(no_mangle)]
206pub unsafe extern "C" fn rorb_object_invoke(
207    obj: *mut ObjectRef,
208    inv: *const Invocation,
209    exc: *mut Exception,
210) -> Status {
211    guard(exc, || {
212        let obj = unsafe { &*obj };
213        let inv = unsafe { &*inv };
214        let sent = match unsafe { send(obj, inv, exc) } {
215            Ok(sent) => sent,
216            Err(status) => return status,
217        };
218        unsafe { read_sent(inv, sent, exc) }
219    })
220}
221
222/// Hands what an invocation got back to the read callbacks of `inv`.
223unsafe fn read_sent(inv: &Invocation, sent: Sent, exc: *mut Exception) -> Status {
224    match sent {
225        Sent::Oneway => OK,
226        Sent::Reply(reply) => {
227            let Some(read_reply) = inv.read_reply else {
228                return OK;
229            };
230            let mut stream = reply.input();
231            let mut input = In::new(&mut stream, CompletionStatus::Yes);
232            crate::stack::commit();
233            if read_reply(inv.context, input.as_ptr()) != OK {
234                return CALLBACK_FAILED;
235            }
236            match input.error {
237                Some(e) => unsafe { set_system(exc, &e) },
238                None => OK,
239            }
240        }
241        Sent::User(u) => {
242            let Some(read_user_exception) = inv.read_user_exception else {
243                return unsafe { set_system(exc, &unlisted()) };
244            };
245            let mut stream = match u.input() {
246                Ok(s) => s,
247                Err(e) => return unsafe { set_system(exc, &e) },
248            };
249            let id = u.repository_id();
250            let mut input = In::new(&mut stream, CompletionStatus::Yes);
251            crate::stack::commit();
252            match read_user_exception(
253                inv.context,
254                id.as_ptr() as *const c_char,
255                id.len(),
256                input.as_ptr(),
257            ) {
258                USER_EXCEPTION => match input.error {
259                    Some(e) => unsafe { set_system(exc, &e) },
260                    None => USER_EXCEPTION,
261                },
262                SYSTEM_EXCEPTION => unsafe { set_system(exc, &unlisted()) },
263                _ => CALLBACK_FAILED,
264            }
265        }
266    }
267}
268
269/// `rorb_sendc_done_fn`.
270type DoneFn = extern "C" fn(*mut c_void, Status, *const Exception);
271
272/// An invocation of [`rorb_object_sendc`], used on other threads until its
273/// `done` has been called.
274struct Pending(Invocation);
275
276// SAFETY: the caller of rorb_object_sendc makes the context and the
277// callbacks usable from any thread until `done` is called.
278unsafe impl Send for Pending {}
279unsafe impl Sync for Pending {}
280
281/// A pointer handed to the thread that runs a callback (crate::offload).
282struct SendPtr<T>(*mut T);
283
284// SAFETY: used by one thread at a time, while its owner waits.
285unsafe impl<T> Send for SendPtr<T> {}
286
287#[unsafe(no_mangle)]
288pub unsafe extern "C" fn rorb_object_sendc(
289    obj: *mut ObjectRef,
290    inv: *const Invocation,
291    done: Option<DoneFn>,
292    exc: *mut Exception,
293) -> Status {
294    guard(exc, || {
295        let obj = unsafe { &*obj };
296        let inv = unsafe { *inv };
297        let Some(done) = done else {
298            return unsafe { set_system(exc, &crate::bad_param()) };
299        };
300        if inv.oneway != 0 {
301            return unsafe { set_system(exc, &crate::bad_param()) };
302        }
303        let operation = match unsafe { str_arg(inv.operation, inv.operation_len) } {
304            Ok(op) => op.to_owned(),
305            Err(e) => return unsafe { set_system(exc, &e) },
306        };
307        // The operation name is copied: its pointer is not kept.
308        let pending = Arc::new(Pending(Invocation {
309            operation: std::ptr::null(),
310            operation_len: 0,
311            ..inv
312        }));
313        // Set when write_args failed.
314        let failed = Arc::new(AtomicBool::new(false));
315        let mut request = obj.request_callback(&operation);
316        if let Some(write_args) = inv.write_args {
317            let pending = Arc::clone(&pending);
318            let failed = Arc::clone(&failed);
319            request = request.args(move |out: &mut OutStream<'_>| {
320                // Written on a thread of the runtime: the caller's callback
321                // runs elsewhere (crate::offload).
322                let out = SendPtr(out as *mut OutStream<'_>);
323                let pending = &pending;
324                let failed = &failed;
325                crate::offload::run(move || {
326                    let out = out;
327                    // SAFETY: the stream outlives this call, which run
328                    // waits for, and nothing else uses it meanwhile.
329                    let mut o = Out::new(unsafe { &mut *out.0 });
330                    crate::stack::commit();
331                    if write_args(pending.0.context, o.as_ptr()) != OK {
332                        failed.store(true, Ordering::Relaxed);
333                        return Err(sys(SystemExceptionKind::UNKNOWN, 0, CompletionStatus::No));
334                    }
335                    match o.error {
336                        Some(e) => Err(e),
337                        None => Ok(()),
338                    }
339                })
340            });
341        }
342        if inv.timeout_us >= 0 {
343            let timeout = u64::try_from(inv.timeout_us).unwrap_or(0);
344            request = request.timeout((timeout > 0).then(|| Duration::from_micros(timeout)));
345        }
346        let sent = request.send(move |result| {
347            let inv = &pending.0;
348            let mut e = crate::Exception::empty();
349            let status = match result {
350                Err(CoreException::System(_)) if failed.load(Ordering::Relaxed) => CALLBACK_FAILED,
351                Err(CoreException::System(s)) => unsafe { set_system(&mut e, &s) },
352                Ok(reply) => unsafe { read_sent(inv, Sent::Reply(reply), &mut e) },
353                Err(CoreException::User(u)) => unsafe { read_sent(inv, Sent::User(u), &mut e) },
354            };
355            crate::stack::commit();
356            done(inv.context, status, &e);
357            unsafe { crate::rorb_exception_clear(&mut e) };
358        });
359        match sent {
360            Ok(()) => OK,
361            Err(e) => unsafe { set_system(exc, &e) },
362        }
363    })
364}