Skip to main content

rustorb_ffi/
lib.rs

1//! Stable `extern "C"` ABI layer over the rustorb core.
2//!
3//! The C++ binding (`cpp/include/rustorb`) and the Java binding (through
4//! the FFM API) are built on this crate; the Python binding uses PyO3
5//! directly instead. The functions are declared, with the rules every
6//! caller follows (handles, errors, strings, the lifetime of streams), in
7//! `include/rustorb/rustorb.h`.
8//!
9//! - [`orb`]: `ORB_init` and the ORB operations.
10//! - [`object`]: object references, and invocations whose arguments and
11//!   results the caller writes and reads in callbacks.
12//! - [`stream`]: the CDR streams the callbacks get. Their errors are
13//!   sticky, so generated code does not check every call.
14//! - [`owned`]: input streams the caller owns after the call that made
15//!   them (replies, the bytes a callback writes, the value of an any), for
16//!   the portable streams of the Java mapping.
17//! - [`servant`]: servants implemented by the caller through a table of
18//!   callbacks, and the replies they write.
19//! - [`poa`]: the POA, its manager and `PortableServer::Current`.
20//! - [`manager`]: servant managers and adapter activators implemented by
21//!   the caller through tables of callbacks.
22//! - [`any`]: TypeCodes, and anys whose values the caller puts in and
23//!   takes out through the same streams.
24//! - [`dynany`]: `DynamicAny`, its values going in and out as anys.
25//! - [`value`]: valuetypes on the streams (sharing, chunks, truncation),
26//!   their TypeCodes and the registry of valuetypes the core reads.
27//! - [`pi`]: Portable Interceptors and `IOP::Codec`.
28//! - [`dii`]: the DII (`rorb_request`) and the DSI (`rorb_server_request`),
29//!   their values going in and out as anys.
30
31// Every function takes raw pointers from C; what they must point to is
32// documented once, in the header.
33#![allow(clippy::missing_safety_doc)]
34
35pub mod any;
36pub mod dii;
37pub mod dynany;
38pub mod manager;
39pub mod object;
40mod offload;
41pub mod orb;
42pub mod owned;
43pub mod pi;
44pub mod poa;
45pub mod policy;
46pub mod servant;
47mod stack;
48pub mod stream;
49pub mod value;
50
51use std::ffi::c_char;
52use std::panic::{AssertUnwindSafe, catch_unwind};
53
54use rustorb_core::{CompletionStatus, PoaError, SystemException, SystemExceptionKind};
55
56/// `rorb_status`.
57pub type Status = i32;
58
59/// Success.
60pub const OK: Status = 0;
61/// A system exception, in the [`Exception`].
62pub const SYSTEM_EXCEPTION: Status = 1;
63/// A user exception, taken by the caller's callback.
64pub const USER_EXCEPTION: Status = 2;
65/// An exception of a local interface, named by [`Exception::local`].
66pub const LOCAL_EXCEPTION: Status = 3;
67/// A callback failed and keeps its own error.
68pub const CALLBACK_FAILED: Status = 4;
69
70/// The version of the ABI in the header (`RORB_ABI_VERSION`).
71pub const ABI_VERSION: u32 = 3;
72
73/// Values of [`Exception::local`] (`RORB_ADAPTER_ALREADY_EXISTS`, ...).
74pub mod local {
75    pub const ADAPTER_ALREADY_EXISTS: u32 = 1;
76    pub const ADAPTER_NON_EXISTENT: u32 = 2;
77    pub const INVALID_POLICY: u32 = 3;
78    pub const SERVANT_ALREADY_ACTIVE: u32 = 4;
79    pub const OBJECT_ALREADY_ACTIVE: u32 = 5;
80    pub const SERVANT_NOT_ACTIVE: u32 = 6;
81    pub const OBJECT_NOT_ACTIVE: u32 = 7;
82    pub const WRONG_POLICY: u32 = 8;
83    pub const WRONG_ADAPTER: u32 = 9;
84    pub const ADAPTER_INACTIVE: u32 = 10;
85    pub const NO_SERVANT: u32 = 11;
86    pub const NO_CONTEXT: u32 = 12;
87    pub const INVALID_NAME: u32 = 13;
88    pub const TC_BAD_KIND: u32 = 14;
89    pub const TC_BOUNDS: u32 = 15;
90    pub const POLICY_ERROR: u32 = 16;
91    pub const DYN_INVALID_VALUE: u32 = 17;
92    pub const DYN_TYPE_MISMATCH: u32 = 18;
93    pub const DYN_INCONSISTENT_TYPECODE: u32 = 19;
94    pub const DYN_MUST_TRUNCATE: u32 = 20;
95    pub const INVALID_SLOT: u32 = 21;
96    pub const DUPLICATE_NAME: u32 = 22;
97    pub const UNKNOWN_ENCODING: u32 = 23;
98    pub const CODEC_INVALID_TYPE_FOR_ENCODING: u32 = 24;
99    pub const CODEC_FORMAT_MISMATCH: u32 = 25;
100    pub const CODEC_TYPE_MISMATCH: u32 = 26;
101    pub const MANAGER_ALREADY_EXISTS: u32 = 27;
102}
103
104/// `rorb_exception`.
105#[repr(C)]
106#[derive(Debug)]
107pub struct Exception {
108    pub repository_id: *mut c_char,
109    pub repository_id_len: usize,
110    pub minor: u32,
111    pub completed: u32,
112    pub local: u32,
113    pub index: u32,
114}
115
116impl Exception {
117    /// No exception, as a zeroed `rorb_exception`.
118    pub(crate) fn empty() -> Exception {
119        Exception {
120            repository_id: std::ptr::null_mut(),
121            repository_id_len: 0,
122            minor: 0,
123            completed: 0,
124            local: 0,
125            index: 0,
126        }
127    }
128}
129
130/// `rorb_bytes`.
131#[repr(C)]
132#[derive(Debug)]
133pub struct Bytes {
134    pub data: *mut u8,
135    pub len: usize,
136}
137
138impl Bytes {
139    pub(crate) fn new(v: Vec<u8>) -> Bytes {
140        let boxed = v.into_boxed_slice();
141        let len = boxed.len();
142        let data = Box::into_raw(boxed) as *mut u8;
143        Bytes { data, len }
144    }
145}
146
147#[unsafe(no_mangle)]
148pub extern "C" fn rorb_abi_version() -> u32 {
149    ABI_VERSION
150}
151
152#[unsafe(no_mangle)]
153pub unsafe extern "C" fn rorb_bytes_free(bytes: Bytes) {
154    if !bytes.data.is_null() {
155        let slice = std::ptr::slice_from_raw_parts_mut(bytes.data, bytes.len);
156        drop(unsafe { Box::from_raw(slice) });
157    }
158}
159
160#[unsafe(no_mangle)]
161pub unsafe extern "C" fn rorb_exception_clear(exc: *mut Exception) {
162    let Some(exc) = (unsafe { exc.as_mut() }) else {
163        return;
164    };
165    if !exc.repository_id.is_null() {
166        // Allocated by set_system with one byte more for the NUL.
167        let slice = std::ptr::slice_from_raw_parts_mut(
168            exc.repository_id as *mut u8,
169            exc.repository_id_len + 1,
170        );
171        drop(unsafe { Box::from_raw(slice) });
172    }
173    exc.repository_id = std::ptr::null_mut();
174    exc.repository_id_len = 0;
175    exc.minor = 0;
176    exc.completed = 0;
177    exc.local = 0;
178    exc.index = 0;
179}
180
181pub(crate) fn completion_code(c: CompletionStatus) -> u32 {
182    match c {
183        CompletionStatus::Yes => 0,
184        CompletionStatus::No => 1,
185        CompletionStatus::Maybe => 2,
186    }
187}
188
189pub(crate) fn completion_status(code: u32) -> CompletionStatus {
190    match code {
191        0 => CompletionStatus::Yes,
192        1 => CompletionStatus::No,
193        _ => CompletionStatus::Maybe,
194    }
195}
196
197/// Fills `exc` with a system exception and returns [`SYSTEM_EXCEPTION`].
198pub(crate) unsafe fn set_system(exc: *mut Exception, e: &SystemException) -> Status {
199    if let Some(exc) = unsafe { exc.as_mut() } {
200        unsafe { rorb_exception_clear(exc) };
201        let mut id = e.repository_id.clone().into_bytes();
202        let len = id.len();
203        id.push(0);
204        exc.repository_id = Box::into_raw(id.into_boxed_slice()) as *mut c_char;
205        exc.repository_id_len = len;
206        exc.minor = e.minor;
207        exc.completed = completion_code(e.completed);
208    }
209    SYSTEM_EXCEPTION
210}
211
212/// Fills `exc` with an exception of a local interface and returns
213/// [`LOCAL_EXCEPTION`].
214pub(crate) unsafe fn set_local(exc: *mut Exception, code: u32, index: u32) -> Status {
215    if let Some(exc) = unsafe { exc.as_mut() } {
216        unsafe { rorb_exception_clear(exc) };
217        exc.local = code;
218        exc.index = index;
219    }
220    LOCAL_EXCEPTION
221}
222
223pub(crate) unsafe fn set_poa_error(exc: *mut Exception, e: &PoaError) -> Status {
224    let code = match e {
225        PoaError::AdapterAlreadyExists => local::ADAPTER_ALREADY_EXISTS,
226        PoaError::AdapterNonExistent => local::ADAPTER_NON_EXISTENT,
227        PoaError::InvalidPolicy(i) => {
228            return unsafe { set_local(exc, local::INVALID_POLICY, u32::from(*i)) };
229        }
230        PoaError::ServantAlreadyActive => local::SERVANT_ALREADY_ACTIVE,
231        PoaError::ObjectAlreadyActive => local::OBJECT_ALREADY_ACTIVE,
232        PoaError::ServantNotActive => local::SERVANT_NOT_ACTIVE,
233        PoaError::ObjectNotActive => local::OBJECT_NOT_ACTIVE,
234        PoaError::WrongPolicy => local::WRONG_POLICY,
235        PoaError::WrongAdapter => local::WRONG_ADAPTER,
236        PoaError::AdapterInactive => local::ADAPTER_INACTIVE,
237        PoaError::ManagerAlreadyExists => local::MANAGER_ALREADY_EXISTS,
238        PoaError::Policy(e) => {
239            return unsafe { set_local(exc, local::POLICY_ERROR, e.reason as u16 as u32) };
240        }
241        PoaError::NoServant => local::NO_SERVANT,
242        PoaError::NoContext => local::NO_CONTEXT,
243        PoaError::System(e) => return unsafe { set_system(exc, e) },
244    };
245    unsafe { set_local(exc, code, 0) }
246}
247
248pub(crate) fn sys(
249    kind: SystemExceptionKind,
250    minor: u32,
251    completed: CompletionStatus,
252) -> SystemException {
253    SystemException::new(kind, minor, completed)
254}
255
256pub(crate) fn bad_param() -> SystemException {
257    sys(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
258}
259
260/// A UTF-8 string argument; NULL is the empty string.
261pub(crate) unsafe fn str_arg<'a>(p: *const c_char, len: usize) -> Result<&'a str, SystemException> {
262    std::str::from_utf8(unsafe { bytes_arg(p as *const u8, len) }).map_err(|_| {
263        sys(
264            SystemExceptionKind::DATA_CONVERSION,
265            0,
266            CompletionStatus::No,
267        )
268    })
269}
270
271/// A byte string argument; NULL is the empty string.
272pub(crate) unsafe fn bytes_arg<'a>(p: *const u8, len: usize) -> &'a [u8] {
273    if p.is_null() || len == 0 {
274        &[]
275    } else {
276        unsafe { std::slice::from_raw_parts(p, len) }
277    }
278}
279
280/// Runs `f`, turning a panic into `INTERNAL` rather than unwinding into C.
281pub(crate) fn guard(exc: *mut Exception, f: impl FnOnce() -> Status) -> Status {
282    match catch_unwind(AssertUnwindSafe(f)) {
283        Ok(status) => status,
284        Err(_) => unsafe {
285            set_system(
286                exc,
287                &sys(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe),
288            )
289        },
290    }
291}
292
293/// Moves a value to the heap for C.
294pub(crate) fn into_handle<T>(v: T) -> *mut T {
295    Box::into_raw(Box::new(v))
296}
297
298/// Drops a handle made by [`into_handle`].
299pub(crate) unsafe fn release_handle<T>(p: *mut T) {
300    if !p.is_null() {
301        drop(unsafe { Box::from_raw(p) });
302    }
303}