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