//! Apple process boundary: only the safe WASM interpreter sees remote updates. use std::panic::{catch_unwind, AssertUnwindSafe}; use wasmi::{Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder}; const MAX_BYTES: usize = 8 * 1024 * 1024 + 1; const FUEL: u64 = 40_000_000; const WASM: &[u8] = include_bytes!("../../crdt/target/wasm32-unknown-unknown/release/docs_native_crdt.wasm"); pub struct Host { store: Store, instance: Instance, memory: Memory, output: Vec, failed: bool, } impl Host { pub fn new() -> Result { let mut config = Config::default(); config.consume_fuel(true); let engine = Engine::new(&config); let module = Module::new(&engine, WASM).map_err(|_| "invalid_module")?; // No imports are supplied: CRDT must remain independent of host JS, // filesystem, entropy and clock functions. Identity is an input. let linker = Linker::new(&engine); let limits = StoreLimitsBuilder::new().memory_size(64 * 1024 * 1024).instances(1).memories(1).tables(1).build(); let mut store = Store::new(&engine, limits); store.limiter(|limits| limits); store.set_fuel(FUEL).map_err(|_| "fuel")?; let instance = linker.instantiate(&mut store, &module).map_err(|_| "invalid_module")?.start(&mut store).map_err(|_| "module_trap")?; let memory = instance.get_memory(&store, "memory").ok_or("invalid_module")?; Ok(Self {store, instance, memory, output: Vec::new(), failed: false}) } pub fn call(&mut self, request: &[u8]) -> Result<&[u8], &'static str> { if self.failed || request.len() > MAX_BYTES { return Err("replica_unavailable"); } // Any failed mutation can have partially modified the WASM state. Once // failed, discard the replica; never let callers continue using it. self.failed = true; self.store.set_fuel(FUEL).map_err(|_| "fuel")?; let alloc = self.instance.get_typed_func::(&self.store, "docs_editor_alloc").map_err(|_| "invalid_abi")?; let ptr = alloc.call(&mut self.store, request.len() as u32).map_err(|_| "module_trap")?; if ptr == 0 { return Err("allocation"); } self.memory.write(&mut self.store, ptr as usize, request).map_err(|_| "invalid_memory")?; let call = self.instance.get_typed_func::<(u32,u32), i32>(&self.store, "docs_editor_call").map_err(|_| "invalid_abi")?; let status = call.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?; let free = self.instance.get_typed_func::<(u32,u32), ()>(&self.store, "docs_editor_free").map_err(|_| "invalid_abi")?; free.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?; if status != 0 { // Report only a fixed whitelist of engine error codes, never content. let len = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_len").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize; let start = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_ptr").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize; let mut code = [0u8; 64]; if len <= code.len() && self.memory.read(&self.store,start,&mut code[..len]).is_ok() { return Err(match &code[..len] { b"unknown_command" => "unknown_command", b"invalid_range" => "invalid_range", b"invalid_anchor" => "invalid_anchor", b"missing_node" => "missing_node", _ => "rejected_command" }); } return Err("rejected_command"); } let length = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_len").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize; let start = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_ptr").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize; if length > MAX_BYTES { return Err("oversized_output"); } self.output.resize(length, 0); self.memory.read(&self.store, start, &mut self.output).map_err(|_| "invalid_memory")?; self.failed = false; Ok(&self.output) } } #[no_mangle] pub extern "C" fn docs_host_new() -> *mut Host { catch_unwind(|| Host::new().map(|h| Box::into_raw(Box::new(h))).unwrap_or(std::ptr::null_mut())).unwrap_or(std::ptr::null_mut()) } /// # Safety /// `host` must be returned by docs_host_new, uniquely owned, and freed once. #[no_mangle] pub unsafe extern "C" fn docs_host_free(host: *mut Host) { if !host.is_null() { let _ = catch_unwind(AssertUnwindSafe(|| drop(Box::from_raw(host)))); } } /// # Safety /// Host/input/output must be valid for their stated lengths. The caller serializes calls. #[no_mangle] pub unsafe extern "C" fn docs_host_call(host: *mut Host, input: *const u8, length: usize, output: *mut u8, capacity: usize) -> i64 { if host.is_null() || input.is_null() || output.is_null() || length > MAX_BYTES || capacity > MAX_BYTES { return -1; } catch_unwind(AssertUnwindSafe(|| { let host = &mut *host; let bytes = std::slice::from_raw_parts(input, length); match host.call(bytes) { Ok(result) if result.len() <= capacity => { std::ptr::copy_nonoverlapping(result.as_ptr(), output, result.len()); result.len() as i64 }, _ => { host.failed = true; -1 }, } })).unwrap_or_else(|_| { (*host).failed = true; -1 }) }