diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 049050ac6..72a73641a 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -7,7 +7,6 @@ publish = false [dependencies] allocator-api2 = { workspace = true, features = ["alloc"] } -wincode = { workspace = true } bumpalo = { workspace = true, features = ["allocator-api2", "collections"] } derive_more = { workspace = true, features = ["debug"] } vt_materialized_artifact = { workspace = true } @@ -51,6 +50,7 @@ fspy_detours_sys = { workspace = true } fspy_preload_windows = { workspace = true } ntapi = { workspace = true } winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi"] } +wincode = { workspace = true } winsafe = { workspace = true, features = ["kernel"] } [target.'cfg(target_os = "macos")'.dev-dependencies] diff --git a/crates/fspy/src/ipc.rs b/crates/fspy/src/ipc.rs index 6d15bf436..691157d9d 100644 --- a/crates/fspy/src/ipc.rs +++ b/crates/fspy/src/ipc.rs @@ -1,8 +1,5 @@ use allocator_api2::alloc::Global; -use fspy_shared::ipc::{ - PathAccess, - channel::{FrameReader, Receiver}, -}; +use fspy_shared::ipc::{AccessReader, AccessReceiver, PathAccess}; use crate::error::TrackingIncomplete; @@ -35,10 +32,10 @@ pub fn shm_capacity() -> usize { /// The path accesses a run reported through the IPC channel. pub struct ChannelAccesses { - frames: FrameReader, + reader: AccessReader, } -impl TryFrom> for ChannelAccesses { +impl TryFrom> for ChannelAccesses { type Error = TrackingIncomplete; /// Closes the channel and takes every record it collected. @@ -53,16 +50,13 @@ impl TryFrom> for ChannelAccesses { /// [`TrackingIncomplete`] when a tracked process could not record /// something it went on to do. What did arrive is then a subset of /// what the run really touched, so none of it is handed back. - fn try_from(receiver: Receiver) -> Result { - Ok(Self { frames: receiver.close().map_err(|_| TrackingIncomplete)? }) + fn try_from(receiver: AccessReceiver) -> Result { + Ok(Self { reader: receiver.close().map_err(|_| TrackingIncomplete)? }) } } impl ChannelAccesses { pub fn iter_path_accesses(&self) -> impl Iterator> { - self.frames.iter().map(|frame| { - wincode::deserialize_exact(frame) - .expect("committed frames are complete under the channel protocol") - }) + self.reader.iter() } } diff --git a/crates/fspy/src/unix/mod.rs b/crates/fspy/src/unix/mod.rs index e0e850037..4f05b394a 100644 --- a/crates/fspy/src/unix/mod.rs +++ b/crates/fspy/src/unix/mod.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use fspy_seccomp_unotify::supervisor::supervise; #[cfg(not(target_env = "musl"))] use fspy_shared::ipc::IpcStr; -use fspy_shared::ipc::{PathAccess, channel::channel}; +use fspy_shared::ipc::{PathAccess, access_channel}; use fspy_shared_unix::{ exec::ExecResolveConfig, payload::{Payload, encode_payload}, @@ -88,8 +88,9 @@ impl SpyImpl { mut command: Command, cancellation_token: CancellationToken, ) -> Result { - let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) - .map_err(SpawnError::ChannelCreation)?; + let ipc_receiver = + access_channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) + .map_err(SpawnError::ChannelCreation)?; // The supervisor records the accesses it intercepts into the same // channel as the preload library. diff --git a/crates/fspy/src/unix/syscall_handler/mod.rs b/crates/fspy/src/unix/syscall_handler/mod.rs index d55ce8fbb..845a3536d 100644 --- a/crates/fspy/src/unix/syscall_handler/mod.rs +++ b/crates/fspy/src/unix/syscall_handler/mod.rs @@ -17,7 +17,7 @@ use fspy_seccomp_unotify::{ impl_handler, supervisor::handler::arg::{CStrPtr, Caller, Fd}, }; -use fspy_shared::ipc::{AccessMode, PathAccess, channel::Sender}; +use fspy_shared::ipc::{AccessMode, AccessSender, PathAccess}; const PATH_MAX: usize = libc::PATH_MAX as usize; @@ -27,12 +27,12 @@ const PATH_MAX: usize = libc::PATH_MAX as usize; /// every record is published before the access it describes, as the channel /// requires of its senders. pub struct SyscallHandler { - ipc_sender: Arc, + ipc_sender: Arc, path_read_buf: [u8; PATH_MAX], } impl SyscallHandler { - pub const fn new(ipc_sender: Arc) -> Self { + pub const fn new(ipc_sender: Arc) -> Self { Self { ipc_sender, path_read_buf: [0; PATH_MAX] } } diff --git a/crates/fspy/src/windows/mod.rs b/crates/fspy/src/windows/mod.rs index 1f4dd14f0..b50ef920c 100644 --- a/crates/fspy/src/windows/mod.rs +++ b/crates/fspy/src/windows/mod.rs @@ -10,7 +10,7 @@ use std::{ use fspy_detours_sys::{DetourCopyPayloadToProcess, DetourUpdateProcessWithDll}; use fspy_shared::{ - ipc::{PathAccess, channel::channel}, + ipc::{PathAccess, access_channel}, windows::{PAYLOAD_ID, Payload}, }; use futures_util::FutureExt; @@ -89,7 +89,7 @@ impl SpyImpl { let ansi_dll_path_with_nul = &self.ansi_dll_path_with_nul; command.env("FSPY", "1"); - let receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) + let receiver = access_channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) .map_err(SpawnError::ChannelCreation)?; let payload = Payload { diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index c3e95b94b..6efcf34fc 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -14,10 +14,7 @@ use std::{ use allocator_api2::alloc::Global; use fspy_seccomp_unotify::payload::SeccompPayload; -use fspy_shared::ipc::{ - IpcStr, - channel::{Receiver, RecordsLost, channel}, -}; +use fspy_shared::ipc::{AccessCloseError, AccessReceiver, IpcStr, access_channel}; use fspy_shared_unix::payload::{Payload, encode_payload}; use crate::test_utils::test_bin_path; @@ -30,8 +27,8 @@ const PRELOAD_CDYLIB: &str = env!("CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); /// Clears `command`'s environment and preloads fspy into it with a seccomp /// payload whose install always fails. Returns the channel the preload /// reports to. -fn preload_with_failing_seccomp(command: &mut Command) -> Receiver { - let receiver = channel(1 << 30, Global).unwrap(); +fn preload_with_failing_seccomp(command: &mut Command) -> AccessReceiver { + let receiver = access_channel(1 << 30, Global).unwrap(); { let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); let payload = Payload { @@ -70,7 +67,7 @@ fn static_binary_runs_untracked_when_injection_fails() { String::from_utf8_lossy(&output.stderr) ); - let Err(RecordsLost) = receiver.close() else { + let Err(AccessCloseError::Reported) = receiver.close() else { panic!("the channel did not report the untracked exec"); }; } @@ -98,7 +95,7 @@ fn execvp_fallback_keeps_path_search() { String::from_utf8_lossy(&output.stderr) ); - let Err(RecordsLost) = receiver.close() else { + let Err(AccessCloseError::Reported) = receiver.close() else { panic!("the channel did not report the untracked exec"); }; } diff --git a/crates/fspy_client_unix/src/lib.rs b/crates/fspy_client_unix/src/lib.rs index d51c90f10..056264f6a 100644 --- a/crates/fspy_client_unix/src/lib.rs +++ b/crates/fspy_client_unix/src/lib.rs @@ -12,7 +12,7 @@ use std::{ffi::OsStr, fmt::Debug, os::unix::ffi::OsStrExt as _, path::Path}; use allocator_api2::alloc::Allocator; use convert::{ToAbsolutePath, ToAccessMode}; -use fspy_shared::ipc::{AccessMode, channel::Sender}; +use fspy_shared::ipc::{AccessMode, AccessSender}; use fspy_shared_unix::{ exec::ExecResolveConfig, payload::{EncodedPayload, decode_payload_from_env}, @@ -22,7 +22,7 @@ use raw_exec::RawExec; pub struct Client<'a> { encoded_payload: EncodedPayload<'a>, - ipc_sender: Option, + ipc_sender: Option, } // Seals the view-only design: the client holds views of leaked memory and @@ -62,10 +62,10 @@ impl<'a> Client<'a> { ) -> Self { let encoded_payload = decode_payload_from_env(envs, allocator.clone()).unwrap(); - // `None` when the channel is already over, which happens when this - // process starts after the root target exited. Nothing is said - // about it: a preload library writing to the traced process's - // stderr corrupts whatever that process is printing. + // `None` when the channel is already closed — because the root target + // exited, the channel overflowed, or an earlier process aborted + // tracking. Nothing is said about it: a preload library writing to the + // traced process's stderr corrupts whatever that process is printing. let ipc_sender = encoded_payload.payload.ipc_channel_conf.sender(allocator); Self { encoded_payload, ipc_sender } diff --git a/crates/fspy_preload_windows/src/windows/client.rs b/crates/fspy_preload_windows/src/windows/client.rs index 7dde59c76..6c6eaba64 100644 --- a/crates/fspy_preload_windows/src/windows/client.rs +++ b/crates/fspy_preload_windows/src/windows/client.rs @@ -3,7 +3,7 @@ use std::{cell::SyncUnsafeCell, ffi::CStr, mem::MaybeUninit}; use allocator_api2::alloc::Allocator; use fspy_detours_sys::DetourCopyPayloadToProcess; use fspy_shared::{ - ipc::{PathAccess, channel::Sender}, + ipc::{AccessSender, PathAccess}, windows::{PAYLOAD_ID, Payload}, }; use winapi::{shared::minwindef::BOOL, um::winnt::HANDLE}; @@ -11,17 +11,17 @@ use winapi::{shared::minwindef::BOOL, um::winnt::HANDLE}; pub struct Client<'a> { payload: Payload<'a>, payload_bytes: &'a [u8], - ipc_sender: Option, + ipc_sender: Option, } impl<'a> Client<'a> { pub fn from_payload_bytes(payload_bytes: &'a [u8], allocator: impl Allocator) -> Self { let payload: Payload<'a> = wincode::deserialize_exact(payload_bytes).unwrap(); - // `None` when the channel is already over, which happens when this - // process starts after the root target exited. Nothing is said - // about it: a detours DLL writing to the traced process's stderr - // corrupts whatever that process is printing. + // `None` when the channel is already closed — because the root target + // exited, the channel overflowed, or an earlier process aborted + // tracking. Nothing is said about it: a detours DLL writing to the + // traced process's stderr corrupts whatever that process is printing. let ipc_sender = payload.channel_conf.sender(allocator); Self { payload, payload_bytes, ipc_sender } diff --git a/crates/fspy_shared/src/ipc/channel/mod.rs b/crates/fspy_shared/src/ipc/channel/mod.rs index e5026cdd3..362b357c8 100644 --- a/crates/fspy_shared/src/ipc/channel/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/mod.rs @@ -1,15 +1,18 @@ -//! Fast mpsc IPC channel implementation based on shared memory. +//! Fast typed mpsc IPC channel implementation based on shared memory. //! //! The channel is crash-tolerant and nonblocking on both ends: any sender //! process may die (or keep running) at any point without preventing the -//! receiver from closing the channel and reading every committed frame. See -//! the `shm_io` module for the underlying protocol. +//! receiver from closing the channel and reading every committed record. +//! Both serialization and deserialization use `wincode` and are owned by this +//! module, keyed by a [`ChannelProtocol`] type so senders and receivers agree +//! on the wire schema at compile time. See the `shm_io` module for the +//! underlying raw-frame protocol. mod shm_io; -use core::num::NonZeroUsize; +use core::{fmt, marker::PhantomData, mem::MaybeUninit, num::NonZeroUsize}; #[cfg(not(target_os = "none"))] -use std::{env::temp_dir, ffi::OsStr, io, path::PathBuf}; +use std::{env::temp_dir, ffi::OsStr, io, iter::FusedIterator, path::PathBuf}; use allocator_api2::alloc::Allocator; #[cfg(not(target_os = "none"))] @@ -22,17 +25,29 @@ use fspy_shm::ShmHandle; use shm_io::ShmWriter; #[cfg(not(target_os = "none"))] use shm_io::{SealError, ShmReader}; - -/// Reads the committed frames of a sealed channel; borrows the shared -/// mapping, which stays alive (and mapped) until this value drops. -#[cfg(not(target_os = "none"))] -pub type FrameReader = shm_io::ShmReader; #[cfg(not(target_os = "none"))] use uuid::Uuid; -use wincode::{SchemaRead, SchemaWrite, Serialize as _, config::DefaultConfig}; +use wincode::{ + SchemaRead, SchemaWrite, Serialize as _, + config::{Config, DefaultConfig}, + error::{ReadResult, WriteResult}, + io::{Reader as WincodeReader, Writer as WincodeWriter}, +}; use super::IpcStr; +/// Wire schema for a typed IPC channel. +/// +/// [`Self::Record`] may borrow from the channel's shared mapping on the +/// receiving end (zero-copy) and from caller stack or arena buffers on the +/// sending end (`no_std`-compatible, zero heap allocation). +pub trait ChannelProtocol { + /// Record type carried through [`Sender::send`] and yielded by + /// [`RecordReader::iter`]. + type Record<'a>: SchemaWrite> + + SchemaRead<'a, DefaultConfig, Dst = Self::Record<'a>>; +} + /// Prefix of shared-memory backing file names inside the system temporary /// directory. /// @@ -51,22 +66,68 @@ const SHM_BACKING_PREFIX: &str = "vite-task-fspy-"; /// slots are claimed, so a channel pays only for the ones it uses. const SLOTS: usize = 1 << 26; -/// Serializable configuration to create channel senders. +/// Serializable configuration to create channel senders for protocol `P`. /// /// A conf is a view: it borrows the path the [`Receiver`] owns (or, in a /// receiving process, the payload bytes it was deserialized from), so /// materializing and serializing one allocates nothing. -#[derive(SchemaWrite, SchemaRead, Clone, Copy, Debug)] -pub struct ChannelConf<'a> { +pub struct ChannelConf<'a, P> { shm_id: &'a IpcStr, + _protocol: PhantomData P>, +} + +impl

