| 1 | //! Apple process boundary: only the safe WASM interpreter sees remote updates. |
| 2 | use std::panic::{catch_unwind, AssertUnwindSafe}; |
| 3 | use wasmi::{Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder}; |
| 4 | const MAX_BYTES: usize = 8 * 1024 * 1024 + 1; |
| 5 | const FUEL: u64 = 40_000_000; |
| 6 | const WASM: &[u8] = include_bytes!("../../crdt/target/wasm32-unknown-unknown/release/docs_native_crdt.wasm"); |
| 7 | pub struct Host { |
| 8 | store: Store<StoreLimits>, |
| 9 | instance: Instance, |
| 10 | memory: Memory, |
| 11 | output: Vec<u8>, |
| 12 | failed: bool, |
| 13 | } |
| 14 | impl Host { |
| 15 | pub fn new() -> Result<Self, &'static str> { |
| 16 | let mut config = Config::default(); |
| 17 | config.consume_fuel(true); |
| 18 | let engine = Engine::new(&config); |
| 19 | let module = Module::new(&engine, WASM).map_err(|_| "invalid_module")?; |
| 20 | // No imports are supplied: CRDT must remain independent of host JS, |
| 21 | // filesystem, entropy and clock functions. Identity is an input. |
| 22 | let linker = Linker::new(&engine); |
| 23 | let limits = StoreLimitsBuilder::new().memory_size(64 * 1024 * 1024).instances(1).memories(1).tables(1).build(); |
| 24 | let mut store = Store::new(&engine, limits); |
| 25 | store.limiter(|limits| limits); |
| 26 | store.set_fuel(FUEL).map_err(|_| "fuel")?; |
| 27 | let instance = linker.instantiate(&mut store, &module).map_err(|_| "invalid_module")?.start(&mut store).map_err(|_| "module_trap")?; |
| 28 | let memory = instance.get_memory(&store, "memory").ok_or("invalid_module")?; |
| 29 | Ok(Self {store, instance, memory, output: Vec::new(), failed: false}) |
| 30 | } |
| 31 | pub fn call(&mut self, request: &[u8]) -> Result<&[u8], &'static str> { |
| 32 | if self.failed || request.len() > MAX_BYTES { return Err("replica_unavailable"); } |
| 33 | // Any failed mutation can have partially modified the WASM state. Once |
| 34 | // failed, discard the replica; never let callers continue using it. |
| 35 | self.failed = true; |
| 36 | self.store.set_fuel(FUEL).map_err(|_| "fuel")?; |
| 37 | let alloc = self.instance.get_typed_func::<u32, u32>(&self.store, "docs_editor_alloc").map_err(|_| "invalid_abi")?; |
| 38 | let ptr = alloc.call(&mut self.store, request.len() as u32).map_err(|_| "module_trap")?; |
| 39 | if ptr == 0 { return Err("allocation"); } |
| 40 | self.memory.write(&mut self.store, ptr as usize, request).map_err(|_| "invalid_memory")?; |
| 41 | let call = self.instance.get_typed_func::<(u32,u32), i32>(&self.store, "docs_editor_call").map_err(|_| "invalid_abi")?; |
| 42 | let status = call.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?; |
| 43 | let free = self.instance.get_typed_func::<(u32,u32), ()>(&self.store, "docs_editor_free").map_err(|_| "invalid_abi")?; |
| 44 | free.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?; |
| 45 | if status != 0 { |
| 46 | // Report only a fixed whitelist of engine error codes, never content. |
| 47 | 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; |
| 48 | 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; |
| 49 | let mut code = [0u8; 64]; |
| 50 | if len <= code.len() && self.memory.read(&self.store,start,&mut code[..len]).is_ok() { |
| 51 | 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" }); |
| 52 | } |
| 53 | return Err("rejected_command"); |
| 54 | } |
| 55 | 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; |
| 56 | 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; |
| 57 | if length > MAX_BYTES { return Err("oversized_output"); } |
| 58 | self.output.resize(length, 0); |
| 59 | self.memory.read(&self.store, start, &mut self.output).map_err(|_| "invalid_memory")?; |
| 60 | self.failed = false; |
| 61 | Ok(&self.output) |
| 62 | } |
| 63 | } |
| 64 | #[no_mangle] |
| 65 | pub extern "C" fn docs_host_new() -> *mut Host { |
| 66 | catch_unwind(|| Host::new().map(|h| Box::into_raw(Box::new(h))).unwrap_or(std::ptr::null_mut())).unwrap_or(std::ptr::null_mut()) |
| 67 | } |
| 68 | /// # Safety |
| 69 | /// `host` must be returned by docs_host_new, uniquely owned, and freed once. |
| 70 | #[no_mangle] |
| 71 | pub unsafe extern "C" fn docs_host_free(host: *mut Host) { |
| 72 | if !host.is_null() { let _ = catch_unwind(AssertUnwindSafe(|| drop(Box::from_raw(host)))); } |
| 73 | } |
| 74 | /// # Safety |
| 75 | /// Host/input/output must be valid for their stated lengths. The caller serializes calls. |
| 76 | #[no_mangle] |
| 77 | pub unsafe extern "C" fn docs_host_call(host: *mut Host, input: *const u8, length: usize, output: *mut u8, capacity: usize) -> i64 { |
| 78 | if host.is_null() || input.is_null() || output.is_null() || length > MAX_BYTES || capacity > MAX_BYTES { return -1; } |
| 79 | catch_unwind(AssertUnwindSafe(|| { |
| 80 | let host = &mut *host; |
| 81 | let bytes = std::slice::from_raw_parts(input, length); |
| 82 | match host.call(bytes) { |
| 83 | Ok(result) if result.len() <= capacity => { |
| 84 | std::ptr::copy_nonoverlapping(result.as_ptr(), output, result.len()); result.len() as i64 |
| 85 | }, |
| 86 | _ => { host.failed = true; -1 }, |
| 87 | } |
| 88 | })).unwrap_or_else(|_| { (*host).failed = true; -1 }) |
| 89 | } |
| 90 | |