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