Clone for ChannelConf<'_, P> { + fn clone(&self) -> Self { + *self + } +} + +impl

Copy for ChannelConf<'_, P> {} + +impl

fmt::Debug for ChannelConf<'_, P> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ChannelConf").field("shm_id", &self.shm_id).finish() + } +} + +// SAFETY: Delegates directly to `&IpcStr`'s `SchemaWrite` impl; `PhantomData` +// contributes zero bytes to the wire format. +unsafe impl SchemaWrite for ChannelConf<'_, P> { + type Src = Self; + + fn size_of(src: &Self::Src) -> WriteResult { + <&IpcStr as SchemaWrite>::size_of(&src.shm_id) + } + + fn write(writer: impl WincodeWriter, src: &Self::Src) -> WriteResult<()> { + <&IpcStr as SchemaWrite>::write(writer, &src.shm_id) + } } -/// Creates a mpsc IPC channel and returns its receiver. [`Receiver::conf`] +// SAFETY: Delegates directly to `&IpcStr`'s `SchemaRead` impl; `dst` is fully +// initialized on `Ok`. +unsafe impl<'de, C: Config, P> SchemaRead<'de, C> for ChannelConf<'de, P> { + type Dst = Self; + + fn read( + mut reader: impl WincodeReader<'de>, + dst: &mut MaybeUninit, + ) -> ReadResult<()> { + let shm_id: &'de IpcStr = <&IpcStr as SchemaRead<'de, C>>::get(&mut reader)?; + dst.write(Self { shm_id, _protocol: PhantomData }); + Ok(()) + } +} + +/// Creates a typed mpsc IPC channel and returns its receiver. [`Receiver::conf`] /// derives the serializable configuration that other processes use to create /// senders. #[expect(clippy::missing_errors_doc, reason = "non-vt crate: cannot use vt_str/vt_path types")] #[cfg(not(target_os = "none"))] -pub fn channel(capacity: usize, allocator: A) -> io::Result> { +pub fn channel( + capacity: usize, + allocator: A, +) -> io::Result> { let shm_c_path = os_c_string(shm_backing_path()?.as_os_str(), allocator)?; let handle = fspy_shm::create(shm_c_path.as_c_str().as_thin(), capacity).map_err(shm_error_to_io)?; @@ -86,7 +147,7 @@ pub fn channel(capacity: usize, allocator: A) -> io::Result Drop for ShmKeeper { } } -impl ChannelConf<'_> { - /// Creates a sender, or `None` when the channel is already over. +impl ChannelConf<'_, P> { + /// Creates a sender, or `None` when the channel is already closed. /// - /// Never blocks. `None` means the receiver removed the backing file, - /// or sealed the region before removing it and this call caught the - /// gate in between. Either way whatever the caller does next happens - /// past the receiver's boundary, so recording nothing loses nothing. + /// Never blocks. `None` means the receiver removed the backing file, or + /// any close gate (receiver seal, capacity overflow, or prior writer + /// abort) is already set. In all cases further records would either land + /// past the receiver's boundary or into a channel the receiver will reject, + /// so attaching is unnecessary. /// /// # Panics /// /// When the channel is there but cannot be attached to: its path is /// unreadable, the file refuses to open or map, or the region cannot /// hold the protocol. A process with no sender has no way to tell the - /// receiver it recorded nothing, and a trace that silently omits every - /// access a process made is worse than no trace, so it stops here. + /// receiver it recorded nothing, so it stops here. #[must_use] - pub fn sender(&self, allocator: A) -> Option { + pub fn sender(&self, allocator: A) -> Option> { // The allocation is transient: the decoded path only has to outlive // the open call below, and dropping it hands the space back to a // bump allocator, whose most recent allocation it is. @@ -218,47 +279,45 @@ impl ChannelConf<'_> { // `shm_io` protocol by every attached process. let writer = unsafe { ShmWriter::new(mapping, SLOTS) } .expect("the shared-memory region cannot hold the channel"); - // The receiver sealed the region but has not removed it yet. + // The channel is already closed (sealed by the receiver, overflowed, + // or aborted by an earlier sender). if writer.is_closed() { return None; } - Some(Sender { writer }) + Some(Sender { writer, _protocol: PhantomData }) } } -pub struct Sender { +pub struct Sender

