Skip to content

Commit 8ba51c6

Browse files
wan9chiclaude
andauthored
refactor(fspy-shm): adopt the no-std OsCStr API (#668)
## Motivation With the backing path supplied by the caller (#667), nothing left in fspy_shm needs std: the remaining `OsStr`/`CString`/`io::Error` uses were adapters at the API boundary. Dropping them makes the crate usable from the preload contexts where std is not dependable, matching fspy_nostd's guarantees. fspy_shm is `no_std` now: `create`/`open`/`remove` take `fspy_nostd::OsCStr` paths (bytes on Unix, wide units on Windows), `create` takes `NonZeroUsize`, and every function returns `fspy_nostd::Result` with raw OS error codes. Supporting surface, each piece consumed immediately: - fspy_nostd gains the `OsCStr` alias and a `Fat`→`Thin` downgrade. - fspy_nostd_alloc compiles on every platform now that only `arena` and `fs` are unix-specific; `CString` is generic over the code unit, renames its byte accessors to unit accessors, gains a checked `from_vec_with_nul`, and an `OsCString` alias mirrors `OsCStr`. - fspy_shared owns the `OsStr` boundary: it encodes paths into `OsCString`, keeps one in its keeper, and maps raw OS errors back to `io::Error`. --- <sub>Stack created with <a href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1 parent 74d31d6 commit 8ba51c6

16 files changed

Lines changed: 351 additions & 271 deletions

File tree

‎Cargo.lock‎

Lines changed: 4 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/fspy_client_unix/src/convert.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ fn get_fd_path<A: Allocator>(allocator: A, fd: BorrowedFd<'_>) -> nix::Result<Op
1111
if fd.as_raw_fd() == CWD.as_raw_fd() {
1212
let path = fspy_nostd_alloc::fs::getcwd(allocator)
1313
.map_err(|errno| nix::errno::Errno::from_raw(errno.raw_os_error()))?
14-
.into_bytes();
14+
.into_units();
1515
return Ok(Some(path));
1616
}
1717
let mut path = [0; PROC_FD_PATH_CAPACITY];
@@ -51,15 +51,15 @@ fn get_fd_path<A: Allocator>(allocator: A, fd: BorrowedFd<'_>) -> nix::Result<Op
5151
if fd.as_raw_fd() == CWD.as_raw_fd() {
5252
let path = fspy_nostd_alloc::fs::getcwd(allocator)
5353
.map_err(|errno| nix::errno::Errno::from_raw(errno.raw_os_error()))?
54-
.into_bytes();
54+
.into_units();
5555
return Ok(Some(path));
5656
}
5757

5858
match fspy_nostd_alloc::fs::fcntl_getpath(allocator, fd) {
5959
Ok(path) => {
6060
// `F_GETPATH` does not return a length. Count at this caller before
6161
// converting its allocation into the returned path.
62-
Ok(Some(path.count().into_bytes()))
62+
Ok(Some(path.count().into_units()))
6363
}
6464
Err(fspy_nostd::Error::BADF | fspy_nostd::Error::NOENT) => Ok(None),
6565
Err(errno) => Err(nix::errno::Errno::from_raw(errno.raw_os_error())),

‎crates/fspy_nostd/src/c_str.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,15 @@ pub struct CStr<'a, R, U: CStrUnit = u8> {
4646
/// A borrowed NUL-terminated string of `u16` code units.
4747
pub type WideCStr<'a, R> = CStr<'a, R, u16>;
4848

49+
/// A borrowed NUL-terminated string of the platform's native path code
50+
/// units: bytes on Unix and wide (`u16`) code units on Windows.
51+
#[cfg(unix)]
52+
pub type OsCStr<'a, R> = CStr<'a, R>;
53+
/// A borrowed NUL-terminated string of the platform's native path code
54+
/// units: bytes on Unix and wide (`u16`) code units on Windows.
55+
#[cfg(windows)]
56+
pub type OsCStr<'a, R> = WideCStr<'a, R>;
57+
4958
/// An iterator over the non-NUL code units of a thin C string.
5059
#[derive(Clone)]
5160
pub struct Units<'a, U: CStrUnit> {
@@ -187,6 +196,13 @@ impl<'a, U: CStrUnit> CStr<'a, Fat, U> {
187196
}
188197
}
189198

199+
/// Discards the retained length and returns a thin view of the same
200+
/// string.
201+
#[must_use]
202+
pub const fn as_thin(self) -> CStr<'a, Thin, U> {
203+
CStr { ptr: self.ptr, repr: Thin { _private: () }, lifetime: PhantomData }
204+
}
205+
190206
/// Returns the string's code units without the terminating NUL.
191207
#[must_use]
192208
pub const fn as_units(&self) -> &'a [U] {

‎crates/fspy_nostd/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ pub mod mm;
2020
#[cfg(unix)]
2121
pub mod param;
2222

23-
pub use c_str::{CStr, CStrUnit, Fat, Thin, Units, WideCStr};
23+
pub use c_str::{CStr, CStrUnit, Fat, OsCStr, Thin, Units, WideCStr};
2424
#[cfg(windows)]
2525
pub use windows::{
2626
BorrowedHandle, OwnedHandle, RawHandle, SecurityAttributes, bool_result, get_module_handle,

‎crates/fspy_nostd_alloc/Cargo.toml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ publish = false
77
[lib]
88
doctest = false
99

10-
[target.'cfg(unix)'.dependencies]
10+
[dependencies]
1111
allocator-api2 = { workspace = true, features = ["alloc"] }
12-
bump-scope = { workspace = true }
1312
fspy_nostd = { workspace = true }
1413

14+
[target.'cfg(unix)'.dependencies]
15+
bump-scope = { workspace = true }
16+
1517
[lints]
1618
workspace = true
Lines changed: 66 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,114 +1,137 @@
11
use core::{mem::MaybeUninit, ptr, slice};
22

33
use allocator_api2::{alloc::Allocator, boxed::Box, vec::Vec};
4-
use fspy_nostd::{CStr, Fat, Thin};
4+
use fspy_nostd::{CStr, CStrUnit, Fat, Thin};
55

66
/// An allocator-backed owned C string.
7-
pub struct CString<R, A: Allocator> {
8-
bytes: Box<[MaybeUninit<u8>], A>,
7+
pub struct CString<R, A: Allocator, U: CStrUnit = u8> {
8+
units: Box<[MaybeUninit<U>], A>,
99
repr: R,
1010
}
1111

12-
impl<A: Allocator> CString<Fat, A> {
13-
/// Converts a byte vector to a C string without checking its contents.
12+
/// An allocator-backed owned C string of the platform's native path code
13+
/// units: bytes on Unix and wide (`u16`) code units on Windows.
14+
#[cfg(unix)]
15+
pub type OsCString<R, A> = CString<R, A>;
16+
/// An allocator-backed owned C string of the platform's native path code
17+
/// units: bytes on Unix and wide (`u16`) code units on Windows.
18+
#[cfg(windows)]
19+
pub type OsCString<R, A> = CString<R, A, u16>;
20+
21+
impl<A: Allocator, U: CStrUnit> CString<Fat, A, U> {
22+
/// Converts a code-unit vector that ends with the single NUL terminator
23+
/// to a C string.
24+
///
25+
/// Returns [`None`] when `units` is empty, does not end with a NUL code
26+
/// unit, or contains an interior NUL code unit.
27+
#[must_use]
28+
pub fn from_vec_with_nul(units: Vec<U, A>) -> Option<Self> {
29+
CStr::<Fat, U>::from_units_with_nul(&units)?;
30+
// SAFETY: validated just above.
31+
Some(unsafe { Self::from_vec_with_nul_unchecked(units) })
32+
}
33+
34+
/// Converts a code-unit vector to a C string without checking its
35+
/// contents.
1436
///
1537
/// # Safety
1638
///
17-
/// `bytes` must end with exactly one NUL byte and contain no other NUL
18-
/// bytes.
39+
/// `units` must end with exactly one NUL code unit and contain no other
40+
/// NUL code units.
1941
#[must_use]
20-
pub unsafe fn from_vec_with_nul_unchecked(bytes: Vec<u8, A>) -> Self {
42+
pub unsafe fn from_vec_with_nul_unchecked(units: Vec<U, A>) -> Self {
2143
// SAFETY: upheld by the caller.
22-
let repr = unsafe { CStr::<Fat>::from_units_with_nul_unchecked(&bytes) }.into_repr();
23-
let (bytes, _len, capacity, allocator) = bytes.into_raw_parts_with_alloc();
24-
let bytes = ptr::slice_from_raw_parts_mut(bytes.cast::<MaybeUninit<u8>>(), capacity);
44+
let repr = unsafe { CStr::<Fat, U>::from_units_with_nul_unchecked(&units) }.into_repr();
45+
let (units, _len, capacity, allocator) = units.into_raw_parts_with_alloc();
46+
let units = ptr::slice_from_raw_parts_mut(units.cast::<MaybeUninit<U>>(), capacity);
2547

2648
Self {
2749
// SAFETY: this uses the vector's original pointer, capacity, and
2850
// allocator. Its initialized prefix is described by `repr`; any
29-
// spare capacity is valid as `MaybeUninit<u8>`.
30-
bytes: unsafe { Box::from_raw_in(bytes, allocator) },
51+
// spare capacity is valid as `MaybeUninit<U>`.
52+
units: unsafe { Box::from_raw_in(units, allocator) },
3153
repr,
3254
}
3355
}
3456
}
3557

36-
impl<A: Allocator> CString<Thin, A> {
58+
impl<A: Allocator, U: CStrUnit> CString<Thin, A, U> {
3759
/// Converts boxed storage to a thin C string without checking its
3860
/// contents.
3961
///
4062
/// # Safety
4163
///
42-
/// `bytes` must begin with a valid NUL-terminated C string. Bytes after
43-
/// that string may be uninitialized.
64+
/// `units` must begin with a valid NUL-terminated C string. Code units
65+
/// after that string may be uninitialized.
4466
#[must_use]
45-
pub unsafe fn from_boxed_with_nul_unchecked(bytes: Box<[MaybeUninit<u8>], A>) -> Self {
67+
pub unsafe fn from_boxed_with_nul_unchecked(units: Box<[MaybeUninit<U>], A>) -> Self {
4668
// SAFETY: upheld by the caller. Creating a thin view does not scan the
4769
// allocation or retain the string length.
48-
let repr = unsafe { CStr::<Thin>::from_ptr(bytes.as_ptr().cast()) }.into_repr();
49-
Self { bytes, repr }
70+
let repr = unsafe { CStr::<Thin, U>::from_ptr(units.as_ptr().cast()) }.into_repr();
71+
Self { units, repr }
5072
}
5173

5274
/// Returns a thin borrowed view of this C string.
5375
#[must_use]
54-
pub fn as_c_str(&self) -> CStr<'_, Thin> {
76+
pub fn as_c_str(&self) -> CStr<'_, Thin, U> {
5577
// SAFETY: upheld by the constructor; `self` owns the storage.
56-
unsafe { CStr::from_ptr(self.bytes.as_ptr().cast()) }
78+
unsafe { CStr::from_ptr(self.units.as_ptr().cast()) }
5779
}
5880

5981
/// Counts through the terminating NUL and returns a length-retaining C
6082
/// string using the same allocation.
6183
#[must_use]
62-
pub fn count(self) -> CString<Fat, A> {
84+
pub fn count(self) -> CString<Fat, A, U> {
6385
let repr = self.as_c_str().count().into_repr();
64-
CString { bytes: self.bytes, repr }
86+
CString { units: self.units, repr }
6587
}
6688
}
6789

68-
impl<A: Allocator> CString<Fat, A> {
90+
impl<A: Allocator, U: CStrUnit> CString<Fat, A, U> {
6991
/// Extracts a borrowed C string view containing the entire string.
7092
#[must_use]
71-
pub fn as_c_str(&self) -> CStr<'_, Fat> {
93+
pub fn as_c_str(&self) -> CStr<'_, Fat, U> {
7294
// SAFETY: the initialized prefix described by `repr` is a C string.
73-
unsafe { CStr::from_units_with_nul_unchecked(self.as_bytes_with_nul()) }
95+
unsafe { CStr::from_units_with_nul_unchecked(self.as_units_with_nul()) }
7496
}
7597

7698
/// Returns the contents of this C string without the terminating NUL.
7799
#[must_use]
78-
pub fn as_bytes(&self) -> &[u8] {
79-
let bytes = self.as_bytes_with_nul();
80-
bytes.split_at(bytes.len() - 1).0
100+
pub fn as_units(&self) -> &[U] {
101+
let units = self.as_units_with_nul();
102+
units.split_at(units.len() - 1).0
81103
}
82104

83105
/// Returns the contents of this C string, including the terminating NUL.
84106
#[must_use]
85-
pub fn as_bytes_with_nul(&self) -> &[u8] {
107+
pub fn as_units_with_nul(&self) -> &[U] {
86108
// SAFETY: `repr` describes the initialized C string prefix.
87-
unsafe { slice::from_raw_parts(self.bytes.as_ptr().cast(), self.repr.len_with_nul()) }
109+
unsafe { slice::from_raw_parts(self.units.as_ptr().cast(), self.repr.len_with_nul()) }
88110
}
89111

90-
/// Consumes this C string and returns its bytes without the terminating NUL.
112+
/// Consumes this C string and returns its code units without the
113+
/// terminating NUL.
91114
#[must_use = "`self` will be dropped if the result is not used"]
92-
pub fn into_bytes(self) -> Vec<u8, A> {
115+
pub fn into_units(self) -> Vec<U, A> {
93116
let len = self.repr.len_with_nul() - 1;
94117
self.into_vec(len)
95118
}
96119

97-
/// Consumes this C string and returns its bytes, including the terminating
98-
/// NUL.
120+
/// Consumes this C string and returns its code units, including the
121+
/// terminating NUL.
99122
#[must_use = "`self` will be dropped if the result is not used"]
100-
pub fn into_bytes_with_nul(self) -> Vec<u8, A> {
123+
pub fn into_units_with_nul(self) -> Vec<U, A> {
101124
let len = self.repr.len_with_nul();
102125
self.into_vec(len)
103126
}
104127

105-
fn into_vec(self, len: usize) -> Vec<u8, A> {
106-
let Self { bytes, .. } = self;
107-
let capacity = bytes.len();
108-
let (bytes, allocator) = Box::into_raw_with_allocator(bytes);
128+
fn into_vec(self, len: usize) -> Vec<U, A> {
129+
let Self { units, .. } = self;
130+
let capacity = units.len();
131+
let (units, allocator) = Box::into_raw_with_allocator(units);
109132

110-
// SAFETY: the box was allocated for `capacity` bytes with `allocator`.
111-
// The first `len` bytes are initialized.
112-
unsafe { Vec::from_raw_parts_in(bytes.cast::<u8>(), len, capacity, allocator) }
133+
// SAFETY: the box was allocated for `capacity` units with `allocator`.
134+
// The first `len` units are initialized.
135+
unsafe { Vec::from_raw_parts_in(units.cast::<U>(), len, capacity, allocator) }
113136
}
114137
}

‎crates/fspy_nostd_alloc/src/fs.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,12 @@ mod tests {
115115
let expected = expected.as_units_with_nul();
116116

117117
assert_eq!(path.as_c_str().as_units_with_nul(), expected);
118-
assert_eq!(path.as_bytes(), &expected[..expected.len() - 1]);
119-
assert_eq!(path.as_bytes_with_nul(), expected);
120-
assert_eq!(path.into_bytes().as_slice(), &expected[..expected.len() - 1]);
118+
assert_eq!(path.as_units(), &expected[..expected.len() - 1]);
119+
assert_eq!(path.as_units_with_nul(), expected);
120+
assert_eq!(path.into_units().as_slice(), &expected[..expected.len() - 1]);
121121

122122
let path = super::getcwd(Global).unwrap();
123-
assert_eq!(path.into_bytes_with_nul().as_slice(), expected);
123+
assert_eq!(path.into_units_with_nul().as_slice(), expected);
124124
}
125125

126126
#[cfg(target_os = "macos")]

‎crates/fspy_nostd_alloc/src/lib.rs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,42 +11,52 @@
1111
//! intercepted call, drawing its chunks from the process-wide pool and
1212
//! returning them on drop.
1313
14-
#![cfg(unix)]
1514
#![cfg_attr(not(test), no_std)]
1615

1716
mod c_string;
17+
#[cfg(unix)]
1818
pub mod fs;
19+
#[cfg(unix)]
1920
mod mmap;
21+
#[cfg(unix)]
2022
mod pool;
2123

24+
#[cfg(unix)]
2225
use allocator_api2::alloc::Allocator;
26+
#[cfg(unix)]
2327
use bump_scope::{
2428
Bump,
2529
alloc::compat::AllocatorApi2V02Compat,
2630
settings::{BumpAllocatorSettings, BumpSettings},
2731
};
28-
pub use c_string::CString;
32+
pub use c_string::{CString, OsCString};
33+
#[cfg(unix)]
2934
use mmap::MmapAllocator;
35+
#[cfg(unix)]
3036
use pool::ChunkPool;
3137

3238
/// Every cached chunk is 64 KiB: a whole multiple of the page size on all
3339
/// supported targets, and big enough that most intercepted calls fit their
3440
/// allocations into a single chunk. [`ArenaSettings`] pins the arenas' own
3541
/// chunk sizing to this same value.
42+
#[cfg(unix)]
3643
const CHUNK_SIZE: usize = 64 * 1024;
3744
/// The alignment chunks are allocated with. Must be at least the alignment
3845
/// `bump_scope::Bump` uses for its chunk requests — 16 (see
3946
/// [`MmapAllocator`]'s docs for the links). bump-scope does not export that
4047
/// constant, so the `bump_chunk_requests_fit_the_pool_gates` test pins the
4148
/// fit instead: it fails if a bump-scope upgrade ever requests chunks the
4249
/// pool would refuse.
50+
#[cfg(unix)]
4351
const CHUNK_ALIGN: usize = 16;
4452
/// At most this many chunks stay cached, capping retained memory at
4553
/// `SLOTS * CHUNK_SIZE` = 4 MiB.
54+
#[cfg(unix)]
4655
const SLOTS: usize = 64;
4756

4857
/// The process-wide chunk pool. `const`-initialized, so it works from the
4958
/// first allocation on — even before any constructor has run.
59+
#[cfg(unix)]
5060
static CHUNK_POOL: ChunkPool<MmapAllocator, CHUNK_SIZE, CHUNK_ALIGN, SLOTS> = ChunkPool::new();
5161

5262
/// The `Bump` settings the arenas use — the defaults, with two changes:
@@ -63,13 +73,15 @@ static CHUNK_POOL: ChunkPool<MmapAllocator, CHUNK_SIZE, CHUNK_ALIGN, SLOTS> = Ch
6373
/// minimum — which is exactly what keeps a minimum-sized request within
6474
/// the pool's `size <= CHUNK_SIZE` gate; the
6575
/// `bump_chunk_requests_fit_the_pool_gates` test pins that fit.
76+
#[cfg(unix)]
6677
type ArenaSettings = <<BumpSettings as BumpAllocatorSettings>::WithGuaranteedAllocated<false> as BumpAllocatorSettings>::WithMinimumChunkSize<CHUNK_SIZE>;
6778

6879
/// `Bump::unallocated` requires its base allocator to implement `Default`
6980
/// (an arena without chunks has nowhere to store an allocator value, so it
7081
/// conjures one on first use). Point defaulted references at the
7182
/// process-wide pool. As an allocator, `&ChunkPool` already works through
7283
/// allocator-api2's blanket `impl Allocator for &A`.
84+
#[cfg(unix)]
7385
impl Default for &'static ChunkPool<MmapAllocator, CHUNK_SIZE, CHUNK_ALIGN, SLOTS> {
7486
fn default() -> Self {
7587
&CHUNK_POOL
@@ -89,6 +101,7 @@ impl Default for &'static ChunkPool<MmapAllocator, CHUNK_SIZE, CHUNK_ALIGN, SLOT
89101
/// across threads. Creating one is safe anywhere, any time: the pool
90102
/// underneath works in signal handlers and in the child of `fork()` (see
91103
/// `ChunkPool` and `MmapAllocator` in this crate's source for why).
104+
#[cfg(unix)]
92105
#[must_use]
93106
pub fn arena() -> impl Allocator {
94107
Bump::<
@@ -97,7 +110,7 @@ pub fn arena() -> impl Allocator {
97110
>::unallocated()
98111
}
99112

100-
#[cfg(test)]
113+
#[cfg(all(test, unix))]
101114
mod tests {
102115
use core::alloc::Layout;
103116

0 commit comments

Comments
 (0)