diff --git a/packages/cli-rs/crates/plugin-abi/src/lib.rs b/packages/cli-rs/crates/plugin-abi/src/lib.rs index c310e89e2d6..f21458cd3c9 100644 --- a/packages/cli-rs/crates/plugin-abi/src/lib.rs +++ b/packages/cli-rs/crates/plugin-abi/src/lib.rs @@ -12,6 +12,8 @@ //! - [`PluginApi`] and [`HostApi`] start with their own size and version. New entries are only ever added at the //! end, and each new entry is optional (an `Option` of a function, null when absent). A reader treats entries //! past the other side's size as absent, so a plugin built against an older minor version loads and works. +//! Every callback is an `Option` of a function, which has the layout of a nullable C function pointer, so a +//! null from C code is checked rather than called; the host refuses a plugin that leaves a required one null. //! - JSON payloads only gain optional fields, and readers ignore fields they do not know. //! - A newer plugin on an older host uses what the host offers: the host answers an unknown [`HostRequest`] with an //! error, and a plugin that cannot work without a newer host sets [`PluginApi::requires_minor`], which the host @@ -117,10 +119,11 @@ pub struct HostApi { pub major: u32, pub minor: u32, pub ctx: *mut c_void, - /// Handles a [`HostRequest`] and writes the JSON result into `out`. - pub call: unsafe extern "C" fn(ctx: *mut c_void, request: Bytes, out: *mut Owned) -> i32, + /// Handles a [`HostRequest`] and writes the JSON result into `out`. A plugin treats a null entry, or a null + /// `free`, as a host that answers every request with an error. + pub call: Option i32>, /// Frees a buffer `call` wrote. - pub free: unsafe extern "C" fn(owned: Owned), + pub free: Option, // 1.2 /// Whether the page theme is dark ([`THEME_DARK`]) or light ([`THEME_LIGHT`]), as TS plugins read /// `api.themeMode`. @@ -140,8 +143,8 @@ pub struct HostApiV1_1 { pub major: u32, pub minor: u32, pub ctx: *mut c_void, - pub call: unsafe extern "C" fn(*mut c_void, Bytes, *mut Owned) -> i32, - pub free: unsafe extern "C" fn(Owned), + pub call: Option i32>, + pub free: Option, } /// Dark or light, from [`Host::theme_mode`]. @@ -163,14 +166,16 @@ pub struct PluginApi { /// The oldest host minor version the plugin works with; 0 for any. pub requires_minor: u32, /// Runs the plugin's setup with `options` (the JSON of its `plugins` entry's options, or empty). On [`OK`] it - /// sets `instance` and writes the [`Manifest`] JSON into `out`. - pub create: + /// sets `instance` and writes the [`Manifest`] JSON into `out`. Required: the host refuses a null entry. + pub create: Option< unsafe extern "C" fn(host: *const HostApi, options: Bytes, instance: *mut *mut c_void, out: *mut Owned) -> i32, - /// Handles a [`Request`] and writes the JSON result into `out`. - pub call: unsafe extern "C" fn(instance: *mut c_void, request: Bytes, out: *mut Owned) -> i32, - pub destroy: unsafe extern "C" fn(instance: *mut c_void), - /// Frees a buffer `create` or `call` wrote. - pub free: unsafe extern "C" fn(owned: Owned), + >, + /// Handles a [`Request`] and writes the JSON result into `out`. Required. + pub call: Option i32>, + /// Destroys an instance. Optional: a plugin without per-instance state leaves it null. + pub destroy: Option, + /// Frees a buffer `create`, `call`, or `describe` wrote. Required. + pub free: Option, // 1.1 /// Writes the plugin's [`Metadata`] JSON into `out`. pub describe: Option i32>, @@ -185,10 +190,10 @@ pub struct PluginApiV1_0 { pub major: u32, pub minor: u32, pub requires_minor: u32, - pub create: unsafe extern "C" fn(*const HostApi, Bytes, *mut *mut c_void, *mut Owned) -> i32, - pub call: unsafe extern "C" fn(*mut c_void, Bytes, *mut Owned) -> i32, - pub destroy: unsafe extern "C" fn(*mut c_void), - pub free: unsafe extern "C" fn(Owned), + pub create: Option i32>, + pub call: Option i32>, + pub destroy: Option, + pub free: Option, } /// What [`PluginApi::describe`] returns (1.1). @@ -358,11 +363,15 @@ impl Host { let json = serde_json::to_vec(request).map_err(|error| error.to_string())?; let mut out = Owned::EMPTY; // SAFETY: the host keeps `api` alive until it destroys the instance this handle belongs to. + let api = unsafe { self.api.as_ref() }.ok_or("no host")?; + let (Some(call), Some(free)) = (api.call, api.free) else { + return Err("the host takes no requests".to_owned()); + }; + // SAFETY: `call` writes `out`, which `free` takes back. let (status, bytes) = unsafe { - let api = &*self.api; - let status = (api.call)(api.ctx, Bytes::new(&json), &mut out); + let status = call(api.ctx, Bytes::new(&json), &mut out); let bytes = out.to_vec(); - (api.free)(out); + free(out); (status, bytes) }; match status { @@ -400,7 +409,7 @@ impl Host { pub fn theme_mode(&self) -> Option { // SAFETY: the host keeps `api` alive until it destroys the instance; `size` says which entries it has. let mode = unsafe { - let api = &*self.api; + let api = self.api.as_ref()?; let end = std::mem::offset_of!(HostApi, theme_mode) + size_of::>(); if api.size < end { return None; @@ -520,10 +529,10 @@ macro_rules! export_plugin { major: $major, minor: $minor, requires_minor: $requires, - create, - call: $crate::runtime::call, - destroy: $crate::runtime::destroy, - free: $crate::runtime::free, + create: Some(create), + call: Some($crate::runtime::call), + destroy: Some($crate::runtime::destroy), + free: Some($crate::runtime::free), describe: Some(describe), }; &API @@ -539,10 +548,10 @@ macro_rules! export_plugin { major: 1, minor: 0, requires_minor: 0, - create, - call: $crate::runtime::call, - destroy: $crate::runtime::destroy, - free: $crate::runtime::free, + create: Some(create), + call: Some($crate::runtime::call), + destroy: Some($crate::runtime::destroy), + free: Some($crate::runtime::free), }; (&API as *const $crate::PluginApiV1_0).cast() } @@ -591,9 +600,12 @@ pub mod runtime { routes: Vec::new(), commands: Vec::new(), }; + if instance.is_null() { + return Err("no instance pointer".to_owned()); + } setup(&mut registered)?; let manifest = serde_json::to_vec(®istered.manifest).map_err(|error| error.to_string())?; - // SAFETY: `instance` is valid for writes during the call. + // SAFETY: `instance` is non-null and valid for writes during the call. unsafe { *instance = Box::into_raw(Box::new(registered)).cast() }; Ok(manifest) }) @@ -609,11 +621,12 @@ pub mod runtime { } /// # Safety - /// `instance` must come from [`create`] and not be destroyed. + /// `instance` must come from [`create`] and not be destroyed, or be null. pub unsafe extern "C" fn call(instance: *mut c_void, request: Bytes, out: *mut Owned) -> i32 { // SAFETY: as documented. - let (setup, request) = unsafe { (&*instance.cast::(), request.as_slice()) }; + let (setup, request) = unsafe { (instance.cast::().as_ref(), request.as_slice()) }; guard(out, || { + let setup = setup.ok_or("no instance")?; let request: Request = serde_json::from_slice(request).map_err(|error| error.to_string())?; let value = setup.handle(request)?; serde_json::to_vec(&value).map_err(|error| error.to_string()) @@ -621,8 +634,11 @@ pub mod runtime { } /// # Safety - /// `instance` must come from [`create`] and not be destroyed. + /// `instance` must come from [`create`] and not be destroyed, or be null. pub unsafe extern "C" fn destroy(instance: *mut c_void) { + if instance.is_null() { + return; + } // SAFETY: as documented. let setup = unsafe { Box::from_raw(instance.cast::()) }; let _ = catch_unwind(AssertUnwindSafe(move || drop(setup))); @@ -635,13 +651,18 @@ pub mod runtime { drop(unsafe { owned.into_vec() }); } + /// Runs `f` and writes its result into `out`. With a null `out` nothing runs: there is nowhere to put the + /// result. fn guard(out: *mut Owned, f: impl FnOnce() -> Result, String>) -> i32 { + if out.is_null() { + return ERROR; + } let (status, bytes) = match catch_unwind(AssertUnwindSafe(f)) { Ok(Ok(bytes)) => (OK, bytes), Ok(Err(error)) => (ERROR, error.into_bytes()), Err(panic) => (PANIC, panic_message(&*panic).into_bytes()), }; - // SAFETY: `out` is valid for writes during the call. + // SAFETY: `out` is non-null and valid for writes during the call. unsafe { *out = Owned::from_vec(bytes) }; status } @@ -676,6 +697,7 @@ mod tests { #[test] fn the_theme_mode_is_read_only_when_the_host_offers_it() { let ctx = std::ptr::null_mut(); + let (call, free) = (Some(call as _), Some(free as _)); let current = HostApi { size: size_of::(), major: 1, minor: 2, ctx, call, free, theme_mode: Some(light) }; assert_eq!(Host { api: ¤t }.theme_mode(), Some(ThemeMode::Light)); @@ -684,4 +706,51 @@ mod tests { let old = HostApiV1_1 { size: size_of::(), major: 1, minor: 1, ctx, call, free }; assert_eq!(Host { api: std::ptr::from_ref(&old).cast() }.theme_mode(), None); } + + // Expected: a C host that passes no table, or leaves `call` or `free` null, gets errors, not a jump to address 0. + #[test] + fn a_null_host_or_host_callback_is_an_error() { + let host = Host { api: std::ptr::null() }; + assert_eq!(host.storage_get("count"), None); + assert_eq!(host.storage_set("count", "{}"), Err("no host".to_owned())); + assert_eq!(host.theme_mode(), None); + let ctx = std::ptr::null_mut(); + let api = + HostApi { size: size_of::(), major: 1, minor: 2, ctx, call: None, free: None, theme_mode: None }; + assert_eq!(Host { api: &api }.storage_set("count", "{}"), Err("the host takes no requests".to_owned())); + let api = HostApi { call: Some(call), ..api }; + assert_eq!(Host { api: &api }.storage_set("count", "{}"), Err("the host takes no requests".to_owned())); + } + + // Expected: the shims answer a null instance with an error, ignore a null `out` or a null `destroy`, and never + // dereference either. + #[test] + fn the_shims_check_null_pointers() { + let request = serde_json::to_vec(&Request::Route { name: "x".to_owned() }).unwrap(); + let mut out = Owned::EMPTY; + // SAFETY: null pointers are what is under test; `out` is freed by the same library. + unsafe { + assert_eq!(runtime::call(std::ptr::null_mut(), Bytes::new(&request), &mut out), ERROR); + assert_eq!(out.to_vec(), b"no instance"); + runtime::free(out); + assert_eq!(runtime::call(std::ptr::null_mut(), Bytes::new(&request), std::ptr::null_mut()), ERROR); + runtime::destroy(std::ptr::null_mut()); + let mut out = Owned::EMPTY; + let status = + runtime::create("x", |_| Ok(()), std::ptr::null(), Bytes::new(b""), std::ptr::null_mut(), &mut out); + assert_eq!((status, out.to_vec()), (ERROR, b"no instance pointer".to_vec())); + runtime::free(out); + let mut instance = std::ptr::null_mut(); + let status = runtime::create( + "x", + |_| Ok(()), + std::ptr::null(), + Bytes::new(b""), + &mut instance, + std::ptr::null_mut(), + ); + assert_eq!(status, ERROR); + assert!(instance.is_null()); + } + } } diff --git a/packages/cli-rs/crates/plugin/src/loader/native.rs b/packages/cli-rs/crates/plugin/src/loader/native.rs index d11a6f4de68..5dd1721f396 100644 --- a/packages/cli-rs/crates/plugin/src/loader/native.rs +++ b/packages/cli-rs/crates/plugin/src/loader/native.rs @@ -115,7 +115,7 @@ struct Library { minor: u32, create: unsafe extern "C" fn(*const HostApi, Bytes, *mut *mut c_void, *mut Owned) -> i32, call: unsafe extern "C" fn(*mut c_void, Bytes, *mut Owned) -> i32, - destroy: unsafe extern "C" fn(*mut c_void), + destroy: Option, free: unsafe extern "C" fn(Owned), describe: Option i32>, } @@ -136,18 +136,27 @@ impl Library { let entry = unsafe { library.get::(abi::ENTRY.as_bytes()) } .map_err(|_| format!("not an opencode-rs plugin: no `{}` symbol", abi::ENTRY))?; // SAFETY: as above; the table it returns lives as long as the library. - let api = unsafe { entry() }; + let opened = Self::from_table(unsafe { entry() })?; + std::mem::forget(library); + Ok(opened) + } + + /// Checks the table `api` points to and takes its entries. Nothing past the `size` it declares is read. + fn from_table(api: *const PluginApi) -> Result { if api.is_null() { return Err(format!("`{}` returned no table", abi::ENTRY)); } - // SAFETY: every table of any version starts with `size`, `major`, and `minor`. - let (size, major, minor) = unsafe { - ( - std::ptr::addr_of!((*api).size).read(), - std::ptr::addr_of!((*api).major).read(), - std::ptr::addr_of!((*api).minor).read(), - ) - }; + if !api.is_aligned() { + return Err("plugin table is not aligned".to_owned()); + } + // SAFETY: every table of any version starts with `size`, and `api` is aligned and non-null. + let size = unsafe { std::ptr::addr_of!((*api).size).read() }; + if size < offset_of!(PluginApiV1_0, requires_minor) { + return Err(format!("plugin table is {size} bytes, shorter than its version header")); + } + // SAFETY: `size` covers `major` and `minor`. + let (major, minor) = + unsafe { (std::ptr::addr_of!((*api).major).read(), std::ptr::addr_of!((*api).minor).read()) }; if major != ABI_MAJOR { return Err(format!( "plugin ABI {major}.{minor} is not supported: this opencode-rs loads ABI {ABI_MAJOR}.x plugins \ @@ -157,7 +166,7 @@ impl Library { if size < size_of::() { return Err(format!("plugin table is {size} bytes, shorter than the ABI {ABI_MAJOR}.0 core")); } - // SAFETY: the 1.0 core is within `size`. + // SAFETY: the 1.0 core is within `size`; its callbacks are nullable. let core = unsafe { &*api.cast::() }; if core.requires_minor > HOST_MINOR { return Err(format!( @@ -166,14 +175,15 @@ impl Library { core.requires_minor )); } + let required = |name: &str| format!("plugin table has a null `{name}` callback"); + let create = core.create.ok_or_else(|| required("create"))?; + let call = core.call.ok_or_else(|| required("call"))?; + let free = core.free.ok_or_else(|| required("free"))?; let describe = has:: i32>>(size, offset_of!(PluginApi, describe)) // SAFETY: `size` covers the entry. .then(|| unsafe { std::ptr::addr_of!((*api).describe).read() }) .flatten(); - let opened = - Self { minor, create: core.create, call: core.call, destroy: core.destroy, free: core.free, describe }; - std::mem::forget(library); - Ok(opened) + Ok(Self { minor, create, call, destroy: core.destroy, free, describe }) } /// The plugin's version, when it has `describe` (1.1). @@ -230,8 +240,8 @@ impl Instance { major: ABI_MAJOR, minor: HOST_MINOR, ctx: std::ptr::from_ref::>>(&ctx).cast_mut().cast(), - call: host_call::, - free: host_free, + call: Some(host_call::), + free: Some(host_free), theme_mode: Some(host_theme_mode::), }); let mut handle = std::ptr::null_mut(); @@ -289,16 +299,23 @@ impl Instance { impl Drop for Instance { fn drop(&mut self) { - // SAFETY: `handle` came from `create` and is destroyed once; the plugin catches its own panics. - unsafe { (self.library.destroy)(self.handle) }; + if let Some(destroy) = self.library.destroy { + // SAFETY: `handle` came from `create` and is destroyed once; the plugin catches its own panics. + unsafe { destroy(self.handle) }; + } } } /// The host's side of [`HostApi::call`]. Catches the host's panics. unsafe extern "C" fn host_call(ctx: *mut c_void, request: Bytes, out: *mut Owned) -> i32 { - // SAFETY: `ctx` is the `RefCell>` this instance was created with; `request` is valid for the call. - let (ctx, request) = unsafe { (&*ctx.cast::>>(), request.as_slice()) }; + if out.is_null() { + return abi::ERROR; + } + // SAFETY: `ctx` is the `RefCell>` this instance was created with, or null; `request` is valid for the + // call. + let (ctx, request) = unsafe { (ctx.cast::>>().as_ref(), request.as_slice()) }; let result = catch_unwind(AssertUnwindSafe(|| { + let ctx = ctx.ok_or("no host context")?; let request: HostRequest = serde_json::from_slice(request) .map_err(|error| format!("unsupported host request (host ABI {ABI_MAJOR}.{HOST_MINOR}): {error}"))?; let mut ctx = ctx.try_borrow_mut().map_err(|_| "the host is busy".to_owned())?; @@ -316,9 +333,9 @@ unsafe extern "C" fn host_call(ctx: *mut c_void, request: Bytes, out: * /// The host's side of [`HostApi::theme_mode`]. A host that is gone or panics answers dark. unsafe extern "C" fn host_theme_mode(ctx: *mut c_void) -> u32 { - // SAFETY: `ctx` is the `RefCell>` this instance was created with. - let ctx = unsafe { &*ctx.cast::>>() }; - let host = ctx.try_borrow().ok().and_then(|ctx| ctx.host.upgrade()); + // SAFETY: `ctx` is the `RefCell>` this instance was created with, or null. + let ctx = unsafe { ctx.cast::>>().as_ref() }; + let host = ctx.and_then(|ctx| ctx.try_borrow().ok()).and_then(|ctx| ctx.host.upgrade()); let light = catch_unwind(AssertUnwindSafe(|| host.is_some_and(|host| host.theme_mode() == ThemeMode::Light))); if light.unwrap_or(false) { abi::THEME_LIGHT } else { abi::THEME_DARK } } diff --git a/packages/cli-rs/crates/plugin/src/loader/native/tests.rs b/packages/cli-rs/crates/plugin/src/loader/native/tests.rs index 59ec2ab58d6..d3aad05ddb3 100644 --- a/packages/cli-rs/crates/plugin/src/loader/native/tests.rs +++ b/packages/cli-rs/crates/plugin/src/loader/native/tests.rs @@ -205,3 +205,38 @@ fn the_loader_reloads_a_rebuilt_library() { assert!(screen.contains("SAMPLE v2 HI"), "{screen}"); assert_eq!(registry.entries().len(), 1); } + +// Expected: a table from a C plugin is refused, without reading past its declared size or through a null or +// misaligned pointer, when it is too short for its header, misaligned, or leaves a required callback null. A null +// `destroy` is allowed. +#[test] +fn a_malformed_table_is_refused_without_reading_it() { + let refused = |api: *const PluginApi| Library::from_table(api).err().unwrap(); + assert_eq!(refused(std::ptr::null()), "`opencode_plugin_v1` returned no table"); + let short: [usize; 1] = [size_of::()]; + assert_eq!(refused(short.as_ptr().cast()), "plugin table is 8 bytes, shorter than its version header"); + let bytes = [0u64; 16]; + assert_eq!(refused(bytes.as_ptr().cast::().wrapping_add(1).cast()), "plugin table is not aligned"); + let null = PluginApi { + size: size_of::(), + major: 1, + minor: 0, + requires_minor: 0, + create: None, + call: None, + destroy: None, + free: None, + describe: None, + }; + assert_eq!(refused(&null), "plugin table has a null `create` callback"); + unsafe extern "C" fn create(_: *const HostApi, _: Bytes, _: *mut *mut c_void, _: *mut Owned) -> i32 { + abi::ERROR + } + let api = PluginApi { create: Some(create), ..null }; + assert_eq!(refused(&api), "plugin table has a null `call` callback"); + let api = PluginApi { call: Some(abi::runtime::call), ..api }; + assert_eq!(refused(&api), "plugin table has a null `free` callback"); + let api = PluginApi { free: Some(abi::runtime::free), ..api }; + let library = Library::from_table(&api).unwrap(); + assert!(library.destroy.is_none() && library.describe.is_none()); +}