Skip to main content

rustorb_ffi/
dii.rs

1//! The DII and the DSI (`rorb_request`, `rorb_server_request`) on the
2//! core's [`DiiRequest`] and [`ServerRequest`] (`docs/dii-dsi.md`).
3//!
4//! The values go in and out as anys (`rorb_any`). A request is made for
5//! one call: the caller (the C++ `CORBA::Request`) keeps its own list of
6//! arguments and makes a new `rorb_request` each time it sends it.
7//!
8//! A DSI servant is an ordinary caller servant (`rorb_servant_get`): its
9//! `dispatch` makes a `rorb_server_request` from the arguments stream,
10//! before reading anything from it, and ends with
11//! `rorb_server_request_reply`.
12
13use std::ffi::c_char;
14use std::sync::Mutex;
15
16use rustorb_core::dii::{ArgMode, DiiRequest, NamedValue, ServerRequest};
17use rustorb_core::{
18    Any, CompletionStatus, Exception as CoreException, ObjectRef, SystemException,
19    SystemExceptionKind, TypeCode, minor,
20};
21
22use crate::servant::ReplyFfi;
23use crate::stream::RorbIn;
24use crate::{
25    Exception, OK, Status, USER_EXCEPTION, bad_param, guard, into_handle, release_handle,
26    set_system, str_arg, sys,
27};
28
29fn bad_inv_order() -> SystemException {
30    sys(SystemExceptionKind::BAD_INV_ORDER, 0, CompletionStatus::No)
31}
32
33fn mode(flags: u32) -> Result<ArgMode, SystemException> {
34    ArgMode::from_flags(flags).ok_or_else(bad_param)
35}
36
37// --- the client side (rorb_request) ----------------------------------------------
38
39/// `rorb_request`: a [`DiiRequest`] and the user exception of its last
40/// call.
41#[derive(Debug)]
42pub struct FfiRequest {
43    request: DiiRequest,
44    exception: Option<Any>,
45}
46
47/// The request behind a handle; the lock is not poisoned by a panic the
48/// guard caught.
49type Handle = Mutex<FfiRequest>;
50
51unsafe fn request<'a>(req: *mut Handle) -> std::sync::MutexGuard<'a, FfiRequest> {
52    unsafe { &*req }.lock().unwrap_or_else(|e| e.into_inner())
53}
54
55#[unsafe(no_mangle)]
56pub unsafe extern "C" fn rorb_request_new(
57    target: *mut ObjectRef,
58    operation: *const c_char,
59    len: usize,
60    out: *mut *mut Handle,
61    exc: *mut Exception,
62) -> Status {
63    guard(exc, || {
64        let target = unsafe { &*target };
65        match unsafe { str_arg(operation, len) } {
66            Ok(op) => {
67                let r = FfiRequest {
68                    request: target.create_request(op),
69                    exception: None,
70                };
71                unsafe { *out = into_handle(Mutex::new(r)) };
72                OK
73            }
74            Err(e) => unsafe { set_system(exc, &e) },
75        }
76    })
77}
78
79#[unsafe(no_mangle)]
80pub unsafe extern "C" fn rorb_request_release(req: *mut Handle) {
81    unsafe { release_handle(req) }
82}
83
84/// Adds an argument: `value` is its value, or for an `out` argument
85/// only its type.
86#[unsafe(no_mangle)]
87pub unsafe extern "C" fn rorb_request_add_arg(
88    req: *mut Handle,
89    name: *const c_char,
90    len: usize,
91    flags: u32,
92    value: *const Any,
93    exc: *mut Exception,
94) -> Status {
95    guard(exc, || {
96        let r = (|| {
97            let name = unsafe { str_arg(name, len) }?;
98            let mode = mode(flags)?;
99            let value = unsafe { &*value };
100            let nv = match mode {
101                ArgMode::Out => NamedValue::out(name, value.typecode().clone()),
102                _ => NamedValue::new(name, value.clone(), mode),
103            };
104            unsafe { request(req) }.request.arguments_mut().push(nv);
105            Ok(())
106        })();
107        match r {
108            Ok(()) => OK,
109            Err(e) => unsafe { set_system(exc, &e) },
110        }
111    })
112}
113
114#[unsafe(no_mangle)]
115pub unsafe extern "C" fn rorb_request_set_return_type(req: *mut Handle, tc: *const TypeCode) {
116    let tc = unsafe { &*tc }.clone();
117    unsafe { request(req) }.request.set_return_type(tc);
118}
119
120#[unsafe(no_mangle)]
121pub unsafe extern "C" fn rorb_request_add_exception(req: *mut Handle, tc: *const TypeCode) {
122    let tc = unsafe { &*tc }.clone();
123    unsafe { request(req) }.request.add_exception(tc);
124}
125
126/// The timeout of the calls, as `rorb_invocation.timeout_us`: negative
127/// for the policies', 0 for none.
128#[unsafe(no_mangle)]
129pub unsafe extern "C" fn rorb_request_set_timeout(req: *mut Handle, us: i64) {
130    if us < 0 {
131        return;
132    }
133    let us = u64::try_from(us).unwrap_or(0);
134    let timeout = (us > 0).then(|| std::time::Duration::from_micros(us));
135    unsafe { request(req) }.request.set_timeout(timeout);
136}
137
138/// The outcome of a call: a user exception is kept as an any (with the
139/// TypeCode of the exception list) and is [`USER_EXCEPTION`]; one that is
140/// not listed is `UNKNOWN`.
141fn outcome(r: &mut FfiRequest, result: Result<(), CoreException>, exc: *mut Exception) -> Status {
142    r.exception = None;
143    match result {
144        Ok(()) => OK,
145        Err(CoreException::System(e)) => unsafe { set_system(exc, &e) },
146        Err(CoreException::User(u)) => match r.request.exception_value(&u) {
147            Ok(any) => {
148                r.exception = Some(any);
149                USER_EXCEPTION
150            }
151            Err(e) if e.kind() == Some(SystemExceptionKind::UNKNOWN) => unsafe {
152                set_system(
153                    exc,
154                    &sys(
155                        SystemExceptionKind::UNKNOWN,
156                        minor::UNLISTED_USER_EXCEPTION,
157                        CompletionStatus::Yes,
158                    ),
159                )
160            },
161            Err(e) => unsafe { set_system(exc, &e) },
162        },
163    }
164}
165
166#[unsafe(no_mangle)]
167pub unsafe extern "C" fn rorb_request_invoke(req: *mut Handle, exc: *mut Exception) -> Status {
168    guard(exc, || {
169        let mut r = unsafe { request(req) };
170        crate::stack::commit();
171        let result = r.request.invoke();
172        outcome(&mut r, result, exc)
173    })
174}
175
176#[unsafe(no_mangle)]
177pub unsafe extern "C" fn rorb_request_send_oneway(req: *mut Handle, exc: *mut Exception) -> Status {
178    guard(exc, || {
179        match unsafe { request(req) }.request.send_oneway() {
180            Ok(()) => OK,
181            Err(e) => unsafe { set_system(exc, &e) },
182        }
183    })
184}
185
186#[unsafe(no_mangle)]
187pub unsafe extern "C" fn rorb_request_send_deferred(
188    req: *mut Handle,
189    exc: *mut Exception,
190) -> Status {
191    guard(exc, || {
192        match unsafe { request(req) }.request.send_deferred() {
193            Ok(()) => OK,
194            Err(e) => unsafe { set_system(exc, &e) },
195        }
196    })
197}
198
199/// Sets `*ready` to whether the response of `rorb_request_send_deferred`
200/// has arrived.
201#[unsafe(no_mangle)]
202pub unsafe extern "C" fn rorb_request_poll_response(
203    req: *mut Handle,
204    ready: *mut i32,
205    exc: *mut Exception,
206) -> Status {
207    guard(exc, || {
208        match unsafe { request(req) }.request.poll_response() {
209            Ok(v) => {
210                unsafe { *ready = i32::from(v) };
211                OK
212            }
213            Err(e) => unsafe { set_system(exc, &e) },
214        }
215    })
216}
217
218/// Waits for the response of `rorb_request_send_deferred`; the outcome is
219/// that of `rorb_request_invoke`.
220#[unsafe(no_mangle)]
221pub unsafe extern "C" fn rorb_request_get_response(
222    req: *mut Handle,
223    exc: *mut Exception,
224) -> Status {
225    guard(exc, || {
226        let mut r = unsafe { request(req) };
227        let result = r.request.get_response();
228        outcome(&mut r, result, exc)
229    })
230}
231
232/// The return value (its type only before a call): a new handle.
233#[unsafe(no_mangle)]
234pub unsafe extern "C" fn rorb_request_result(req: *mut Handle) -> *mut Any {
235    into_handle(unsafe { request(req) }.request.result().clone())
236}
237
238/// The value of argument `index` (that sent for an `in` one, that received
239/// for the others after a call): a new handle, NULL when there is no such
240/// argument.
241#[unsafe(no_mangle)]
242pub unsafe extern "C" fn rorb_request_argument(req: *mut Handle, index: usize) -> *mut Any {
243    match unsafe { request(req) }.request.arguments().get(index) {
244        Some(nv) => into_handle(nv.value.clone()),
245        None => std::ptr::null_mut(),
246    }
247}
248
249/// The user exception of the last call (after `RORB_USER_EXCEPTION`): a
250/// new handle, NULL when there was none.
251#[unsafe(no_mangle)]
252pub unsafe extern "C" fn rorb_request_exception(req: *mut Handle) -> *mut Any {
253    match &unsafe { request(req) }.exception {
254        Some(any) => into_handle(any.clone()),
255        None => std::ptr::null_mut(),
256    }
257}
258
259// --- the server side (rorb_server_request) ---------------------------------------
260
261/// `rorb_server_request`: a [`ServerRequest`] and the parameters given
262/// before its arguments are read.
263#[derive(Debug)]
264pub struct FfiServerRequest {
265    /// `None` once the reply is written.
266    request: Option<ServerRequest>,
267    params: Vec<NamedValue>,
268}
269
270impl FfiServerRequest {
271    fn request(&mut self) -> Result<&mut ServerRequest, SystemException> {
272        self.request.as_mut().ok_or_else(bad_inv_order)
273    }
274}
275
276type ServerHandle = Mutex<FfiServerRequest>;
277
278unsafe fn server_request<'a>(sr: *mut ServerHandle) -> std::sync::MutexGuard<'a, FfiServerRequest> {
279    unsafe { &*sr }.lock().unwrap_or_else(|e| e.into_inner())
280}
281
282fn status(exc: *mut Exception, r: Result<(), SystemException>) -> Status {
283    match r {
284        Ok(()) => OK,
285        Err(e) => unsafe { set_system(exc, &e) },
286    }
287}
288
289/// The request whose arguments `args` (the stream `dispatch` got, nothing
290/// read from it yet) holds.
291#[unsafe(no_mangle)]
292pub unsafe extern "C" fn rorb_server_request_new(
293    args: *mut RorbIn,
294    operation: *const c_char,
295    len: usize,
296    out: *mut *mut ServerHandle,
297    exc: *mut Exception,
298) -> Status {
299    guard(exc, || {
300        let input = unsafe { &mut *args };
301        let r = unsafe { str_arg(operation, len) }
302            .and_then(|op| ServerRequest::new(op, input.stream()));
303        match r {
304            Ok(request) => {
305                let sr = FfiServerRequest {
306                    request: Some(request),
307                    params: Vec::new(),
308                };
309                unsafe { *out = into_handle(Mutex::new(sr)) };
310                OK
311            }
312            Err(e) => unsafe { set_system(exc, &e) },
313        }
314    })
315}
316
317#[unsafe(no_mangle)]
318pub unsafe extern "C" fn rorb_server_request_release(sr: *mut ServerHandle) {
319    unsafe { release_handle(sr) }
320}
321
322/// Adds a parameter, of type `tc`, for `rorb_server_request_arguments`.
323#[unsafe(no_mangle)]
324pub unsafe extern "C" fn rorb_server_request_add_param(
325    sr: *mut ServerHandle,
326    name: *const c_char,
327    len: usize,
328    flags: u32,
329    tc: *const TypeCode,
330    exc: *mut Exception,
331) -> Status {
332    guard(exc, || {
333        let r = (|| {
334            let name = unsafe { str_arg(name, len) }?;
335            let mode = mode(flags)?;
336            let mut nv = NamedValue::out(name, unsafe { &*tc }.clone());
337            nv.mode = mode;
338            unsafe { server_request(sr) }.params.push(nv);
339            Ok(())
340        })();
341        status(exc, r)
342    })
343}
344
345/// Reads the `in` and `inout` arguments of the parameters added. Once
346/// only (`BAD_INV_ORDER`); arguments that do not match are `MARSHAL`.
347#[unsafe(no_mangle)]
348pub unsafe extern "C" fn rorb_server_request_arguments(
349    sr: *mut ServerHandle,
350    exc: *mut Exception,
351) -> Status {
352    guard(exc, || {
353        let mut s = unsafe { server_request(sr) };
354        let params = std::mem::take(&mut s.params);
355        let r = s.request().and_then(|r| r.arguments(params).map(drop));
356        status(exc, r)
357    })
358}
359
360/// The value of parameter `index` after `rorb_server_request_arguments`
361/// (a new handle); NULL for an `out` one not set, or no such parameter.
362#[unsafe(no_mangle)]
363pub unsafe extern "C" fn rorb_server_request_argument(
364    sr: *mut ServerHandle,
365    index: usize,
366) -> *mut Any {
367    let mut s = unsafe { server_request(sr) };
368    let Ok(r) = s.request() else {
369        return std::ptr::null_mut();
370    };
371    match r.parameters_mut().and_then(|p| p.get(index)) {
372        Some(nv) if !matches!(nv.value.value(), rustorb_core::Value::Void) => {
373            into_handle(nv.value.clone())
374        }
375        _ => std::ptr::null_mut(),
376    }
377}
378
379/// Sets the value of the `out` or `inout` parameter `index`, of a type
380/// equivalent to the parameter's (else `BAD_PARAM`, as for an `in` one or
381/// no such parameter). `BAD_INV_ORDER` before the arguments are read.
382#[unsafe(no_mangle)]
383pub unsafe extern "C" fn rorb_server_request_set_argument(
384    sr: *mut ServerHandle,
385    index: usize,
386    value: *const Any,
387    exc: *mut Exception,
388) -> Status {
389    guard(exc, || {
390        let value = unsafe { &*value };
391        let mut s = unsafe { server_request(sr) };
392        let r = s.request().and_then(|r| {
393            let params = r.parameters_mut().ok_or_else(bad_inv_order)?;
394            let nv = params.get_mut(index).ok_or_else(bad_param)?;
395            if nv.mode == ArgMode::In || !nv.value.typecode().equivalent(value.typecode()) {
396                return Err(bad_param());
397            }
398            nv.value = value.clone();
399            Ok(())
400        });
401        status(exc, r)
402    })
403}
404
405#[unsafe(no_mangle)]
406pub unsafe extern "C" fn rorb_server_request_set_result(
407    sr: *mut ServerHandle,
408    value: *const Any,
409    exc: *mut Exception,
410) -> Status {
411    guard(exc, || {
412        let value = unsafe { &*value }.clone();
413        let mut s = unsafe { server_request(sr) };
414        let r = s.request().and_then(|r| r.set_result(value));
415        status(exc, r)
416    })
417}
418
419/// Makes the reply the user exception `value` (an any of an exception
420/// type, else `BAD_PARAM`).
421#[unsafe(no_mangle)]
422pub unsafe extern "C" fn rorb_server_request_set_exception(
423    sr: *mut ServerHandle,
424    value: *const Any,
425    exc: *mut Exception,
426) -> Status {
427    guard(exc, || {
428        let value = unsafe { &*value }.clone();
429        let mut s = unsafe { server_request(sr) };
430        let r = s.request().and_then(|r| r.set_exception(value));
431        status(exc, r)
432    })
433}
434
435/// Writes the reply of the dispatch `reply` belongs to: the user
436/// exception, or the result and the `out` and `inout` values. Once only
437/// (`BAD_INV_ORDER`). A value that does not fit its type (an `out`
438/// argument not set, say) is `BAD_PARAM`; the dispatch then replies with
439/// that exception.
440#[unsafe(no_mangle)]
441pub unsafe extern "C" fn rorb_server_request_reply(
442    sr: *mut ServerHandle,
443    reply: *mut ReplyFfi,
444    exc: *mut Exception,
445) -> Status {
446    guard(exc, || {
447        let Some(request) = unsafe { server_request(sr) }.request.take() else {
448            return unsafe { set_system(exc, &bad_inv_order()) };
449        };
450        let server_reply = unsafe { &mut *reply }.server_reply();
451        status(exc, request.write_reply(unsafe { &mut *server_reply }))
452    })
453}