industrial_protocols_bridge_ffi/
lib.rs1use industrial_protocols_kernel::bridge::Transport;
14use std::collections::HashMap;
15use std::ffi::{CString, c_char, c_int, c_uint};
16use std::io;
17use std::path::PathBuf;
18
19pub struct FfiConfig {
20 pub library_path: PathBuf,
21 pub vendor: String,
22 pub init_params: HashMap<String, String>,
23 pub symbols: FfiSymbols,
24}
25
26#[derive(Debug, Clone)]
27pub struct FfiSymbols {
28 pub init: String,
29 pub read: String,
30 pub write: String,
31 pub shutdown: String,
32}
33
34impl Default for FfiSymbols {
35 fn default() -> Self {
36 FfiSymbols {
37 init: "vendor_init".into(),
38 read: "vendor_read".into(),
39 write: "vendor_write".into(),
40 shutdown: "vendor_shutdown".into(),
41 }
42 }
43}
44
45type FfiInitFn = unsafe extern "C" fn(*const c_char) -> c_int;
46type FfiReadFn = unsafe extern "C" fn(c_uint, *mut u8, c_uint) -> c_int;
47type FfiWriteFn = unsafe extern "C" fn(c_uint, *const u8, c_uint) -> c_int;
48type FfiShutdownFn = unsafe extern "C" fn() -> c_int;
49
50pub struct SafeVendorTransport {
54 #[allow(dead_code)]
56 library: libloading::Library,
57 read_fn: unsafe extern "C" fn(c_uint, *mut u8, c_uint) -> c_int,
58 write_fn: unsafe extern "C" fn(c_uint, *const u8, c_uint) -> c_int,
59 shutdown_fn: unsafe extern "C" fn() -> c_int,
60 open: bool,
61}
62
63impl SafeVendorTransport {
64 pub fn load(config: FfiConfig) -> io::Result<Self> {
65 unsafe {
66 let lib = libloading::Library::new(&config.library_path).map_err(|e| {
67 io::Error::new(io::ErrorKind::NotFound, format!("failed to load: {e}"))
68 })?;
69
70 let init_sym: libloading::Symbol<FfiInitFn> =
72 lib.get(config.symbols.init.as_bytes()).map_err(|e| {
73 io::Error::new(io::ErrorKind::NotFound, format!("init symbol: {e}"))
74 })?;
75 let params = CString::new(
76 config
77 .init_params
78 .get("config")
79 .cloned()
80 .unwrap_or_default(),
81 )
82 .map_err(|_| {
83 io::Error::new(
84 io::ErrorKind::InvalidInput,
85 "init parameter contains a NUL byte",
86 )
87 })?;
88 let rc = init_sym(params.as_ptr());
89 if rc != 0 {
90 return Err(io::Error::other(format!("vendor init failed: code {rc}")));
91 }
92
93 let read_sym: libloading::Symbol<FfiReadFn> =
95 lib.get(config.symbols.read.as_bytes())
96 .map_err(|e| io::Error::new(io::ErrorKind::NotFound, format!("read: {e}")))?;
97 let read_fn: FfiReadFn = std::mem::transmute_copy(&*read_sym);
98
99 let write_sym: libloading::Symbol<FfiWriteFn> = lib
100 .get(config.symbols.write.as_bytes())
101 .map_err(|e| io::Error::new(io::ErrorKind::NotFound, format!("write: {e}")))?;
102 let write_fn: FfiWriteFn = std::mem::transmute_copy(&*write_sym);
103
104 let shutdown_sym: libloading::Symbol<FfiShutdownFn> = lib
105 .get(config.symbols.shutdown.as_bytes())
106 .map_err(|e| io::Error::new(io::ErrorKind::NotFound, format!("shutdown: {e}")))?;
107 let shutdown_fn: FfiShutdownFn = std::mem::transmute_copy(&*shutdown_sym);
108
109 Ok(SafeVendorTransport {
110 library: lib,
111 read_fn,
112 write_fn,
113 shutdown_fn,
114 open: true,
115 })
116 }
117 }
118
119 pub fn read_raw(&self, offset: u32, len: u32) -> io::Result<Vec<u8>> {
120 let mut buf = vec![0u8; len as usize];
121 let rc = unsafe { (self.read_fn)(offset, buf.as_mut_ptr(), len) };
122 if rc < 0 {
123 return Err(io::Error::other(format!("read failed: {rc}")));
124 }
125 Ok(buf)
126 }
127
128 pub fn write_raw(&self, offset: u32, data: &[u8]) -> io::Result<()> {
129 let rc = unsafe { (self.write_fn)(offset, data.as_ptr(), data.len() as u32) };
130 if rc < 0 {
131 return Err(io::Error::other(format!("write failed: {rc}")));
132 }
133 Ok(())
134 }
135}
136
137impl Transport for SafeVendorTransport {
138 fn send(&mut self, data: &[u8]) -> io::Result<Vec<u8>> {
139 if data.len() < 4 {
140 return Err(io::Error::new(
141 io::ErrorKind::InvalidInput,
142 "FFI frame too short",
143 ));
144 }
145 let offset = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
146 let payload = &data[4..];
147 if !payload.is_empty() {
148 self.write_raw(offset, payload)?;
149 }
150 self.read_raw(offset, 256)
151 }
152 fn is_open(&self) -> bool {
153 self.open
154 }
155 fn close(&mut self) -> io::Result<()> {
156 if !self.open {
157 return Ok(());
158 }
159 self.open = false;
160 unsafe {
161 (self.shutdown_fn)();
162 }
163 Ok(())
164 }
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170
171 fn config(lib: &str) -> FfiConfig {
172 FfiConfig {
173 library_path: PathBuf::from(lib),
174 vendor: "test".into(),
175 init_params: HashMap::new(),
176 symbols: FfiSymbols::default(),
177 }
178 }
179
180 #[test]
181 fn test_ffi_config_defaults() {
182 let syms = FfiSymbols::default();
183 assert_eq!(syms.init, "vendor_init");
184 assert_eq!(syms.read, "vendor_read");
185 assert_eq!(syms.write, "vendor_write");
186 assert_eq!(syms.shutdown, "vendor_shutdown");
187 }
188
189 #[test]
190 fn test_ffi_symbols_clone_debug() {
191 let syms = FfiSymbols::default();
192 let copy = syms.clone();
193 assert_eq!(copy.init, syms.init);
194 let _dbg = format!("{syms:?}");
195 }
196
197 #[test]
198 fn test_load_nonexistent_library() {
199 assert!(SafeVendorTransport::load(config("/tmp/nonexistent_lib.so")).is_err());
200 }
201
202 #[test]
203 fn test_ffi_config_custom_symbols_and_params() {
204 let cfg = FfiConfig {
205 library_path: PathBuf::from("/tmp/missing.so"),
206 vendor: "acme".into(),
207 init_params: HashMap::from([("config".to_string(), "cfg.txt".to_string())]),
208 symbols: FfiSymbols {
209 init: "acme_init".into(),
210 read: "acme_read".into(),
211 write: "acme_write".into(),
212 shutdown: "acme_shutdown".into(),
213 },
214 };
215 assert_eq!(cfg.vendor, "acme");
216 assert_eq!(cfg.symbols.init, "acme_init");
217 assert!(cfg.init_params.contains_key("config"));
218 assert!(SafeVendorTransport::load(cfg).is_err());
220 }
221
222 #[cfg(target_os = "linux")]
223 #[test]
224 fn test_load_system_lib_with_missing_init_symbol() {
225 assert!(SafeVendorTransport::load(config("libc.so.6")).is_err());
228 }
229}