1use 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#[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#[derive(Debug)]
35pub struct FfiServant {
36 this: *mut c_void,
37 vtable: *const ServantVtable,
38 repository_id: String,
39}
40
41unsafe impl Send for FfiServant {}
44unsafe impl Sync for FfiServant {}
45
46#[derive(Default)]
47struct Registry {
48 by_self: HashMap<usize, Weak<FfiServant>>,
50 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 (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 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#[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
175pub(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
181pub(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 let s = unsafe { &*(addr as *const FfiServant) };
189 (s.vtable().add_ref)(s.this);
190 Some(s.this)
191}
192
193pub(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(¤t) 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}