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