Skip to main content

rustorb_ffi/
servant.rs

1//! Servants implemented in C (`rorb_servant` is a boxed
2//! `Arc<FfiServant>`) and the replies they write.
3//!
4//! Each servant object of the caller (`self`) has one [`FfiServant`] while
5//! the POA or a handle holds it, found again by `self` in a registry. The
6//! `FfiServant` holds a reference to `self` (`add_ref` when made,
7//! `remove_ref` when dropped); the caller's object only points back
8//! weakly, through the registry, so there is no cycle.
9
10use std::collections::HashMap;
11use std::ffi::{c_char, c_void};
12use std::sync::{Arc, Mutex, Weak};
13
14use rustorb_core::{
15    CompletionStatus, InStream, ObjectRef, PoaCurrent, Servant, ServerReply, SystemException,
16    SystemExceptionKind,
17};
18
19use crate::stream::{In, Out, RorbIn, RorbOut};
20use crate::{OK, SYSTEM_EXCEPTION, Status, completion_status, str_arg, sys};
21
22/// `rorb_servant_vtable`.
23#[repr(C)]
24#[derive(Debug)]
25pub struct ServantVtable {
26    pub dispatch:
27        extern "C" fn(*mut c_void, *const c_char, usize, *mut RorbIn, *mut ReplyFfi) -> Status,
28    pub is_a: extern "C" fn(*mut c_void, *const c_char, usize) -> i32,
29    pub add_ref: extern "C" fn(*mut c_void),
30    pub remove_ref: extern "C" fn(*mut c_void),
31}
32
33/// A servant of the caller, as the POA sees it.
34#[derive(Debug)]
35pub struct FfiServant {
36    this: *mut c_void,
37    vtable: *const ServantVtable,
38    repository_id: String,
39}
40
41// The caller's servants are called from any upcall thread, as the header
42// says.
43unsafe impl Send for FfiServant {}
44unsafe impl Sync for FfiServant {}
45
46#[derive(Default)]
47struct Registry {
48    /// The `FfiServant` of each caller object.
49    by_self: HashMap<usize, Weak<FfiServant>>,
50    /// The caller object of each live `FfiServant`, by its address.
51    by_addr: HashMap<usize, usize>,
52}
53
54static REGISTRY: Mutex<Option<Registry>> = Mutex::new(None);
55
56impl FfiServant {
57    fn vtable(&self) -> &ServantVtable {
58        unsafe { &*self.vtable }
59    }
60}
61
62impl Drop for FfiServant {
63    fn drop(&mut self) {
64        {
65            let mut reg = REGISTRY.lock().unwrap();
66            if let Some(reg) = reg.as_mut() {
67                reg.by_addr.remove(&(self as *const FfiServant as usize));
68                let key = self.this as usize;
69                if reg.by_self.get(&key).is_some_and(|w| w.upgrade().is_none()) {
70                    reg.by_self.remove(&key);
71                }
72            }
73        }
74        // Outside the lock: the caller's object may go now, and release
75        // other servants.
76        (self.vtable().remove_ref)(self.this);
77    }
78}
79
80impl Servant for FfiServant {
81    fn repository_id(&self) -> &str {
82        &self.repository_id
83    }
84
85    fn is_a(&self, repository_id: &str) -> bool {
86        crate::stack::commit();
87        (self.vtable().is_a)(
88            self.this,
89            repository_id.as_ptr() as *const c_char,
90            repository_id.len(),
91        ) != 0
92    }
93
94    fn dispatch(
95        &self,
96        operation: &str,
97        input: &mut InStream<'_>,
98        reply: &mut ServerReply,
99    ) -> Result<(), SystemException> {
100        let mut input = In::new(input, CompletionStatus::No);
101        let mut r = ReplyFfi {
102            out: Out::reply(reply),
103            system: None,
104        };
105        crate::stack::commit();
106        let status = (self.vtable().dispatch)(
107            self.this,
108            operation.as_ptr() as *const c_char,
109            operation.len(),
110            input.as_ptr(),
111            &mut r,
112        );
113        match status {
114            OK => {
115                if let Some(e) = input.error {
116                    return Err(e);
117                }
118                // The operation has run.
119                if let Some(mut e) = r.out.error {
120                    e.completed = CompletionStatus::Yes;
121                    return Err(e);
122                }
123                Ok(())
124            }
125            SYSTEM_EXCEPTION => Err(r.system.unwrap_or_else(unknown)),
126            _ => Err(unknown()),
127        }
128    }
129}
130
131fn unknown() -> SystemException {
132    sys(SystemExceptionKind::UNKNOWN, 0, CompletionStatus::Maybe)
133}
134
135/// `rorb_server_reply`.
136#[derive(Debug)]
137pub struct ReplyFfi {
138    out: Out<'static, 'static>,
139    system: Option<SystemException>,
140}
141
142impl ReplyFfi {
143    /// The core's reply.
144    pub(crate) fn server_reply(&self) -> *mut ServerReply {
145        self.out.server_reply()
146    }
147}
148
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn rorb_servant_get(
151    this: *mut c_void,
152    repository_id: *const c_char,
153    len: usize,
154    vtable: *const ServantVtable,
155) -> *mut Arc<FfiServant> {
156    let repository_id = unsafe { str_arg(repository_id, len) }
157        .unwrap_or_default()
158        .to_owned();
159    let mut reg = REGISTRY.lock().unwrap();
160    let reg = reg.get_or_insert_with(Registry::default);
161    let key = this as usize;
162    if let Some(s) = reg.by_self.get(&key).and_then(Weak::upgrade) {
163        return Box::into_raw(Box::new(s));
164    }
165    let vt = unsafe { &*vtable };
166    (vt.add_ref)(this);
167    let servant = Arc::new(FfiServant {
168        this,
169        vtable,
170        repository_id,
171    });
172    reg.by_self.insert(key, Arc::downgrade(&servant));
173    reg.by_addr.insert(Arc::as_ptr(&servant) as usize, key);
174    Box::into_raw(Box::new(servant))
175}
176
177#[unsafe(no_mangle)]
178pub unsafe extern "C" fn rorb_servant_release(servant: *mut Arc<FfiServant>) {
179    if !servant.is_null() {
180        drop(unsafe { Box::from_raw(servant) });
181    }
182}
183
184/// The servant behind a handle, as the POA takes it.
185pub(crate) unsafe fn servant_arg(servant: *mut Arc<FfiServant>) -> Arc<dyn Servant> {
186    let s: Arc<FfiServant> = Arc::clone(unsafe { &*servant });
187    s
188}
189
190/// The caller's object of a servant from the POA, with a reference added
191/// for the caller; `None` if it is not one of the caller's servants.
192pub(crate) fn caller_object(servant: &Arc<dyn Servant>) -> Option<*mut c_void> {
193    let addr = Arc::as_ptr(servant) as *const () as usize;
194    let reg = REGISTRY.lock().unwrap();
195    reg.as_ref()?.by_addr.get(&addr)?;
196    // `servant` keeps the FfiServant at `addr` alive.
197    let s = unsafe { &*(addr as *const FfiServant) };
198    (s.vtable().add_ref)(s.this);
199    Some(s.this)
200}
201
202/// The caller's object of a servant from the POA, without a reference
203/// added (valid while `servant` lives); NULL if it is not one of the
204/// caller's servants.
205pub(crate) fn caller_self(servant: &Arc<dyn Servant>) -> *mut c_void {
206    let addr = Arc::as_ptr(servant) as *const () as usize;
207    let reg = REGISTRY.lock().unwrap();
208    reg.as_ref()
209        .and_then(|r| r.by_addr.get(&addr))
210        .map_or(std::ptr::null_mut(), |&this| this as *mut c_void)
211}
212
213#[unsafe(no_mangle)]
214pub unsafe extern "C" fn rorb_servant_current_reference(
215    servant: *mut Arc<FfiServant>,
216    obj: *mut *mut ObjectRef,
217) -> i32 {
218    let Ok(current) = PoaCurrent::get_servant() else {
219        return 0;
220    };
221    let mine = Arc::as_ptr(unsafe { &*servant }) as *const ();
222    if Arc::as_ptr(&current) as *const () != mine {
223        return 0;
224    }
225    match PoaCurrent::get_reference() {
226        Ok(r) => {
227            unsafe { *obj = crate::into_handle(r) };
228            1
229        }
230        Err(_) => 0,
231    }
232}
233
234#[unsafe(no_mangle)]
235pub unsafe extern "C" fn rorb_server_reply_output(reply: *mut ReplyFfi) -> *mut RorbOut {
236    unsafe { &mut *reply }.out.as_ptr()
237}
238
239#[unsafe(no_mangle)]
240pub unsafe extern "C" fn rorb_server_reply_user_exception(
241    reply: *mut ReplyFfi,
242    id: *const c_char,
243    len: usize,
244) -> *mut RorbOut {
245    let r = unsafe { &mut *reply };
246    let result = unsafe { str_arg(id, len) }.and_then(|id| {
247        let server_reply = r.out.server_reply();
248        unsafe { &mut *server_reply }.user_exception(id).map(drop)
249    });
250    r.out.error = result.err();
251    r.out.as_ptr()
252}
253
254#[unsafe(no_mangle)]
255pub unsafe extern "C" fn rorb_server_reply_system_exception(
256    reply: *mut ReplyFfi,
257    id: *const c_char,
258    len: usize,
259    minor: u32,
260    completed: u32,
261) {
262    let r = unsafe { &mut *reply };
263    let repository_id = unsafe { str_arg(id, len) }
264        .unwrap_or("IDL:omg.org/CORBA/UNKNOWN:1.0")
265        .to_owned();
266    r.system = Some(SystemException {
267        repository_id,
268        minor,
269        completed: completion_status(completed),
270    });
271}