Files
@ 952d4edf0cbb
Branch filter:
Location: CSY/reowolf/src/runtime/ffi.rs
952d4edf0cbb
10.6 KiB
application/rls-services+xml
first C example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | use crate::common::*;
use crate::runtime::*;
use core::cell::RefCell;
use std::os::raw::{c_char, c_int, c_uchar, c_uint};
struct StoredError {
filled: bool,
buf: Vec<c_char>,
}
thread_local! {
// stores a string. DOES store the null terminator
static LAST_ERROR: RefCell<StoredError> = RefCell::new(StoredError { filled: false, buf: Vec::with_capacity(128) } );
}
const NULL_TERMINATOR: c_char = b'\0' as c_char;
// Silly HACK: rust uses MAX alignment of 128 bytes for fields (no effect) but causes
// cbindgen tool to make this struct OPAQUE (which is what we want).
// NOT null terminated
fn overwrite_last_error(error_msg: &[u8]) {
LAST_ERROR.with(|stored_error| {
let mut stored_error = stored_error.borrow_mut();
stored_error.filled = true;
stored_error.buf.clear();
let error_msg = unsafe { &*(error_msg as *const [u8] as *const [i8]) };
stored_error.buf.extend_from_slice(error_msg);
stored_error.buf.push(NULL_TERMINATOR);
})
}
unsafe fn as_rust_str<R, F: FnOnce(&str) -> R>(s: *const c_char, f: F) -> Option<R> {
as_rust_bytes(s, |bytes| {
let s = std::str::from_utf8(bytes).ok()?;
Some(f(s))
})
}
unsafe fn as_rust_bytes<R, F: FnOnce(&[u8]) -> R>(s: *const c_char, f: F) -> R {
let len = c_str_len(s);
let s = s as *const u8;
let bytes: &[u8] = std::slice::from_raw_parts(s, len);
f(bytes)
}
unsafe fn c_str_len(s: *const c_char) -> usize {
let mut len = 0;
while *(s.offset(len.try_into().unwrap())) != NULL_TERMINATOR {
len += 1;
}
len
}
unsafe fn try_parse_addr(s: *const c_char) -> Option<SocketAddr> {
as_rust_str(s, |s| s.parse().ok()).and_then(|x| x)
}
///////////////////////////////////////
/// Returns a pointer into the error buffer for reading as a null-terminated string
/// Returns null if there is no error in the buffer.
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_error_peek() -> *const c_char {
LAST_ERROR.with(|stored_error| {
let stored_error = stored_error.borrow();
if stored_error.filled {
stored_error.buf.as_ptr()
} else {
std::ptr::null()
}
})
}
/// Resets the error message buffer.
/// Returns:
/// - 0 if an error was cleared
/// - 1 if there was no error to clear
/// # Safety
/// TODO
#[no_mangle]
pub extern "C" fn connector_error_clear() -> c_int {
LAST_ERROR.with(|stored_error| {
let mut stored_error = stored_error.borrow_mut();
if stored_error.filled {
stored_error.buf.clear();
stored_error.filled = false;
0
} else {
1
}
})
}
/// Creates and returns Reowolf Connector structure allocated on the heap.
#[no_mangle]
pub extern "C" fn connector_new() -> *mut Connector {
Box::into_raw(Box::new(Connector::default()))
}
/// Creates and returns Reowolf Connector structure allocated on the heap.
#[no_mangle]
pub extern "C" fn connector_with_controller_id(controller_id: ControllerId) -> *mut Connector {
Box::into_raw(Box::new(Connector::Unconfigured(Unconfigured { controller_id })))
}
/// Configures the given Reowolf connector with a protocol description in PDL.
/// Returns:
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_configure(
connector: *mut Connector,
pdl: *mut c_char,
main: *mut c_char,
) -> c_int {
let mut b = Box::from_raw(connector); // unsafe!
let ret = as_rust_bytes(pdl, |pdl_bytes| {
as_rust_bytes(main, |main_bytes| match b.configure(pdl_bytes, main_bytes) {
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
})
});
Box::into_raw(b); // don't drop!
ret
}
/// Provides a binding annotation for the port with the given index with "native":
/// (The port is exposed for reading and writing from the application)
/// Returns:
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_bind_native(
connector: *mut Connector,
proto_port_index: usize,
) -> c_int {
// use PortBindErr::*;
let mut b = Box::from_raw(connector); // unsafe!
let ret = match b.bind_port(proto_port_index, PortBinding::Native) {
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
ret
}
/// Provides a binding annotation for the port with the given index with "native":
/// (The port is exposed for reading and writing from the application)
/// Returns:
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_bind_passive(
connector: *mut Connector,
proto_port_index: c_uint,
address: *const c_char,
) -> c_int {
if let Some(addr) = try_parse_addr(address) {
// use PortBindErr::*;
let mut b = Box::from_raw(connector); // unsafe!
let ret =
match b.bind_port(proto_port_index.try_into().unwrap(), PortBinding::Passive(addr)) {
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
ret
} else {
overwrite_last_error(b"Failed to parse input as ip address!");
-1
}
}
/// Provides a binding annotation for the port with the given index with "active":
/// (The port will conenct to a "passive" port at the given address during connect())
/// Returns:
/// - 0 for success
/// - 1 if the port was already bound and was left unchanged
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_bind_active(
connector: *mut Connector,
proto_port_index: c_uint,
address: *const c_char,
) -> c_int {
if let Some(addr) = try_parse_addr(address) {
// use PortBindErr::*;
let mut b = Box::from_raw(connector); // unsafe!
let ret = match b.bind_port(proto_port_index.try_into().unwrap(), PortBinding::Active(addr))
{
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
ret
} else {
overwrite_last_error(b"Failed to parse input as ip address!");
-1
}
}
/// Provides a binding annotation for the port with the given index with "active":
/// (The port will conenct to a "passive" port at the given address during connect())
/// Returns:
/// - 0 SUCCESS: connected successfully
/// - TODO error codes
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_connect(
connector: *mut Connector,
timeout_millis: u64,
) -> c_int {
let mut b = Box::from_raw(connector); // unsafe!
let ret = match b.connect(Duration::from_millis(timeout_millis)) {
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
ret
}
/// Destroys the given connector, freeing its underlying resources.
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_destroy(connector: *mut Connector) {
let c = Box::from_raw(connector); // unsafe!
drop(c); // for readability
}
/// Prepares to synchronously put a message at the given port, reading it from the given buffer.
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_put(
connector: *mut Connector,
proto_port_index: c_uint,
buf_ptr: *mut c_uchar,
msg_len: c_uint,
) -> c_int {
let buf = std::slice::from_raw_parts_mut(buf_ptr, msg_len.try_into().unwrap());
let payload = buf.to_vec(); // unsafe
let mut b = Box::from_raw(connector); // unsafe!
let ret = b.put(proto_port_index.try_into().unwrap(), payload);
Box::into_raw(b); // don't drop!
match ret {
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
}
}
/// Prepares to synchronously put a message at the given port, writing it to the given buffer.
/// - 0 SUCCESS
/// - 1 this port has the wrong direction
/// - 2 this port is already marked to get
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_get(connector: *mut Connector, proto_port_index: c_uint) -> c_int {
let mut b = Box::from_raw(connector); // unsafe!
let ret = b.get(proto_port_index.try_into().unwrap());
Box::into_raw(b); // don't drop!
// use PortOperationErr::*;
match ret {
Ok(()) => 0,
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
}
}
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_gotten(
connector: *mut Connector,
proto_port_index: c_uint,
buf_ptr_outptr: *mut *const c_uchar,
len_outptr: *mut c_uint,
) -> c_int {
let b = Box::from_raw(connector); // unsafe!
let ret = b.read_gotten(proto_port_index.try_into().unwrap());
// use ReadGottenErr::*;
let result = match ret {
Ok(ptr_slice) => {
let buf_ptr = ptr_slice.as_ptr();
let len = ptr_slice.len().try_into().unwrap();
buf_ptr_outptr.write(buf_ptr);
len_outptr.write(len);
0
}
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
result
}
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn port_close(connector: *mut Connector, _proto_port_index: c_uint) -> c_int {
let b = Box::from_raw(connector); // unsafe!
// TODO
Box::into_raw(b); // don't drop!
0
}
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_next_batch(connector: *mut Connector) -> c_int {
let mut b = Box::from_raw(connector); // unsafe!
let result = match b.next_batch() {
Ok(batch_index) => batch_index.try_into().unwrap(),
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
result
}
/// # Safety
/// TODO
#[no_mangle]
pub unsafe extern "C" fn connector_sync(connector: *mut Connector, timeout_millis: u64) -> c_int {
let mut b = Box::from_raw(connector); // unsafe!
let result = match b.sync(Duration::from_millis(timeout_millis)) {
Ok(batch_index) => batch_index.try_into().unwrap(),
Err(e) => {
overwrite_last_error(format!("{:?}", e).as_bytes());
-1
}
};
Box::into_raw(b); // don't drop!
result
}
|