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        (self.vtable().is_a)(
87            self.this,
88            repository_id.as_ptr() as *const c_char,
89            repository_id.len(),
90        ) != 0
91    }
92
93    fn dispatch(
94        &self,
95        operation: &str,
96        input: &mut InStream<'_>,
97        reply: &mut ServerReply,
98    ) -> Result<(), SystemException> {
99        let mut input = In::new(input, CompletionStatus::No);
100        let mut r = ReplyFfi {
101            out: Out::reply(reply),
102            system: None,
103        };
104        let status = (self.vtable().dispatch)(
105            self.this,
106            operation.as_ptr() as *const c_char,
107            operation.len(),
108            input.as_ptr(),
109            &mut r,
110        );
111        match status {
112            OK => {
113                if let Some(e) = input.error {
114                    return Err(e);
115                }
116                // The operation has run.
117                if let Some(mut e) = r.out.error {
118                    e.completed = CompletionStatus::Yes;
119                    return Err(e);
120                }
121                Ok(())
122            }
123            SYSTEM_EXCEPTION => Err(r.system.unwrap_or_else(unknown)),
124            _ => Err(unknown()),
125        }
126    }
127}
128
129fn unknown() -> SystemException {
130    sys(SystemExceptionKind::UNKNOWN, 0, CompletionStatus::Maybe)
131}
132
133/// `rorb_server_reply`.
134#[derive(Debug)]
135pub struct ReplyFfi {
136    out: Out<'static, 'static>,
137    system: Option<SystemException>,
138}
139
140#[unsafe(no_mangle)]
141pub unsafe extern "C" fn rorb_servant_get(
142    this: *mut c_void,
143    repository_id: *const c_char,
144    len: usize,
145    vtable: *const ServantVtable,
146) -> *mut Arc<FfiServant> {
147    let repository_id = unsafe { str_arg(repository_id, len) }
148        .unwrap_or_default()
149        .to_owned();
150    let mut reg = REGISTRY.lock().unwrap();
151    let reg = reg.get_or_insert_with(Registry::default);
152    let key = this as usize;
153    if let Some(s) = reg.by_self.get(&key).and_then(Weak::upgrade) {
154        return Box::into_raw(Box::new(s));
155    }
156    let vt = unsafe { &*vtable };
157    (vt.add_ref)(this);
158    let servant = Arc::new(FfiServant {
159        this,
160        vtable,
161        repository_id,
162    });
163    reg.by_self.insert(key, Arc::downgrade(&servant));
164    reg.by_addr.insert(Arc::as_ptr(&servant) as usize, key);
165    Box::into_raw(Box::new(servant))
166}
167
168#[unsafe(no_mangle)]
169pub unsafe extern "C" fn rorb_servant_release(servant: *mut Arc<FfiServant>) {
170    if !servant.is_null() {
171        drop(unsafe { Box::from_raw(servant) });
172    }
173}
174
175/// The servant behind a handle, as the POA takes it.
176pub(crate) unsafe fn servant_arg(servant: *mut Arc<FfiServant>) -> Arc<dyn Servant> {
177    let s: Arc<FfiServant> = Arc::clone(unsafe { &*servant });
178    s
179}
180
181/// The caller's object of a servant from the POA, with a reference added
182/// for the caller; `None` if it is not one of the caller's servants.
183pub(crate) fn caller_object(servant: &Arc<dyn Servant>) -> Option<*mut c_void> {
184    let addr = Arc::as_ptr(servant) as *const () as usize;
185    let reg = REGISTRY.lock().unwrap();
186    reg.as_ref()?.by_addr.get(&addr)?;
187    // `servant` keeps the FfiServant at `addr` alive.
188    let s = unsafe { &*(addr as *const FfiServant) };
189    (s.vtable().add_ref)(s.this);
190    Some(s.this)
191}
192
193/// The caller's object of a servant from the POA, without a reference
194/// added (valid while `servant` lives); NULL if it is not one of the
195/// caller's servants.
196pub(crate) fn caller_self(servant: &Arc<dyn Servant>) -> *mut c_void {
197    let addr = Arc::as_ptr(servant) as *const () as usize;
198    let reg = REGISTRY.lock().unwrap();
199    reg.as_ref()
200        .and_then(|r| r.by_addr.get(&addr))
201        .map_or(std::ptr::null_mut(), |&this| this as *mut c_void)
202}
203
204#[unsafe(no_mangle)]
205pub unsafe extern "C" fn rorb_servant_current_reference(
206    servant: *mut Arc<FfiServant>,
207    obj: *mut *mut ObjectRef,
208) -> i32 {
209    let Ok(current) = PoaCurrent::get_servant() else {
210        return 0;
211    };
212    let mine = Arc::as_ptr(unsafe { &*servant }) as *const ();
213    if Arc::as_ptr(&current) as *const () != mine {
214        return 0;
215    }
216    match PoaCurrent::get_reference() {
217        Ok(r) => {
218            unsafe { *obj = crate::into_handle(r) };
219            1
220        }
221        Err(_) => 0,
222    }
223}
224
225#[unsafe(no_mangle)]
226pub unsafe extern "C" fn rorb_server_reply_output(reply: *mut ReplyFfi) -> *mut RorbOut {
227    unsafe { &mut *reply }.out.as_ptr()
228}
229
230#[unsafe(no_mangle)]
231pub unsafe extern "C" fn rorb_server_reply_user_exception(
232    reply: *mut ReplyFfi,
233    id: *const c_char,
234    len: usize,
235) -> *mut RorbOut {
236    let r = unsafe { &mut *reply };
237    let result = unsafe { str_arg(id, len) }.and_then(|id| {
238        let server_reply = r.out.server_reply();
239        unsafe { &mut *server_reply }.user_exception(id).map(drop)
240    });
241    r.out.error = result.err();
242    r.out.as_ptr()
243}
244
245#[unsafe(no_mangle)]
246pub unsafe extern "C" fn rorb_server_reply_system_exception(
247    reply: *mut ReplyFfi,
248    id: *const c_char,
249    len: usize,
250    minor: u32,
251    completed: u32,
252) {
253    let r = unsafe { &mut *reply };
254    let repository_id = unsafe { str_arg(id, len) }
255        .unwrap_or("IDL:omg.org/CORBA/UNKNOWN:1.0")
256        .to_owned();
257    r.system = Some(SystemException {
258        repository_id,
259        minor,
260        completed: completion_status(completed),
261    });
262}