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