Skip to main content

rustorb_ffi/
manager.rs

1//! Servant managers (`ServantActivator`, `ServantLocator`) and adapter
2//! activators implemented by the caller through a table of callbacks.
3//!
4//! Like servants, each one holds a reference to the caller's object
5//! (`add_ref` when the POA takes it, `remove_ref` when the POA lets it go).
6//! The objects the POA holds are remembered by address, so that
7//! `get_servant_manager` and `the_activator` give back the caller's object.
8
9use std::collections::HashMap;
10use std::ffi::{c_char, c_void};
11use std::sync::{Arc, Mutex};
12
13use rustorb_core::{
14    AdapterActivator, CompletionStatus, Cookie, ObjectRef, Poa, Servant, ServantActivator,
15    ServantLocator, ServantManager, ServantManagerError, SystemException, SystemExceptionKind,
16};
17
18use crate::poa::poa_call;
19use crate::servant::{FfiServant, caller_self};
20use crate::{Exception, OK, Status, completion_status, into_handle, release_handle, str_arg, sys};
21
22/// `rorb_servant_activator_vtable`.
23#[repr(C)]
24#[derive(Debug)]
25pub struct ActivatorVtable {
26    pub incarnate: extern "C" fn(
27        *mut c_void,
28        *const u8,
29        usize,
30        *mut Poa,
31        *mut *mut Arc<FfiServant>,
32        *mut ManagerError,
33    ) -> Status,
34    pub etherealize:
35        Option<extern "C" fn(*mut c_void, *const u8, usize, *mut Poa, *mut c_void, i32, i32)>,
36    pub add_ref: extern "C" fn(*mut c_void),
37    pub remove_ref: extern "C" fn(*mut c_void),
38}
39
40/// `rorb_servant_locator_vtable`.
41#[repr(C)]
42#[derive(Debug)]
43pub struct LocatorVtable {
44    #[allow(clippy::type_complexity)]
45    pub preinvoke: extern "C" fn(
46        *mut c_void,
47        *const u8,
48        usize,
49        *mut Poa,
50        *const c_char,
51        usize,
52        *mut *mut Arc<FfiServant>,
53        *mut *mut c_void,
54        *mut ManagerError,
55    ) -> Status,
56    #[allow(clippy::type_complexity)]
57    pub postinvoke: Option<
58        extern "C" fn(
59            *mut c_void,
60            *const u8,
61            usize,
62            *mut Poa,
63            *const c_char,
64            usize,
65            *mut c_void,
66            *mut c_void,
67        ),
68    >,
69    pub add_ref: extern "C" fn(*mut c_void),
70    pub remove_ref: extern "C" fn(*mut c_void),
71}
72
73/// `rorb_adapter_activator_vtable`.
74#[repr(C)]
75#[derive(Debug)]
76pub struct AdapterActivatorVtable {
77    pub unknown_adapter: extern "C" fn(*mut c_void, *mut Poa, *const c_char, usize) -> i32,
78    pub add_ref: extern "C" fn(*mut c_void),
79    pub remove_ref: extern "C" fn(*mut c_void),
80}
81
82/// `rorb_manager_error`: what `incarnate` or `preinvoke` raised.
83#[derive(Debug, Default)]
84pub struct ManagerError(Option<ServantManagerError>);
85
86/// `RORB_SERVANT_ACTIVATOR` and `RORB_SERVANT_LOCATOR`.
87const ACTIVATOR: i32 = 1;
88const LOCATOR: i32 = 2;
89
90/// The caller's object of each live manager, by the address of its Rust
91/// side.
92static LIVE: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
93
94fn register(addr: usize, this: *mut c_void) {
95    LIVE.lock()
96        .unwrap()
97        .get_or_insert_with(HashMap::new)
98        .insert(addr, this as usize);
99}
100
101fn unregister(addr: usize) {
102    if let Some(live) = LIVE.lock().unwrap().as_mut() {
103        live.remove(&addr);
104    }
105}
106
107fn caller_of<T: ?Sized>(manager: &Arc<T>) -> Option<*mut c_void> {
108    let addr = Arc::as_ptr(manager) as *const () as usize;
109    let live = LIVE.lock().unwrap();
110    live.as_ref()?.get(&addr).map(|&p| p as *mut c_void)
111}
112
113/// The reference counting callbacks every table has.
114trait Refs {
115    fn add_ref(&self) -> extern "C" fn(*mut c_void);
116    fn remove_ref(&self) -> extern "C" fn(*mut c_void);
117}
118
119macro_rules! refs {
120    ($($vt:ty),*) => {$(
121        impl Refs for $vt {
122            fn add_ref(&self) -> extern "C" fn(*mut c_void) {
123                self.add_ref
124            }
125            fn remove_ref(&self) -> extern "C" fn(*mut c_void) {
126                self.remove_ref
127            }
128        }
129    )*};
130}
131
132refs!(ActivatorVtable, LocatorVtable, AdapterActivatorVtable);
133
134/// One of the caller's objects with its callbacks.
135struct Caller<V: Refs> {
136    this: *mut c_void,
137    vtable: *const V,
138}
139
140// The caller's managers are called from any upcall thread, as the header
141// says.
142unsafe impl<V: Refs> Send for Caller<V> {}
143unsafe impl<V: Refs> Sync for Caller<V> {}
144
145impl<V: Refs> Caller<V> {
146    fn new(this: *mut c_void, vtable: *const V) -> Arc<Self> {
147        (unsafe { &*vtable }.add_ref())(this);
148        let c = Arc::new(Caller { this, vtable });
149        register(Arc::as_ptr(&c) as usize, this);
150        c
151    }
152
153    fn vtable(&self) -> &V {
154        unsafe { &*self.vtable }
155    }
156
157    /// The caller's object with a reference added for the caller.
158    fn get(&self) -> *mut c_void {
159        (self.vtable().add_ref())(self.this);
160        self.this
161    }
162}
163
164impl<V: Refs> Drop for Caller<V> {
165    fn drop(&mut self) {
166        unregister(self as *const Self as usize);
167        (self.vtable().remove_ref())(self.this);
168    }
169}
170
171/// A handle of `adapter` for the duration of a callback.
172struct Borrowed(*mut Poa);
173
174impl Borrowed {
175    fn new(adapter: &Poa) -> Borrowed {
176        Borrowed(into_handle(adapter.clone()))
177    }
178}
179
180impl Drop for Borrowed {
181    fn drop(&mut self) {
182        unsafe { release_handle(self.0) };
183    }
184}
185
186/// The servant a callback gave (one handle reference), or the error it
187/// raised.
188fn provided(
189    status: Status,
190    servant: *mut Arc<FfiServant>,
191    error: ManagerError,
192) -> Result<Arc<dyn Servant>, ServantManagerError> {
193    let servant = (!servant.is_null()).then(|| *unsafe { Box::from_raw(servant) });
194    if status != OK {
195        return Err(error.0.unwrap_or_else(|| {
196            ServantManagerError::System(sys(
197                SystemExceptionKind::UNKNOWN,
198                0,
199                CompletionStatus::Maybe,
200            ))
201        }));
202    }
203    match servant {
204        Some(s) => Ok(s),
205        None => Err(ServantManagerError::System(sys(
206            SystemExceptionKind::OBJ_ADAPTER,
207            0,
208            CompletionStatus::No,
209        ))),
210    }
211}
212
213impl ServantActivator for Caller<ActivatorVtable> {
214    fn incarnate(&self, id: &[u8], adapter: &Poa) -> Result<Arc<dyn Servant>, ServantManagerError> {
215        let poa = Borrowed::new(adapter);
216        let mut servant = std::ptr::null_mut();
217        let mut error = ManagerError::default();
218        let status = (self.vtable().incarnate)(
219            self.this,
220            id.as_ptr(),
221            id.len(),
222            poa.0,
223            &mut servant,
224            &mut error,
225        );
226        provided(status, servant, error)
227    }
228
229    fn etherealize(
230        &self,
231        id: &[u8],
232        adapter: &Poa,
233        servant: Arc<dyn Servant>,
234        cleanup_in_progress: bool,
235        remaining_activations: bool,
236    ) {
237        let Some(etherealize) = self.vtable().etherealize else {
238            return;
239        };
240        let poa = Borrowed::new(adapter);
241        etherealize(
242            self.this,
243            id.as_ptr(),
244            id.len(),
245            poa.0,
246            caller_self(&servant),
247            i32::from(cleanup_in_progress),
248            i32::from(remaining_activations),
249        );
250        // The POA's reference to the servant goes after the callback.
251        drop(servant);
252    }
253}
254
255/// The caller's cookie.
256struct CookiePtr(*mut c_void);
257
258unsafe impl Send for CookiePtr {}
259
260impl ServantLocator for Caller<LocatorVtable> {
261    fn preinvoke(
262        &self,
263        id: &[u8],
264        adapter: &Poa,
265        operation: &str,
266    ) -> Result<(Arc<dyn Servant>, Cookie), ServantManagerError> {
267        let poa = Borrowed::new(adapter);
268        let mut servant = std::ptr::null_mut();
269        let mut cookie = std::ptr::null_mut();
270        let mut error = ManagerError::default();
271        let status = (self.vtable().preinvoke)(
272            self.this,
273            id.as_ptr(),
274            id.len(),
275            poa.0,
276            operation.as_ptr() as *const c_char,
277            operation.len(),
278            &mut servant,
279            &mut cookie,
280            &mut error,
281        );
282        let servant = provided(status, servant, error)?;
283        Ok((servant, Box::new(CookiePtr(cookie))))
284    }
285
286    fn postinvoke(
287        &self,
288        id: &[u8],
289        adapter: &Poa,
290        operation: &str,
291        cookie: Cookie,
292        servant: Arc<dyn Servant>,
293    ) {
294        let Some(postinvoke) = self.vtable().postinvoke else {
295            return;
296        };
297        let cookie = cookie
298            .downcast::<CookiePtr>()
299            .map_or(std::ptr::null_mut(), |c| c.0);
300        let poa = Borrowed::new(adapter);
301        postinvoke(
302            self.this,
303            id.as_ptr(),
304            id.len(),
305            poa.0,
306            operation.as_ptr() as *const c_char,
307            operation.len(),
308            cookie,
309            caller_self(&servant),
310        );
311        drop(servant);
312    }
313}
314
315impl AdapterActivator for Caller<AdapterActivatorVtable> {
316    fn unknown_adapter(&self, parent: &Poa, name: &str) -> bool {
317        let poa = Borrowed::new(parent);
318        (self.vtable().unknown_adapter)(
319            self.this,
320            poa.0,
321            name.as_ptr() as *const c_char,
322            name.len(),
323        ) != 0
324    }
325}
326
327#[unsafe(no_mangle)]
328pub unsafe extern "C" fn rorb_manager_error_forward(error: *mut ManagerError, obj: *mut ObjectRef) {
329    let error = unsafe { &mut *error };
330    error.0 = Some(match unsafe { obj.as_ref() } {
331        Some(obj) => ServantManagerError::ForwardRequest(obj.clone()),
332        // A nil forward reference.
333        None => ServantManagerError::System(sys(
334            SystemExceptionKind::BAD_PARAM,
335            0,
336            CompletionStatus::No,
337        )),
338    });
339}
340
341#[unsafe(no_mangle)]
342pub unsafe extern "C" fn rorb_manager_error_system(
343    error: *mut ManagerError,
344    id: *const c_char,
345    len: usize,
346    minor: u32,
347    completed: u32,
348) {
349    let repository_id = unsafe { str_arg(id, len) }
350        .unwrap_or("IDL:omg.org/CORBA/UNKNOWN:1.0")
351        .to_owned();
352    unsafe { &mut *error }.0 = Some(ServantManagerError::System(SystemException {
353        repository_id,
354        minor,
355        completed: completion_status(completed),
356    }));
357}
358
359#[unsafe(no_mangle)]
360pub unsafe extern "C" fn rorb_poa_set_servant_activator(
361    poa: *mut Poa,
362    this: *mut c_void,
363    vtable: *const ActivatorVtable,
364    exc: *mut Exception,
365) -> Status {
366    poa_call(
367        exc,
368        || {
369            let manager = Caller::<ActivatorVtable>::new(this, vtable);
370            unsafe { &*poa }.set_servant_manager(ServantManager::Activator(manager))
371        },
372        |()| {},
373    )
374}
375
376#[unsafe(no_mangle)]
377pub unsafe extern "C" fn rorb_poa_set_servant_locator(
378    poa: *mut Poa,
379    this: *mut c_void,
380    vtable: *const LocatorVtable,
381    exc: *mut Exception,
382) -> Status {
383    poa_call(
384        exc,
385        || {
386            let manager = Caller::<LocatorVtable>::new(this, vtable);
387            unsafe { &*poa }.set_servant_manager(ServantManager::Locator(manager))
388        },
389        |()| {},
390    )
391}
392
393/// The caller's object of a manager the POA holds, with a reference added
394/// for the caller, or NULL for none or one of another kind.
395fn manager_object(manager: &ServantManager) -> (i32, *mut c_void) {
396    match manager {
397        ServantManager::Activator(a) => (
398            ACTIVATOR,
399            caller_of(a).map_or(std::ptr::null_mut(), |_| {
400                // Registered, so `a` is one of ours.
401                let c =
402                    unsafe { &*(Arc::as_ptr(a) as *const () as *const Caller<ActivatorVtable>) };
403                c.get()
404            }),
405        ),
406        ServantManager::Locator(l) => (
407            LOCATOR,
408            caller_of(l).map_or(std::ptr::null_mut(), |_| {
409                let c = unsafe { &*(Arc::as_ptr(l) as *const () as *const Caller<LocatorVtable>) };
410                c.get()
411            }),
412        ),
413    }
414}
415
416#[unsafe(no_mangle)]
417pub unsafe extern "C" fn rorb_poa_get_servant_manager(
418    poa: *mut Poa,
419    kind: *mut i32,
420    this: *mut *mut c_void,
421    exc: *mut Exception,
422) -> Status {
423    poa_call(
424        exc,
425        || unsafe { &*poa }.get_servant_manager(),
426        |m| {
427            let (k, p) = m.as_ref().map_or((0, std::ptr::null_mut()), manager_object);
428            unsafe {
429                *kind = k;
430                *this = p;
431            }
432        },
433    )
434}
435
436#[unsafe(no_mangle)]
437pub unsafe extern "C" fn rorb_poa_set_the_activator(
438    poa: *mut Poa,
439    this: *mut c_void,
440    vtable: *const AdapterActivatorVtable,
441    exc: *mut Exception,
442) -> Status {
443    poa_call(
444        exc,
445        || {
446            let activator: Option<Arc<dyn AdapterActivator>> = if this.is_null() {
447                None
448            } else {
449                Some(Caller::<AdapterActivatorVtable>::new(this, vtable))
450            };
451            unsafe { &*poa }.set_the_activator(activator)
452        },
453        |()| {},
454    )
455}
456
457#[unsafe(no_mangle)]
458pub unsafe extern "C" fn rorb_poa_the_activator(poa: *mut Poa) -> *mut c_void {
459    let Some(a) = unsafe { &*poa }.the_activator() else {
460        return std::ptr::null_mut();
461    };
462    match caller_of(&a) {
463        Some(_) => {
464            let c = unsafe {
465                &*(Arc::as_ptr(&a) as *const () as *const Caller<AdapterActivatorVtable>)
466            };
467            c.get()
468        }
469        None => std::ptr::null_mut(),
470    }
471}