//! The C ABI the Go host calls through wazero. No wasm-bindgen: wazero //! provides no JS glue, so everything crosses as integers and linear-memory //! offsets. //! //! Handles are indices into a slab rather than raw pointers, so a stale //! handle from the host is a null lookup instead of a wild dereference. //! //! # Containment, after the fix-round-1 review //! //! §5.2's architecture is: each document gets its own wasm module instance, //! and a trapped instance is discarded and rebuilt from a snapshot by the //! host. That defence is necessarily architectural, not something this //! module can validate its way out of — `yrs` decodes wire bytes with //! `std::str::from_utf8_unchecked` in places (`encoding/read.rs:137`, //! `lib.rs:763`, `decoder.rs:480`), so a sufficiently corrupted update can //! reach real undefined behaviour deep inside the CRDT decode, and finding //! that requires actually parsing the update — which is `yrs`'s job, not //! ours to redo. //! //! What *is* this module's job is to not make an upstream trap worse than //! it has to be: //! //! - No `DOCS` `RefCell` borrow is held across a call into `yrs` //! (`apply_update`, `fragment_text`, `fragment_html`). A wasm trap does not unwind — it is //! compiled to an `unreachable` instruction with `panic = "abort"` //! (`Cargo.toml`), which does not run destructors — so a borrow guard //! still on the stack at the moment of a trap never gets dropped and //! stays "borrowed" in the instance's memory forever, poisoning every //! later call that needs `borrow_mut()` (`doc_new`, `doc_free`) even for //! documents the bad update never touched. `get_doc` below clones the //! `Doc` out (an `Arc` clone — `yrs::Doc` is `#[derive(Clone)]` over //! `DocStore(Arc)`, so this is cheap and doesn't copy CRDT //! state) and releases the borrow before doing anything that might trap. //! - Every raw pointer/length pair this module receives from the host //! (`docs_core_doc_new`'s GUID, `docs_core_apply`'s update bytes, //! `docs_core_text_read`'s output buffer) is bounds-checked against the //! module's actual linear memory (`in_bounds`) before a slice is ever //! constructed over it. This turns a host bug (a bad pointer or a //! length that doesn't fit) into a returned error code instead of an //! out-of-bounds-memory trap — one we could prevent outright, unlike the //! CRDT-internal ones above. //! - A handle that doesn't exist in `DOCS` is distinguishable from a //! handle to a real, empty document: `docs_core_text_len` and //! `docs_core_text_read` both return `ERR_NO_DOC` for the former, not 0 //! bytes — a host silently persisting `""` over live content because it //! held a stale handle is exactly the kind of silent corruption §5.2 //! exists to avoid. use crate::{ apply_update, fragment_html, fragment_json, fragment_text, snapshot_bytes, verify_snapshot, CoreError, }; use std::cell::RefCell; use std::collections::HashMap; use yrs::updates::decoder::Decode; use yrs::{Doc, Options}; thread_local! { static DOCS: RefCell> = RefCell::new(HashMap::new()); static NEXT: RefCell = const { RefCell::new(1) }; } pub const ERR_NO_DOC: i32 = -1; pub const ERR_DECODE: i32 = -2; pub const ERR_APPLY: i32 = -3; pub const ERR_BUFFER_TOO_SMALL: i32 = -4; /// The host handed us a `ptr`/`len` pair this module's linear memory /// cannot possibly satisfy: `len` alone exceeds `isize::MAX` (the limit /// `std::slice::from_raw_parts` requires), or `ptr..ptr+len` reaches past /// the module's currently instantiated memory, or the addition overflows /// `u64`. See `in_bounds`. pub const ERR_INVALID_LENGTH: i32 = -5; /// Clones the `Doc` for `handle` out of `DOCS` and releases the borrow /// before returning it, so callers never hold a `RefCell` guard across a /// call into `yrs` that might trap. `yrs::Doc` clones cheaply (an `Arc` /// bump, not a copy of CRDT state) so this costs nothing meaningful. fn get_doc(handle: u32) -> Option { DOCS.with(|d| d.borrow().get(&handle).cloned()) } pub fn doc_new(guid: &str, client_id: u64) -> u32 { let id = NEXT.with(|n| { let mut n = n.borrow_mut(); let id = *n; // Finding 6: 0 is the failure sentinel every caller checks handles // against. Wrapping `u32` addition would land exactly on 0 after // 2^32 calls and silently hand out a "null" handle as if it were // real; skip 0 on wraparound instead of landing on it. let next = id.wrapping_add(1); *n = if next == 0 { 1 } else { next }; id }); let doc = Doc::with_options(Options::with_guid_and_client_id(guid.into(), client_id)); DOCS.with(|d| d.borrow_mut().insert(id, doc)); id } pub fn doc_free(handle: u32) { DOCS.with(|d| d.borrow_mut().remove(&handle)); } pub fn apply_slice(handle: u32, update: &[u8]) -> i32 { match get_doc(handle) { None => ERR_NO_DOC, Some(doc) => match apply_update(&doc, update) { Ok(()) => 0, Err(CoreError::Decode(_)) => ERR_DECODE, Err(CoreError::Apply(_)) => ERR_APPLY, }, } } /// `None` for an unknown handle — distinct from `Some(String::new())`, a /// real empty document. Callers must not collapse the two (Finding 3). /// /// Reads `fragment_text` (root "prosemirror"), not `text_content` (root /// "content"). Fix round 1 on the fragment-migration task: every real /// document has stored its content as a Y.XmlFragment on "prosemirror" /// since seed data and the editor moved there, so `text_content`'s root /// has been empty for any of them since — `docs_core_text_len`/ /// `docs_core_text_read` (and this function, the thing both of them /// call) were a silent trap, reporting an empty document's worth of /// success instead of a real one's prose. "This document's text" means /// `fragment_text`'s plain-text rendering of the fragment now. /// /// No ABI version bump for this: `docs_core_text_len`/ /// `docs_core_text_read`'s signatures and calling convention are /// unchanged — same byte-length-then-bytes shape the host already /// speaks — only what they read changed, and the host and this module /// ship embedded together with no version skew between separately /// deployed copies to guard against (`docs_core_abi_version`'s own doc /// comment covers what *does* need a bump: an incompatible export /// shape). Recorded here because "the semantics changed but the number /// did not" is exactly the kind of thing that looks like an oversight /// later. /// /// `text_content` itself is untouched and still backs the Rust↔JS /// Y.Text wire fixtures (`core/tests/wire_compat.rs`) directly — this /// repoints only what the wasm ABI exposes as "text", not the function /// the wire contract tests call by name. A future consumer that /// genuinely wants the bare-Y.Text root back (there is none today) can /// still call `text_content` directly; nothing here deletes it. pub fn text_string(handle: u32) -> Option { get_doc(handle).map(|doc| fragment_text(&doc)) } /// `None` for an unknown handle — distinct from `Some(String::new())`, a /// real empty document. Callers must not collapse the two (Finding 3), /// exactly as `text_string` above. pub fn html_string(handle: u32) -> Option { get_doc(handle).map(|doc| fragment_html(&doc)) } /// `None` for an unknown handle — distinct from `Some(String::new())`, a /// real empty document (Finding 3), exactly as `text_string` and /// `html_string` above. Note that an empty document is never the empty /// *string* here: `fragment_json` always emits at least /// `{"type":"doc","content":[]}`, so a zero length from /// `docs_core_json_len` is unreachable for a live handle and the host /// need not treat it as a special case the way the other two do. pub fn json_string(handle: u32) -> Option { get_doc(handle).map(|doc| fragment_json(&doc)) } /// The whole document as one update. Bytes, not a string — the host /// reads it through the same len/read convention as the three /// renderers, which is why this is shaped like them. pub fn snapshot_vec(handle: u32) -> Option> { get_doc(handle).map(|doc| snapshot_bytes(&doc)) } // --- wasm exports --- // Amended by pre-flight ruling R2. The obvious version — Vec::with_capacity // then Vec::from_raw_parts(ptr, 0, len) — is undefined behaviour: with_capacity // guarantees AT LEAST len, so reconstructing with capacity `len` is wrong // whenever the allocator rounded up. std::alloc with an identical Layout on // both sides has no such gap. /// The `Layout` for a `len`-byte buffer, or `None` if `len` isn't /// representable — `Layout::from_size_align` rejects any size that would /// round up past `isize::MAX` once aligned. That's a real possibility here: /// `len` is a host-supplied `u32`, and on wasm32 (where `usize` is 32-bit) /// `isize::MAX` is only `0x7FFF_FFFF`, well inside `u32`'s range. Fix-round-1 /// finding 2: the earlier version's `.expect("byte layout is always /// valid")` was simply wrong — this is reachable from host input, not an /// invariant. fn layout_for(len: u32) -> Option { // align 1: these are byte buffers the host writes into. std::alloc::Layout::from_size_align(len.max(1) as usize, 1).ok() } /// Number of bytes in this module's currently instantiated linear memory. /// On wasm32 this is the real bound `in_bounds` checks host pointers /// against. Native builds (this crate's own tests, `emit_update`) have no /// such thing as "this module's linear memory" — the concept doesn't /// apply outside the sandboxed wasm target — so `in_bounds` degrades on /// native to just the `isize::MAX` length check, which is still meaningful /// there and is what this crate's own tests exercise. #[cfg(target_arch = "wasm32")] fn memory_len_bytes() -> u64 { const WASM_PAGE_BYTES: u64 = 65536; core::arch::wasm32::memory_size(0) as u64 * WASM_PAGE_BYTES } #[cfg(not(target_arch = "wasm32"))] fn memory_len_bytes() -> u64 { u64::MAX } /// True if `ptr..ptr+len` is representable as a Rust slice and (on wasm32) /// fully inside this module's currently instantiated linear memory. /// `docs_core_doc_new`, `docs_core_apply`, and `docs_core_text_read` all /// call this before constructing a slice over host-supplied bytes, turning /// a bad `ptr`/`len` pair into `ERR_INVALID_LENGTH` instead of an /// out-of-bounds-memory trap (fix-round-1 finding 4). This cannot and does /// not validate the *contents* of the bytes — that's the CRDT decode's job, /// and where the upstream UB this module can't fix lives. fn in_bounds(ptr: u32, len: u32) -> bool { if len as u64 > isize::MAX as u64 { return false; } match (ptr as u64).checked_add(len as u64) { Some(end) => end <= memory_len_bytes(), None => false, } } /// Allocates `len` bytes in this module's linear memory for the host to /// write into (typically before `docs_core_apply` or as the destination /// for `docs_core_text_read`). Returns 0 on failure — `len` too large to /// form a valid `Layout` (see `layout_for`), or genuine allocator /// exhaustion — and **the host must check for a 0 return before using the /// pointer**; nothing here traps on a bad `len`. #[no_mangle] pub extern "C" fn docs_core_alloc(len: u32) -> u32 { match layout_for(len) { // SAFETY: `layout_for` never returns a zero-size Layout (it floors // `len` to 1), which is the one precondition `std::alloc::alloc` // places beyond having a valid Layout at all. Some(layout) => unsafe { std::alloc::alloc(layout) as u32 }, None => 0, } } /// # Safety /// /// `ptr` must be either 0 (a no-op) or a value previously returned by /// `docs_core_alloc`, not yet freed, and `len` must be exactly the `len` /// that allocation was made with — `layout_for(len)` must reproduce the /// same `Layout` used to allocate it, per `std::alloc::dealloc`'s contract. #[no_mangle] pub unsafe extern "C" fn docs_core_free(ptr: u32, len: u32) { if ptr == 0 { return; } // A `len` with no valid Layout cannot be the `len` docs_core_alloc // succeeded with — alloc would have already returned 0 for it. Rather // than call `dealloc` with a fabricated Layout (undefined behaviour if // it doesn't match the allocation), treat this as a no-op: it means // the host handed back an inconsistent ptr/len, not that memory needs // reclaiming. if let Some(layout) = layout_for(len) { std::alloc::dealloc(ptr as *mut u8, layout); } } /// # Safety /// /// `guid_ptr` and `guid_len` must describe a byte range that lies entirely /// within this module's linear memory and is not mutated for the duration /// of this call. (Checked by `in_bounds` before any slice is constructed — /// this safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_doc_new(guid_ptr: u32, guid_len: u32, client_id: u64) -> u32 { if !in_bounds(guid_ptr, guid_len) { return 0; // out-of-bounds ptr/len is a null handle, not a trap } let bytes = std::slice::from_raw_parts(guid_ptr as *const u8, guid_len as usize); match std::str::from_utf8(bytes) { Ok(guid) => doc_new(guid, client_id), Err(_) => 0, // invalid UTF-8 GUID is a null handle, not a trap } } #[no_mangle] pub extern "C" fn docs_core_doc_free(handle: u32) { doc_free(handle) } /// # Safety /// /// `ptr` and `len` must describe a byte range that lies entirely within /// this module's linear memory and is not mutated for the duration of this /// call. (Checked by `in_bounds` before any slice is constructed — this /// safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_apply(handle: u32, ptr: u32, len: u32) -> i32 { if !in_bounds(ptr, len) { return ERR_INVALID_LENGTH; } let bytes = std::slice::from_raw_parts(ptr as *const u8, len as usize); apply_slice(handle, bytes) } /// Returns the byte length of `handle`'s text content, or `ERR_NO_DOC` if /// `handle` doesn't name a live document — distinct from 0, which means a /// real, empty document (Finding 3). #[no_mangle] pub extern "C" fn docs_core_text_len(handle: u32) -> i32 { match text_string(handle) { Some(s) => s.len().try_into().unwrap_or(i32::MAX), None => ERR_NO_DOC, } } /// # Safety /// /// `out_ptr` and `out_len` must describe a byte range that lies entirely /// within this module's linear memory and is valid for writes for the /// duration of this call. (Checked by `in_bounds` before any write — this /// safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_text_read(handle: u32, out_ptr: u32, out_len: u32) -> i32 { let s = match text_string(handle) { Some(s) => s, None => return ERR_NO_DOC, // stale/unknown handle, not an empty read }; if s.len() > out_len as usize { return ERR_BUFFER_TOO_SMALL; } if !in_bounds(out_ptr, out_len) { return ERR_INVALID_LENGTH; } std::ptr::copy_nonoverlapping(s.as_ptr(), out_ptr as *mut u8, s.len()); // s.len() <= out_len, and in_bounds(out_ptr, out_len) already proved // out_len <= isize::MAX, so this fits in i32... only when isize is // 32-bit (wasm32). On native 64-bit test builds isize::MAX is far // larger, so clamp explicitly rather than rely on that coincidence. s.len().try_into().unwrap_or(i32::MAX) } /// Returns the byte length of `handle`'s HTML rendering, or `ERR_NO_DOC` /// if `handle` doesn't name a live document — distinct from 0, which /// means a real, empty document (Finding 3), exactly as /// `docs_core_text_len` above. #[no_mangle] pub extern "C" fn docs_core_html_len(handle: u32) -> i32 { match html_string(handle) { Some(s) => s.len().try_into().unwrap_or(i32::MAX), None => ERR_NO_DOC, } } /// # Safety /// /// `out_ptr` and `out_len` must describe a byte range that lies entirely /// within this module's linear memory and is valid for writes for the /// duration of this call. (Checked by `in_bounds` before any write — this /// safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_html_read(handle: u32, out_ptr: u32, out_len: u32) -> i32 { let s = match html_string(handle) { Some(s) => s, None => return ERR_NO_DOC, // stale/unknown handle, not an empty read }; if s.len() > out_len as usize { return ERR_BUFFER_TOO_SMALL; } if !in_bounds(out_ptr, out_len) { return ERR_INVALID_LENGTH; } std::ptr::copy_nonoverlapping(s.as_ptr(), out_ptr as *mut u8, s.len()); // s.len() <= out_len, and in_bounds(out_ptr, out_len) already proved // out_len <= isize::MAX, so this fits in i32... only when isize is // 32-bit (wasm32). On native 64-bit test builds isize::MAX is far // larger, so clamp explicitly rather than rely on that coincidence. s.len().try_into().unwrap_or(i32::MAX) } /// Returns the byte length of `handle`'s JSON rendering, or `ERR_NO_DOC` /// if `handle` doesn't name a live document — distinct from 0, exactly /// as `docs_core_text_len` and `docs_core_html_len` above. (0 is not /// reachable here at all for a live handle; see `json_string`.) #[no_mangle] pub extern "C" fn docs_core_json_len(handle: u32) -> i32 { match json_string(handle) { Some(s) => s.len().try_into().unwrap_or(i32::MAX), None => ERR_NO_DOC, } } /// # Safety /// /// `out_ptr` and `out_len` must describe a byte range that lies entirely /// within this module's linear memory and is valid for writes for the /// duration of this call. (Checked by `in_bounds` before any write — this /// safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_json_read(handle: u32, out_ptr: u32, out_len: u32) -> i32 { let s = match json_string(handle) { Some(s) => s, None => return ERR_NO_DOC, // stale/unknown handle, not an empty read }; if s.len() > out_len as usize { return ERR_BUFFER_TOO_SMALL; } if !in_bounds(out_ptr, out_len) { return ERR_INVALID_LENGTH; } std::ptr::copy_nonoverlapping(s.as_ptr(), out_ptr as *mut u8, s.len()); // Same clamp, same reason as the two read functions above. s.len().try_into().unwrap_or(i32::MAX) } /// Returns the byte length of `handle`'s whole-state snapshot, or /// `ERR_NO_DOC` if `handle` doesn't name a live document — distinct /// from 0, exactly as `docs_core_text_len`, `docs_core_html_len`, and /// `docs_core_json_len` above. #[no_mangle] pub extern "C" fn docs_core_snapshot_len(handle: u32) -> i32 { match snapshot_vec(handle) { Some(v) => v.len().try_into().unwrap_or(i32::MAX), None => ERR_NO_DOC, } } /// # Safety /// /// `out_ptr` and `out_len` must describe a byte range that lies entirely /// within this module's linear memory and is valid for writes for the /// duration of this call. (Checked by `in_bounds` before any write — this /// safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_snapshot_read(handle: u32, out_ptr: u32, out_len: u32) -> i32 { let v = match snapshot_vec(handle) { Some(v) => v, None => return ERR_NO_DOC, // stale/unknown handle, not an empty read }; if v.len() > out_len as usize { return ERR_BUFFER_TOO_SMALL; } if !in_bounds(out_ptr, out_len) { return ERR_INVALID_LENGTH; } std::ptr::copy_nonoverlapping(v.as_ptr(), out_ptr as *mut u8, v.len()); // Same clamp, same reason as the two read functions above. v.len().try_into().unwrap_or(i32::MAX) } /// 0 = the candidate is this document, 1 = it is not, `ERR_DECODE` = the /// bytes are not an update at all, `ERR_NO_DOC` = no such handle. /// /// Deviation from the brief's Step 5 listing: that code called /// `verify_snapshot` directly and let its `bool` collapse "undecodable" /// into the same `1` as a genuine mismatch, which contradicts this /// export's own documented contract (`ERR_DECODE` as a distinct /// outcome). `verify_snapshot`'s signature — `-> bool` — is the /// documented Rust-level interface and stays that way; the decode is /// checked here, at the ABI boundary, so the two failure modes reach /// the host as different codes without changing that signature. /// /// # Safety /// /// `ptr` and `len` must describe a byte range that lies entirely within /// this module's linear memory and is not mutated for the duration of /// this call. (Checked by `in_bounds` before any slice is constructed — /// this safety requirement covers what that check cannot see, such as /// concurrent mutation.) #[no_mangle] pub unsafe extern "C" fn docs_core_verify_snapshot(handle: u32, ptr: u32, len: u32) -> i32 { if !in_bounds(ptr, len) { return ERR_INVALID_LENGTH; } let candidate = std::slice::from_raw_parts(ptr as *const u8, len as usize); match get_doc(handle) { None => ERR_NO_DOC, // stale/unknown handle, not a mismatch verdict Some(doc) => { if yrs::Update::decode_v1(candidate).is_err() { return ERR_DECODE; } // The verifier's throwaway document takes a fixed guid and // client id rather than generating any: entropy inside the // core is banned (clippy disallowed-methods), and this // document is discarded before the call returns, so a fixed // pair is not merely acceptable but correct. if verify_snapshot(&doc, candidate, "docs-core-verify", 1) { 0 } else { 1 } } } }