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
142#[unsafe(no_mangle)]
143pub unsafe extern "C" fn rorb_servant_get(
144    this: *mut c_void,
145    repository_id: *const c_char,
146    len: usize,
147    vtable: *const ServantVtable,
148) -> *mut Arc<FfiServant> {
149    let repository_id = unsafe { str_arg(repository_id, len) }
150        .unwrap_or_default()
151        .to_owned();
152    let mut reg = REGISTRY.lock().unwrap();
153    let reg = reg.get_or_insert_with(Registry::default);
154    let key = this as usize;
155    if let Some(s) = reg.by_self.get(&key).and_then(Weak::upgrade) {
156        return Box::into_raw(Box::new(s));
157    }
158    let vt = unsafe { &*vtable };
159    (vt.add_ref)(this);
160    let servant = Arc::new(FfiServant {
161        this,
162        vtable,
163        repository_id,
164    });
165    reg.by_self.insert(key, Arc::downgrade(&servant));
166    reg.by_addr.insert(Arc::as_ptr(&servant) as usize, key);
167    Box::into_raw(Box::new(servant))
168}
169
170#[unsafe(no_mangle)]
171pub unsafe extern "C" fn rorb_servant_release(servant: *mut Arc<FfiServant>) {
172    if !servant.is_null() {
173        drop(unsafe { Box::from_raw(servant) });
174    }
175}
176
177/// The servant behind a handle, as the POA takes it.
178pub(crate) unsafe fn servant_arg(servant: *mut Arc<FfiServant>) -> Arc<dyn Servant> {
179    let s: Arc<FfiServant> = Arc::clone(unsafe { &*servant });
180    s
181}
182
183/// The caller's object of a servant from the POA, with a reference added
184/// for the caller; `None` if it is not one of the caller's servants.
185pub(crate) fn caller_object(servant: &Arc<dyn Servant>) -> Option<*mut c_void> {
186    let addr = Arc::as_ptr(servant) as *const () as usize;
187    let reg = REGISTRY.lock().unwrap();
188    reg.as_ref()?.by_addr.get(&addr)?;
189    // `servant` keeps the FfiServant at `addr` alive.
190    let s = unsafe { &*(addr as *const FfiServant) };
191    (s.vtable().add_ref)(s.this);
192    Some(s.this)
193}
194
195/// The caller's object of a servant from the POA, without a reference
196/// added (valid while `servant` lives); NULL if it is not one of the
197/// caller's servants.
198pub(crate) fn caller_self(servant: &Arc<dyn Servant>) -> *mut c_void {
199    let addr = Arc::as_ptr(servant) as *const () as usize;
200    let reg = REGISTRY.lock().unwrap();
201    reg.as_ref()
202        .and_then(|r| r.by_addr.get(&addr))
203        .map_or(std::ptr::null_mut(), |&this| this as *mut c_void)
204}
205
206#[unsafe(no_mangle)]
207pub unsafe extern "C" fn rorb_servant_current_reference(
208    servant: *mut Arc<FfiServant>,
209    obj: *mut *mut ObjectRef,
210) -> i32 {
211    let Ok(current) = PoaCurrent::get_servant() else {
212        return 0;
213    };
214    let mine = Arc::as_ptr(unsafe { &*servant }) as *const ();
215    if Arc::as_ptr(&current) as *const () != mine {
216        return 0;
217    }
218    match PoaCurrent::get_reference() {
219        Ok(r) => {
220            unsafe { *obj = crate::into_handle(r) };
221            1
222        }
223        Err(_) => 0,
224    }
225}
226
227#[unsafe(no_mangle)]
228pub unsafe extern "C" fn rorb_server_reply_output(reply: *mut ReplyFfi) -> *mut RorbOut {
229    unsafe { &mut *reply }.out.as_ptr()
230}
231
232#[unsafe(no_mangle)]
233pub unsafe extern "C" fn rorb_server_reply_user_exception(
234    reply: *mut ReplyFfi,
235    id: *const c_char,
236    len: usize,
237) -> *mut RorbOut {
238    let r = unsafe { &mut *reply };
239    let result = unsafe { str_arg(id, len) }.and_then(|id| {
240        let server_reply = r.out.server_reply();
241        unsafe { &mut *server_reply }.user_exception(id).map(drop)
242    });
243    r.out.error = result.err();
244    r.out.as_ptr()
245}
246
247#[unsafe(no_mangle)]
248pub unsafe extern "C" fn rorb_server_reply_system_exception(
249    reply: *mut ReplyFfi,
250    id: *const c_char,
251    len: usize,
252    minor: u32,
253    completed: u32,
254) {
255    let r = unsafe { &mut *reply };
256    let repository_id = unsafe { str_arg(id, len) }
257        .unwrap_or("IDL:omg.org/CORBA/UNKNOWN:1.0")
258        .to_owned();
259    r.system = Some(SystemException {
260        repository_id,
261        minor,
262        completed: completion_status(completed),
263    });
264}