{ writer: ShmWriter, + _protocol: PhantomData P>, } -impl Sender { - /// Reports that this process went on to perform an operation it could - /// not record, sealing the channel as incomplete. +impl Sender

{ + /// Reports that this sender could not record an operation it is about to + /// perform, aborting the channel so the receiver does not mistake a + /// partial set of records for a complete one. /// - /// Used when a traced process escapes tracing — e.g. a preload that - /// could not install its injection machinery and forwards the operation - /// to the OS untracked. The receiver's close then reports - /// [`RecordsLost`], so the run is treated as untracked rather than - /// cached from a partial trace. + /// Must be called before performing the unrecorded operation. The receiver's + /// close then fails with [`CloseError::Reported`]. pub fn report_loss(&self) { self.writer.abort(); } /// Serializes one record into a committed frame. /// - /// A claim the channel refuses is skipped, because that is all a sender - /// inside an intercepted call can do: the channel has closed, so the - /// record belongs past the receiver's boundary, or the region is full - /// and the failed claim already set the CLOSED gate to say so. + /// A claim the channel refuses is skipped: either the channel has already + /// closed, or the region is full and the failed claim already set the + /// overflow gate so the receiver will reject the trace. /// /// # Panics /// - /// When the record's serialized size disagrees with the bytes it then - /// writes. Nothing the caller passes can cause that, so it is a defect - /// in this crate or its codec, and a trace built on it would be wrong - /// in ways the receiver cannot see. - pub fn send>(&self, value: &T) { - let serialized_size = - T::serialized_size(value).expect("a record cannot report its serialized size"); + /// When the record's serialized size is zero or disagrees with the bytes + /// it writes. Nothing a valid codec produces can cause that, so it + /// indicates a bug in the record schema. + pub fn send(&self, value: &P::Record<'_>) { + let serialized_size = >::serialized_size(value) + .expect("a record cannot report its serialized size"); let frame_size = usize::try_from(serialized_size) .ok() .and_then(NonZeroUsize::new) @@ -267,7 +326,8 @@ impl Sender { return; }; let mut buf: &mut [u8] = &mut frame; - T::serialize_into(&mut buf, value).expect("a record will not serialize into its own frame"); + >::serialize_into(&mut buf, value) + .expect("a record will not serialize into its own frame"); assert!(buf.is_empty(), "a record wrote fewer bytes than the size it reported"); frame.finish(); } @@ -276,24 +336,89 @@ impl Sender { // SAFETY: `Sender` only accesses the shared mapping through the `shm_io` // protocol, which synchronizes concurrent writers and the receiver with // atomic operations; the mapping's address is stable and independently owned. -unsafe impl Send for Sender {} +unsafe impl

Send for Sender

{} // SAFETY: see the `Send` impl; `ShmWriter`'s shared-reference API is // internally synchronized by the protocol. -unsafe impl Sync for Sender {} +unsafe impl

Sync for Sender

{} + +/// Reads the committed records of a sealed channel, deserializing each +/// committed frame on demand straight out of the shared mapping. +/// +/// The shared mapping stays alive (and mapped) until this value drops. +#[cfg(not(target_os = "none"))] +pub struct RecordReader

{ + inner: ShmReader, + _protocol: PhantomData P>, +} + +#[cfg(not(target_os = "none"))] +impl

fmt::Debug for RecordReader

{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RecordReader").field("inner", &self.inner).finish() + } +} + +#[cfg(not(target_os = "none"))] +impl RecordReader

{ + /// Iterates over every committed record in claim order, deserializing + /// directly from the shared mapping without copying. + #[must_use] + pub const fn iter(&self) -> RecordIter<'_, P> { + RecordIter { inner: self.inner.iter(), _protocol: PhantomData } + } +} -/// The unique receiver side of an IPC channel. +/// Iterator over a [`RecordReader`]'s committed records in claim order. +#[cfg(not(target_os = "none"))] +pub struct RecordIter<'a, P> { + inner: shm_io::Iter<'a>, + _protocol: PhantomData P>, +} + +#[cfg(not(target_os = "none"))] +impl<'a, P: ChannelProtocol> Iterator for RecordIter<'a, P> { + type Item = P::Record<'a>; + + fn next(&mut self) -> Option { + let frame = self.inner.next()?; + Some( + wincode::deserialize_exact::>(frame) + .expect("committed frames are complete under the channel protocol"), + ) + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +#[cfg(not(target_os = "none"))] +impl FusedIterator for RecordIter<'_, P> {} + +#[cfg(not(target_os = "none"))] +impl<'a, P: ChannelProtocol> IntoIterator for &'a RecordReader

{ + type IntoIter = RecordIter<'a, P>; + type Item = P::Record<'a>; + + fn into_iter(self) -> RecordIter<'a, P> { + self.iter() + } +} + +/// The unique receiver side of a typed IPC channel. /// /// Holds the shared memory and its backing file alive for as long as senders /// may attach; [`Receiver::close`] (or dropping) removes the backing file. #[cfg(not(target_os = "none"))] -pub struct Receiver { +pub struct Receiver { /// Keeps the shared memory's backing file alive for as long as senders /// may attach. keeper: ShmKeeper, /// Maps the region again for senders in this process. handle: ShmHandle, mapping: Mapping, + _protocol: PhantomData P>, } // SAFETY: `Receiver` only holds the mapping and the handle that maps it; it @@ -301,19 +426,22 @@ pub struct Receiver { // which synchronizes with senders via atomic operations. The mapping's // address is stable and independently owned. #[cfg(not(target_os = "none"))] -unsafe impl Send for Receiver {} +unsafe impl Send for Receiver {} // SAFETY: see the `Send` impl. #[cfg(not(target_os = "none"))] -unsafe impl Sync for Receiver {} +unsafe impl Sync for Receiver {} #[cfg(not(target_os = "none"))] -impl Receiver { +impl Receiver { /// Returns the serializable configuration other processes pass to /// [`ChannelConf::sender`], borrowing this receiver's storage. #[must_use] - pub fn conf(&self) -> ChannelConf<'_> { - ChannelConf { shm_id: IpcStr::from_os_c_str(self.keeper.path.as_c_str()) } + pub fn conf(&self) -> ChannelConf<'_, P> { + ChannelConf { + shm_id: IpcStr::from_os_c_str(self.keeper.path.as_c_str()), + _protocol: PhantomData, + } } /// Creates a sender in this process. @@ -330,41 +458,41 @@ impl Receiver { /// /// When the region cannot hold the protocol, which [`channel`] proved /// it could. - pub fn sender(&self) -> io::Result { + pub fn sender(&self) -> io::Result> { let mapping = self.handle.map().map_err(shm_error_to_io)?; // SAFETY: `mapping` maps the region `channel` created // zero-initialized and accessed only through the `shm_io` protocol // since. let writer = unsafe { ShmWriter::new(mapping, SLOTS) } .expect("the shared-memory region cannot hold the channel"); - Ok(Sender { writer }) + Ok(Sender { writer, _protocol: PhantomData }) } - /// Closes the channel and returns every committed frame, borrowed from - /// the shared mapping that moves into the returned [`FrameReader`]. + /// Closes the channel and returns every committed record, borrowed from + /// the shared mapping that moves into the returned [`RecordReader`]. /// /// Never blocks on senders: it reads the claim counter once, which - /// fixes how far reading goes, and shuts the gate so no later claim - /// succeeds. Committed frames become readable in place. A sender that - /// was still filling a frame keeps running, and its frame may or may + /// fixes how far reading goes, and shuts the seal gate so no later claim + /// succeeds. Committed records become readable in place. A sender that + /// was still filling a frame keeps running, and its record may or may /// not appear depending on whether it commits before the read reaches /// that slot — either way the operation it describes happens after the /// receiver stopped collecting. The mapping is released when the - /// returned [`FrameReader`] drops. + /// returned [`RecordReader`] drops. /// /// # Errors /// - /// [`RecordsLost`] when a sender could not record something it went on - /// to do. There is no complete set of records then, so none are handed - /// back, and a caller that needs the trace has to treat the run as - /// untracked rather than as having reported nothing. + /// [`CloseError`] when records were lost — either because the channel ran + /// out of room ([`CloseError::Capacity`]) or because a sender explicitly + /// called [`Sender::report_loss`] ([`CloseError::Reported`]). There is no + /// complete set of records then, so none are handed back. /// /// # Panics /// /// When the region cannot hold the protocol, which [`channel`] proved /// it could before any sender saw it. - pub fn close(self) -> Result { - let Self { keeper, handle, mapping } = self; + pub fn close(self) -> Result, CloseError> { + let Self { keeper, handle, mapping, _protocol } = self; drop(handle); // SAFETY: `mapping` was created zero-initialized by `channel`, its // address is stable and independently owned, and all attached @@ -376,8 +504,9 @@ impl Receiver { // all, and so could not report whatever it then failed to record. drop(keeper); match sealed { - Ok(reader) => Ok(reader), - Err(SealError::Capacity | SealError::Aborted) => Err(RecordsLost), + Ok(inner) => Ok(RecordReader { inner, _protocol: PhantomData }), + Err(SealError::Capacity) => Err(CloseError::Capacity), + Err(SealError::Aborted) => Err(CloseError::Reported), Err(SealError::AlreadySealed) => { panic!("the unique receiver cannot have already sealed the channel") } @@ -388,20 +517,23 @@ impl Receiver { } } -/// A sender could not record something, so the receiver has no complete -/// set of records to hand back. -/// -/// The region filled up, or a record came out longer than one frame can -/// hold. Both are the channel running out of room rather than anything the -/// senders did wrong, and both leave the run untracked. +/// Why [`Receiver::close`] could not hand back a complete set of records. #[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] -#[error("a sender ran out of room in the shared-memory channel")] #[cfg(not(target_os = "none"))] -pub struct RecordsLost; +pub enum CloseError { + /// A sender ran out of room in the shared-memory region (descriptor slots, + /// payload bytes, or the 32-bit single-frame limit). + #[error("a sender ran out of room in the shared-memory channel")] + Capacity, + /// A sender explicitly reported that it could not record an operation via + /// [`Sender::report_loss`]. + #[error("a sender reported that records were lost")] + Reported, +} #[cfg(test)] mod tests { - use std::{ffi::OsString, fs, num::NonZeroUsize, str::from_utf8}; + use std::{ffi::OsString, fs, num::NonZeroUsize}; use allocator_api2::alloc::Global; use assert2::assert; @@ -409,7 +541,13 @@ mod tests { use vt_subprocess_test::command_for_fn; use super::*; - use crate::ipc::{IpcPath, PathAccess}; + use crate::ipc::{AccessProtocol, IpcPath, PathAccess}; + + /// Simple protocol carrying `u16` records for channel-level unit tests. + struct U16Protocol; + impl ChannelProtocol for U16Protocol { + type Record<'a> = u16; + } /// A gibibyte, which clears the table's half of sparse address space /// and leaves the rest for payloads. None of it costs real memory @@ -424,7 +562,7 @@ mod tests { fn a_capacity_too_small_for_the_table_fails_the_channel() { // The counters alone need sixteen bytes, and the table needs eight // per slot on top. - let Err(error) = channel(8, Global) else { + let Err(error) = channel::(8, Global) else { panic!("a region too small for the protocol made a channel"); }; assert!(error.kind() == io::ErrorKind::InvalidInput); @@ -435,18 +573,15 @@ mod tests { /// must still attach. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn sender_ignores_changed_temp_and_working_directory() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let conf = wincode::serialize(&receiver.conf()).unwrap(); let changed_cwd = temp_dir().join(format!("fspy-ipc-changed-cwd-{}", Uuid::new_v4())); fs::create_dir(&changed_cwd).unwrap(); let mut command = command_for_fn!(conf, |conf: Vec| { - let conf: ChannelConf = wincode::deserialize(&conf).unwrap(); + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); let sender = conf.sender(Global).unwrap(); - let frame_size = NonZeroUsize::new(2).unwrap(); - let mut frame = sender.writer.claim_frame(frame_size).unwrap(); - frame.copy_from_slice(&[4, 2]); - frame.finish(); + sender.send(&42); }); command.cwd = changed_cwd.clone(); for name in ["TMPDIR", "TMP", "TEMP"] { @@ -456,18 +591,15 @@ mod tests { fs::remove_dir(changed_cwd).unwrap(); assert!(succeeded); - let frames = receiver.close().unwrap(); - assert!(frames.iter().next().unwrap() == &[4, 2]); + let records = receiver.close().unwrap(); + assert!(records.iter().collect::>() == [42]); } - /// `Sender::send` is the only writer production uses, and the rest of - /// these tests reach past it into `claim_frame`. This one drives it - /// end to end, so that a disagreement between `serialized_size` and - /// `serialize_into` — which would silently drop every record — fails - /// here rather than in a build. + /// `Sender::send` and `RecordReader::iter` round-trip borrowed `PathAccess` + /// records end to end without copying paths out of shared memory. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn sender_round_trips_records() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let sender = receiver.conf().sender(Global).unwrap(); // A record path carries the platform's own string form: bytes on // unix, UTF-16 on Windows. @@ -486,47 +618,64 @@ mod tests { } drop(sender); - let frames = receiver.close().unwrap(); - let mut iter = frames.iter(); + let records = receiver.close().unwrap(); + let mut iter = records.iter(); for path in paths { - let access: PathAccess<'_> = wincode::deserialize_exact(iter.next().unwrap()).unwrap(); - assert!(access == PathAccess::Read(path)); + assert!(iter.next().unwrap() == PathAccess::Read(path)); } assert!(iter.next().is_none()); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn report_loss_returns_reported_close_error() { + let receiver = channel::(CAPACITY, Global).unwrap(); + let sender = receiver.conf().sender(Global).unwrap(); + sender.send(&7); + sender.report_loss(); + // New senders see the closed gate and give up without attaching. + assert!(receiver.conf().sender(Global).is_none()); + assert!(receiver.close().unwrap_err() == CloseError::Reported); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn capacity_exhaustion_returns_capacity_close_error() { + // Descriptor table (512 MiB) + 16-byte counters + 4 bytes of payload + // room: fits two u16 records (4 bytes) and overflows on the third. + let receiver = channel::(SLOTS * 8 + 20, Global).unwrap(); + let sender = receiver.conf().sender(Global).unwrap(); + sender.send(&1); + sender.send(&2); + sender.send(&3); + assert!(receiver.close().unwrap_err() == CloseError::Capacity); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn smoke() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let conf = wincode::serialize(&receiver.conf()).unwrap(); let cmd = command_for_fn!(conf, |conf: Vec| { - let conf: ChannelConf = wincode::deserialize(&conf).unwrap(); + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); let sender = conf.sender(Global).unwrap(); - let frame_size = NonZeroUsize::new(2).unwrap(); - let mut frame = sender.writer.claim_frame(frame_size).unwrap(); - frame.copy_from_slice(&[4, 2]); - frame.finish(); + sender.send(&42); }); assert!(std::process::Command::from(cmd).status().unwrap().success()); - let frames = receiver.close().unwrap(); - let mut iter = frames.iter(); - - let received_frame = iter.next().unwrap(); - assert!(received_frame == &[4, 2]); + let records = receiver.close().unwrap(); + let mut iter = records.iter(); + assert!(iter.next().unwrap() == 42); assert!(iter.next().is_none()); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[expect(clippy::print_stdout, reason = "test diagnostics")] async fn forbid_new_senders_after_close() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let conf = wincode::serialize(&receiver.conf()).unwrap(); - let _frames = receiver.close().unwrap(); + let _records = receiver.close().unwrap(); let cmd = command_for_fn!(conf, |conf: Vec| { - let conf: ChannelConf = wincode::deserialize(&conf).unwrap(); + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); print!("{}", conf.sender(Global).is_some()); }); let output = std::process::Command::from(cmd).output().unwrap(); @@ -536,12 +685,12 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[expect(clippy::print_stdout, reason = "test diagnostics")] async fn forbid_new_senders_after_receiver_dropped() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let conf = wincode::serialize(&receiver.conf()).unwrap(); drop(receiver); let cmd = command_for_fn!(conf, |conf: Vec| { - let conf: ChannelConf = wincode::deserialize(&conf).unwrap(); + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); print!("{}", conf.sender(Global).is_some()); }); let output = std::process::Command::from(cmd).output().unwrap(); @@ -552,15 +701,12 @@ mod tests { /// claim any new frame afterwards. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn attached_sender_cannot_claim_after_close() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let sender = receiver.conf().sender(Global).unwrap(); + sender.send(&42); - let mut frame = sender.writer.claim_frame(NonZeroUsize::new(2).unwrap()).unwrap(); - frame.copy_from_slice(&[4, 2]); - frame.finish(); - - let frames = receiver.close().unwrap(); - assert!(frames.iter().next().unwrap() == &[4, 2]); + let records = receiver.close().unwrap(); + assert!(records.iter().next().unwrap() == 42); assert!( sender.writer.claim_frame(NonZeroUsize::new(2).unwrap()).unwrap_err() @@ -573,25 +719,20 @@ mod tests { /// sender it outlives the close with every claim refused. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn receiver_sender_shares_the_region_with_other_processes() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let local_sender = receiver.sender().unwrap(); - - let mut frame = local_sender.writer.claim_frame(NonZeroUsize::new(2).unwrap()).unwrap(); - frame.copy_from_slice(&[4, 2]); - frame.finish(); + local_sender.send(&42); let conf = wincode::serialize(&receiver.conf()).unwrap(); let cmd = command_for_fn!(conf, |conf: Vec| { - let conf: ChannelConf = wincode::deserialize(&conf).unwrap(); + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); let sender = conf.sender(Global).unwrap(); - let mut frame = sender.writer.claim_frame(NonZeroUsize::new(2).unwrap()).unwrap(); - frame.copy_from_slice(&[2, 4]); - frame.finish(); + sender.send(&24); }); assert!(std::process::Command::from(cmd).status().unwrap().success()); - let frames = receiver.close().unwrap(); - assert!(frames.iter().collect::>() == [&[4, 2], &[2, 4]]); + let records = receiver.close().unwrap(); + assert!(records.iter().collect::>() == [42, 24]); assert!( local_sender.writer.claim_frame(NonZeroUsize::new(2).unwrap()).unwrap_err() @@ -601,19 +742,13 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn concurrent_senders() { - let receiver = channel(CAPACITY, Global).unwrap(); + let receiver = channel::(CAPACITY, Global).unwrap(); let conf = wincode::serialize(&receiver.conf()).unwrap(); for i in 0u16..200 { let cmd = command_for_fn!((conf.clone(), i), |(conf, i): (Vec, u16)| { - let conf: ChannelConf = wincode::deserialize(&conf).unwrap(); + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); let sender = conf.sender(Global).unwrap(); - let data_to_send = i.to_string(); - let mut frame = sender - .writer - .claim_frame(NonZeroUsize::new(data_to_send.len()).unwrap()) - .unwrap(); - frame.copy_from_slice(data_to_send.as_bytes()); - frame.finish(); + sender.send(&i); }); let output = std::process::Command::from(cmd).output().unwrap(); assert!( @@ -623,9 +758,8 @@ mod tests { B(&output.stderr) ); } - let frames = receiver.close().unwrap(); - let mut received_values: Vec = - frames.iter().map(|frame| from_utf8(frame).unwrap().parse::().unwrap()).collect(); + let records = receiver.close().unwrap(); + let mut received_values: Vec = records.iter().collect(); received_values.sort_unstable(); assert!(received_values == (0u16..200).collect::>()); } diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs index 52e9d78e3..bd701d130 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs @@ -27,7 +27,7 @@ use core::ptr::slice_from_raw_parts_mut; use fspy_shm::Mapping; #[cfg(not(target_os = "none"))] -pub use reader::{SealError, ShmReader}; +pub use reader::{Iter, SealError, ShmReader}; // Only tests name a claim's failure; a sender skips the record either // way, so production matches on `Ok`/`Err` alone. #[cfg(test)] diff --git a/crates/fspy_shared/src/ipc/mod.rs b/crates/fspy_shared/src/ipc/mod.rs index 1983fe200..8cfc7a06b 100644 --- a/crates/fspy_shared/src/ipc/mod.rs +++ b/crates/fspy_shared/src/ipc/mod.rs @@ -2,12 +2,49 @@ pub mod channel; mod ipc_path; use core::iter; +#[cfg(not(target_os = "none"))] +use allocator_api2::alloc::Allocator; #[cfg(not(target_os = "none"))] use bumpalo::Bump; pub use ipc_path::IpcPath; pub use vt_ipc_str::IpcStr; use wincode::{SchemaRead, SchemaWrite}; +/// Channel protocol for fspy file-access tracing. +pub struct AccessProtocol; + +impl channel::ChannelProtocol for AccessProtocol { + type Record<'a> = PathAccess<'a>; +} + +/// Serializable configuration for creating [`AccessSender`]s. +pub type AccessChannelConf<'a> = channel::ChannelConf<'a, AccessProtocol>; + +/// Sender for [`PathAccess`] records. +pub type AccessSender = channel::Sender; + +/// Receiver for [`PathAccess`] records. +#[cfg(not(target_os = "none"))] +pub type AccessReceiver = channel::Receiver; + +/// Reader iterating over committed [`PathAccess`] records. +#[cfg(not(target_os = "none"))] +pub type AccessReader = channel::RecordReader; + +/// Error returned when closing an [`AccessReceiver`] fails. +#[cfg(not(target_os = "none"))] +pub type AccessCloseError = channel::CloseError; + +/// Creates an IPC channel carrying [`PathAccess`] records. +#[expect(clippy::missing_errors_doc, reason = "non-vt crate: cannot use vt_str/vt_path types")] +#[cfg(not(target_os = "none"))] +pub fn access_channel( + capacity: usize, + allocator: A, +) -> std::io::Result> { + channel::channel(capacity, allocator) +} + /// The kind of a single-path access, for building a record before its path /// is resolved. /// diff --git a/crates/fspy_shared/src/windows/mod.rs b/crates/fspy_shared/src/windows/mod.rs index b2700c122..c1fc49e7c 100644 --- a/crates/fspy_shared/src/windows/mod.rs +++ b/crates/fspy_shared/src/windows/mod.rs @@ -1,7 +1,7 @@ use winapi::DEFINE_GUID; use wincode::{SchemaRead, SchemaWrite}; -use crate::ipc::channel::ChannelConf; +use crate::ipc::AccessChannelConf; // Generated by guidgen.exe // {FC4845F1-3A8B-4F05-A3D3-A5E9E102AF33} @@ -22,6 +22,6 @@ DEFINE_GUID!( #[derive(SchemaWrite, SchemaRead, Debug, Clone)] pub struct Payload<'a> { - pub channel_conf: ChannelConf<'a>, + pub channel_conf: AccessChannelConf<'a>, pub ansi_dll_path_with_nul: &'a [u8], } diff --git a/crates/fspy_shared_unix/src/payload.rs b/crates/fspy_shared_unix/src/payload.rs index 8276ba5ee..d5ffb0ddc 100644 --- a/crates/fspy_shared_unix/src/payload.rs +++ b/crates/fspy_shared_unix/src/payload.rs @@ -2,9 +2,7 @@ use allocator_api2::alloc::Allocator; use base64::{Engine as _, prelude::BASE64_STANDARD_NO_PAD}; use bstr::BStr; #[cfg(not(target_env = "musl"))] -use fspy_shared::ipc::IpcStr; -#[cfg(not(target_env = "musl"))] -use fspy_shared::ipc::channel::ChannelConf; +use fspy_shared::ipc::{AccessChannelConf, IpcStr}; use wincode::{SchemaRead, SchemaWrite}; /// The payload as it travels between processes. @@ -17,7 +15,7 @@ use wincode::{SchemaRead, SchemaWrite}; #[derive(Debug, SchemaWrite, SchemaRead)] pub struct Payload<'a> { #[cfg(not(target_env = "musl"))] - pub ipc_channel_conf: ChannelConf<'a>, + pub ipc_channel_conf: AccessChannelConf<'a>, #[cfg(target_env = "musl")] pub ipc_channel_conf: core::marker::PhantomData<&'a ()>,