am-fs-core 0.2.10

Pure-Rust block-device framework — BlockRead/BlockDevice traits + FileDevice + CallbackDevice + LRU cache. Foundation crate for fs-* drivers and img-* containers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
//! C ABI for the block-device framework.
//!
//! Every sister crate (qcow2 reader, partition probe, fs-* drivers) speaks
//! through the [`FsCoreDevice`] handle defined here, so consumers (Swift
//! FSKit modules, Go callers, C programs) only learn one device-handle
//! type and one error convention.
//!
//! ## Conventions
//!
//! - Handles are opaque `*mut FsCoreDevice`. Allocate via a constructor in
//!   one of the sister crates (e.g. `qcow2_open` from rust-img-qcow2),
//!   free via [`fs_core_device_close`] regardless of which crate created
//!   it.
//! - Error reporting is errno-style: every fallible function returns an
//!   [`FsCoreErrorCode`] (0 = OK, non-zero = failure) and stashes a human
//!   message in a thread-local. Read it via
//!   [`fs_core_last_error_message`].
//! - Every entry point catches Rust panics with `catch_unwind` and maps
//!   them to [`FsCoreErrorCode::Panic`]. Crossing an FFI boundary while
//!   unwinding is UB; the catch-net is non-negotiable.
//! - Thread safety: handles wrap `Arc<dyn BlockDevice>`, which is
//!   `Send + Sync` by trait bound. Multiple threads can call read/write
//!   concurrently as long as the underlying device's locking permits it.

#![allow(clippy::missing_safety_doc)]

use crate::block::BlockDevice;
use crate::callback_device::CallbackDevice;
use crate::error::Error;
use std::cell::RefCell;
use std::ffi::{c_char, c_int, c_void, CString};
use std::io;
use std::panic::AssertUnwindSafe;
use std::ptr;
use std::slice;
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Error codes — kept dense and stable so consumers can hard-code them.
// ---------------------------------------------------------------------------

/// Numeric error codes mirrored across every sister crate's C ABI.
///
/// `#[repr(i32)]` so the layout is identical to the matching C `enum`.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FsCoreErrorCode {
    /// Success.
    Ok = 0,
    /// Underlying I/O failed.
    Io = 1,
    /// A read the source could not satisfy in full — it ran out of data.
    /// What a file-backed handle returns for a read off the end of the
    /// file, and what a slice returns for a read past its own end.
    ShortRead = 2,
    /// Write attempted on a read-only device.
    ReadOnly = 3,
    /// A request refused up front because its range lies outside the
    /// device's declared size; nothing was transferred.
    ///
    /// This crate returns it only for a **write** past the end of an RW
    /// slice. It reaches **reads** from sister crates whose container
    /// declares a virtual size (the `img-*` readers), and from this
    /// crate's caching / read-only / slice wrappers when they forward
    /// such a parent's error. A C consumer that only wants to know "the
    /// read overran the device", and does not control which crate opened
    /// the handle, should accept this and `FS_CORE_SHORT_READ` alike —
    /// and should not treat the pair as exhaustive, since a
    /// callback-backed handle reports its host's refusal as
    /// `FS_CORE_IO`.
    OutOfBounds = 4,
    /// Driver-specific error — message in the thread-local last-error.
    Custom = 5,
    /// One of the input pointers was null.
    NullArg = 6,
    /// `catch_unwind` caught a panic crossing the FFI boundary.
    Panic = 7,
    /// Reserved. Never returned.
    ///
    /// It was meant for a path that is not valid UTF-8, but the one
    /// function that meets that case — `fs_core_open_file` — returns a
    /// POINTER, not a code, so it reports the failure as NULL plus a
    /// message and cannot return this. No other entry point takes a
    /// path.
    ///
    /// Kept rather than removed because the numbering is published in
    /// `include/fs_core.h` and a consumer may already switch on 8;
    /// renumbering the codes after it would be an ABI break for a
    /// tidiness gain. A future path-taking function that returns a code
    /// should use this rather than invent another.
    BadString = 8,
}

impl FsCoreErrorCode {
    fn from_error(e: &Error) -> Self {
        match e {
            Error::Io(_) => FsCoreErrorCode::Io,
            Error::ShortRead { .. } => FsCoreErrorCode::ShortRead,
            Error::ReadOnly => FsCoreErrorCode::ReadOnly,
            Error::OutOfBounds { .. } => FsCoreErrorCode::OutOfBounds,
            Error::Custom(_) => FsCoreErrorCode::Custom,
        }
    }
}

// ---------------------------------------------------------------------------
// Thread-local last-error — errno-style detail companion.
// ---------------------------------------------------------------------------

thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

/// Stash a message in the thread-local, replacing any previous one. Public
/// to sister crates so they can populate it for their own error paths.
pub fn set_last_error(message: impl Into<String>) {
    let s = message.into();
    let cs = CString::new(s.replace('\0', "?")).expect("contains no NUL after replace");
    LAST_ERROR.with(|slot| {
        *slot.borrow_mut() = Some(cs);
    });
}

fn clear_last_error() {
    LAST_ERROR.with(|slot| {
        *slot.borrow_mut() = None;
    });
}

/// Return a pointer to the calling thread's most recent error message, or
/// NULL if there is none. The pointer is owned by the framework and remains
/// valid until the next FFI call on this thread.
#[unsafe(no_mangle)]
pub extern "C" fn fs_core_last_error_message() -> *const c_char {
    LAST_ERROR.with(|slot| {
        slot.borrow()
            .as_ref()
            .map(|cs| cs.as_ptr())
            .unwrap_or(ptr::null())
    })
}

/// Helper for sister crates: run `body`, catch panics, map errors to codes,
/// stash the message in the thread-local. Returns the error code.
pub fn ffi_guard<F>(body: F) -> FsCoreErrorCode
where
    F: FnOnce() -> Result<(), Error>,
{
    clear_last_error();
    match std::panic::catch_unwind(AssertUnwindSafe(body)) {
        Ok(Ok(())) => FsCoreErrorCode::Ok,
        Ok(Err(e)) => {
            let code = FsCoreErrorCode::from_error(&e);
            set_last_error(e.to_string());
            code
        }
        Err(panic) => {
            set_last_error(panic_message(&panic));
            FsCoreErrorCode::Panic
        }
    }
}

/// Run `body`, catching a panic and returning `fail` instead — and
/// recording the panic's message where a caller can read it.
///
/// # Why the message matters more than the fallback
///
/// Every fallback value here is also a legitimate answer. Zero is what
/// an empty device reports for its size; `false` is what a read-only
/// device reports for writability; a null pointer is what a failed open
/// returns. So a caller that only sees the fallback cannot tell an
/// ordinary answer from a driver that exploded computing it.
///
/// [`fs_core_last_error_message`] is what separates them, and a guard
/// that returns the fallback without setting it throws away the only
/// evidence there was.
///
/// # Why this is separate from [`ffi_guard`]
///
/// `ffi_guard` returns an [`FsCoreErrorCode`] and takes a body that
/// returns `Result<(), Error>`. That fits an entry point whose whole
/// answer is a status code, and fits nothing else — which is why the
/// eight entry points in this file that return a size, a flag or a
/// pointer each wrote `catch_unwind(AssertUnwindSafe(…)).unwrap_or(…)`
/// by hand instead, sixty lines below the helper.
///
/// Sister crates did the same: eleven of them re-roll one of these two
/// shapes rather than share either.
///
/// The error slot is cleared on entry, like [`ffi_guard`]: a call that
/// succeeds must not leave the previous call's message in place for a
/// caller to read and attribute to this one.
///
/// `AssertUnwindSafe` is used deliberately. The bodies here touch a
/// handle the caller owns and a thread-local error slot; a panic can
/// leave neither in a state another call can observe as inconsistent,
/// because the handle is not read again on this path and the slot is
/// overwritten whole.
pub fn ffi_guard_or<T, F>(fail: T, body: F) -> T
where
    F: FnOnce() -> T,
{
    clear_last_error();
    match std::panic::catch_unwind(AssertUnwindSafe(body)) {
        Ok(value) => value,
        Err(panic) => {
            set_last_error(panic_message(&panic));
            fail
        }
    }
}

/// What a caught panic actually said.
///
/// PUBLIC BECAUSE THE OTHER ELEVEN CRATES NEED IT. Each of them guards
/// its own C entry points with `catch_unwind` and, having no way to
/// reach this, reports the panic as `"panic in <function>"` -- the name
/// of the function that was running, which the caller already knew, in
/// place of the message, which is the only part it did not. An index
/// out of bounds, a slice out of range, an `expect` with a sentence in
/// it: all of it was thrown away at the boundary.
///
/// The guards themselves are NOT shareable, and that is why this is
/// what moved rather than [`ffi_guard`]. Each crate's guard records the
/// message into that crate's own thread-local, which is what its own C
/// callers read; a guard from here would record into this crate's, and
/// every panic message would land in a slot nobody reads.
pub fn panic_message(panic: &Box<dyn std::any::Any + Send>) -> String {
    if let Some(s) = panic.downcast_ref::<&'static str>() {
        return (*s).to_string();
    }
    if let Some(s) = panic.downcast_ref::<String>() {
        return s.clone();
    }
    "panic in FFI".to_string()
}

// ---------------------------------------------------------------------------
// Device handle — opaque to C callers, shared across crates.
// ---------------------------------------------------------------------------

/// Opaque handle wrapping an `Arc<dyn BlockDevice>`. Allocated by sister
/// crates' constructors and freed via [`fs_core_device_close`].
pub struct FsCoreDevice {
    inner: Arc<dyn BlockDevice>,
}

impl FsCoreDevice {
    /// Internal constructor — sister crates use this to wrap their own
    /// device types (Qcow2Reader, FileDevice, OwnedSlice, etc.) into the
    /// shared handle type. Returns a `Box::into_raw` pointer ready to hand
    /// across the FFI boundary.
    pub fn into_handle(inner: Arc<dyn BlockDevice>) -> *mut FsCoreDevice {
        Box::into_raw(Box::new(FsCoreDevice { inner }))
    }

    /// Borrow the inner device. `Arc::clone` it if you want shared
    /// ownership — e.g. when handing the device to a slice adapter while
    /// keeping the original handle alive.
    pub fn inner(&self) -> &Arc<dyn BlockDevice> {
        &self.inner
    }
}

/// Free a device handle. Safe to call with NULL (no-op).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_close(handle: *mut FsCoreDevice) {
    if handle.is_null() {
        return;
    }
    ffi_guard_or((), || unsafe {
        drop(Box::from_raw(handle));
    });
}

/// Total device size in bytes. Returns 0 if `handle` is NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_size_bytes(handle: *const FsCoreDevice) -> u64 {
    if handle.is_null() {
        return 0;
    }
    ffi_guard_or(0, || unsafe { (*handle).inner.size_bytes() })
}

/// True if `write_at` is likely to succeed. Returns false on NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_is_writable(handle: *const FsCoreDevice) -> bool {
    if handle.is_null() {
        return false;
    }
    ffi_guard_or(false, || unsafe { (*handle).inner.is_writable() })
}

/// Read exactly `len` bytes from `offset` into `buf`. `buf` must be at
/// least `len` bytes. Returns an `FsCoreErrorCode`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_read_at(
    handle: *const FsCoreDevice,
    offset: u64,
    buf: *mut u8,
    len: usize,
) -> FsCoreErrorCode {
    // A null buffer is refused whatever the length. `from_raw_parts_mut`
    // requires a non-null, aligned pointer even for a zero-length slice,
    // so `(NULL, 0)` was undefined behaviour rather than the no-op it
    // looks like -- in a crate that otherwise denies
    // `unsafe_op_in_unsafe_fn`.
    if handle.is_null() || buf.is_null() {
        return FsCoreErrorCode::NullArg;
    }
    ffi_guard(|| {
        let slice_buf = unsafe { slice::from_raw_parts_mut(buf, len) };
        unsafe { (*handle).inner.read_at(offset, slice_buf) }
    })
}

/// Write exactly `len` bytes from `buf` to `offset`. Returns `ReadOnly`
/// for read-only devices.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_write_at(
    handle: *const FsCoreDevice,
    offset: u64,
    buf: *const u8,
    len: usize,
) -> FsCoreErrorCode {
    // Null is refused whatever the length; see `fs_core_device_read_at`.
    if handle.is_null() || buf.is_null() {
        return FsCoreErrorCode::NullArg;
    }
    ffi_guard(|| {
        let slice_buf = unsafe { slice::from_raw_parts(buf, len) };
        unsafe { (*handle).inner.write_at(offset, slice_buf) }
    })
}

/// Flush pending writes to stable storage.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_flush(handle: *const FsCoreDevice) -> FsCoreErrorCode {
    if handle.is_null() {
        return FsCoreErrorCode::NullArg;
    }
    ffi_guard(|| unsafe { (*handle).inner.flush() })
}

// ---------------------------------------------------------------------------
// Convenience: open a regular file as a device. Saves callers the trouble
// of building a Rust crate just to wrap `FileDevice`.
// ---------------------------------------------------------------------------

/// Open `path` (NUL-terminated UTF-8) as a `FileDevice` and return a
/// handle. Pass `writable=true` for RW. On failure returns NULL and the
/// thread-local last-error has detail.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_file_open(
    path: *const c_char,
    writable: bool,
) -> *mut FsCoreDevice {
    if path.is_null() {
        set_last_error("path is null");
        return ptr::null_mut();
    }
    ffi_guard_or(ptr::null_mut(), || {
        let cstr = unsafe { std::ffi::CStr::from_ptr(path) };
        let s = match cstr.to_str() {
            Ok(s) => s,
            Err(_) => {
                set_last_error("path is not valid UTF-8");
                return ptr::null_mut();
            }
        };
        let dev = if writable {
            crate::file_device::FileDevice::open_rw(s)
        } else {
            crate::file_device::FileDevice::open(s)
        };
        match dev {
            Ok(d) => FsCoreDevice::into_handle(Arc::new(d)),
            Err(e) => {
                set_last_error(e.to_string());
                ptr::null_mut()
            }
        }
    })
}

// ---------------------------------------------------------------------------
// Callback-backed device. Used when the caller already owns the underlying
// resource (FSKit FSBlockDeviceResource, Go file handle, C-side fd) and
// wants to expose it as an `FsCoreDevice` so it can be stacked under a
// container reader (qcow2, vhd, ...) before reaching a filesystem driver.
// ---------------------------------------------------------------------------

/// Read callback. Returns 0 on success, non-zero (errno-like) on failure.
/// Must fully fill `len` bytes — short reads are treated as I/O errors.
pub type FsCoreReadCb =
    Option<unsafe extern "C" fn(ctx: *mut c_void, offset: u64, buf: *mut u8, len: usize) -> c_int>;

/// Write callback. NULL → device is read-only.
pub type FsCoreWriteCb = Option<
    unsafe extern "C" fn(ctx: *mut c_void, offset: u64, buf: *const u8, len: usize) -> c_int,
>;

/// Flush/fsync callback. NULL → flush is a no-op.
pub type FsCoreFlushCb = Option<unsafe extern "C" fn(ctx: *mut c_void) -> c_int>;

/// Configuration passed to [`fs_core_device_from_callbacks`].
#[repr(C)]
pub struct FsCoreCallbackCfg {
    pub read: FsCoreReadCb,
    pub write: FsCoreWriteCb,
    pub flush: FsCoreFlushCb,
    pub ctx: *mut c_void,
    pub size: u64,
}

/// Turn a callback's non-zero return into an `io::Error`.
fn cb_io_err(rc: c_int, op: &str) -> io::Error {
    io::Error::other(format!("callback {op} returned {rc}"))
}

/// The host callback contract, in one place: **zero is success**.
///
/// All three adapters below wrapped a call in the same four lines —
/// invoke, compare against zero, `Ok(())` or `cb_io_err`. Three copies
/// of a convention is three chances to write `rc != 0` where the others
/// write `rc == 0`, and a caller would see reads succeed while writes
/// reported failure on the very same device.
///
/// `op` names the operation in the error, which is the only thing the
/// three genuinely differ in.
fn cb_result(rc: c_int, op: &'static str) -> io::Result<()> {
    if rc == 0 {
        Ok(())
    } else {
        Err(cb_io_err(rc, op))
    }
}

/// Build an [`FsCoreDevice`] backed by host-provided callbacks. Returns NULL
/// on failure (config null, read callback null, etc.) and stashes detail in
/// the thread-local last-error.
///
/// `cfg.ctx` is opaque to fs-core; it is passed back verbatim to every
/// callback invocation. The caller is responsible for ensuring it remains
/// valid until [`fs_core_device_close`] is called on the returned handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_from_callbacks(
    cfg: *const FsCoreCallbackCfg,
) -> *mut FsCoreDevice {
    if cfg.is_null() {
        set_last_error("cfg is null");
        return ptr::null_mut();
    }
    ffi_guard_or(ptr::null_mut(), || unsafe {
        let cfg = &*cfg;
        let read_fn = match cfg.read {
            Some(f) => f,
            None => {
                set_last_error("cfg.read is null");
                return ptr::null_mut();
            }
        };
        let write_fn = cfg.write;
        let flush_fn = cfg.flush;
        // `*mut c_void` is `!Send + !Sync` by default, and `unsafe impl
        // Send` on a newtype does not propagate cleanly through closure
        // auto-traits. Round-tripping the pointer through `usize` gives
        // something that is `Copy + Send + Sync`, and the callback
        // contract already puts the host on the hook for using `ctx`
        // safely across threads.
        let ctx_addr = cfg.ctx as usize;
        let size = cfg.size;

        let read_cb: crate::callback_device::ReadCb = Box::new(move |off, buf| {
            let ctx = ctx_addr as *mut c_void;
            cb_result(read_fn(ctx, off, buf.as_mut_ptr(), buf.len()), "read")
        });
        let write_cb: Option<crate::callback_device::WriteCb> = write_fn.map(|f| {
            Box::new(move |off, buf: &[u8]| {
                let ctx = ctx_addr as *mut c_void;
                cb_result(f(ctx, off, buf.as_ptr(), buf.len()), "write")
            }) as crate::callback_device::WriteCb
        });
        let flush_cb: Option<crate::callback_device::FlushCb> = flush_fn.map(|f| {
            Box::new(move || {
                let ctx = ctx_addr as *mut c_void;
                cb_result(f(ctx), "flush")
            }) as crate::callback_device::FlushCb
        });

        let dev = CallbackDevice {
            size,
            read: read_cb,
            write: write_cb,
            flush: flush_cb,
        };
        FsCoreDevice::into_handle(Arc::new(dev))
    })
}

// ---------------------------------------------------------------------------
// Slice constructor. Returns a child `FsCoreDevice` whose byte 0 maps to
// `start` of the parent and whose addressable range is `length` bytes.
// Useful for partition-table walkers that want to hand one partition to
// a filesystem driver without copying. The slice keeps an `Arc` to the
// parent, so closing the parent before the slice is fine.
// ---------------------------------------------------------------------------

/// Read-only slice. Writes via the returned handle return
/// `FS_CORE_READ_ONLY` regardless of the parent's writability.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_slice_ro(
    parent: *const FsCoreDevice,
    start: u64,
    length: u64,
) -> *mut FsCoreDevice {
    if parent.is_null() {
        set_last_error("parent is null");
        return ptr::null_mut();
    }
    ffi_guard_or(ptr::null_mut(), || unsafe {
        let parent_arc = (*parent).inner().clone();
        // OwnedSlice takes Arc<dyn BlockRead>; trait upcast from
        // BlockDevice -> BlockRead is supported in the pinned toolchain.
        let parent_read: Arc<dyn crate::block::BlockRead> = parent_arc;
        let slice = crate::slice::OwnedSlice::new(parent_read, start, length);
        FsCoreDevice::into_handle(Arc::new(slice))
    })
}

/// Read-write slice. Writes are forwarded to the parent at `start +
/// offset`; writes outside `[0, length)` return `FS_CORE_OUT_OF_BOUNDS`.
/// If the parent reports `is_writable() == false`, write attempts return
/// `FS_CORE_READ_ONLY`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fs_core_device_slice_rw(
    parent: *const FsCoreDevice,
    start: u64,
    length: u64,
) -> *mut FsCoreDevice {
    if parent.is_null() {
        set_last_error("parent is null");
        return ptr::null_mut();
    }
    ffi_guard_or(ptr::null_mut(), || unsafe {
        let parent_arc = (*parent).inner().clone();
        let slice = crate::slice::OwnedRwSlice::new(parent_arc, start, length);
        FsCoreDevice::into_handle(Arc::new(slice))
    })
}

// ---------------------------------------------------------------------------
// Tests — exercise the FFI surface from Rust. The C side is verified by
// the consumer crates that use these functions through their own headers.
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    /// THE MESSAGE, not the fact that something panicked.
    ///
    /// Both shapes a panic payload takes: `panic!("literal")` gives a
    /// `&'static str`, and `panic!("{x}")` or an out-of-bounds index
    /// gives a `String`. A guard that reports neither tells its caller
    /// only what it already knew.
    #[test]
    fn a_caught_panic_reports_what_it_said() {
        let literal =
            std::panic::catch_unwind(|| panic!("a literal message")).expect_err("it panicked");
        assert_eq!(panic_message(&literal), "a literal message");

        let owned = std::panic::catch_unwind(|| {
            let v: Vec<u8> = Vec::new();
            let _ = v[3];
        })
        .expect_err("it panicked");
        assert!(
            panic_message(&owned).contains("index out of bounds"),
            "the index panic's own words should survive: {}",
            panic_message(&owned)
        );

        // Anything else says so rather than pretending to a message.
        let odd =
            std::panic::catch_unwind(|| std::panic::panic_any(42u8)).expect_err("it panicked");
        assert_eq!(panic_message(&odd), "panic in FFI");
    }

    use super::*;
    use std::fs::File;
    use std::io::Write;

    fn tmp_image(bytes: &[u8]) -> String {
        use std::sync::atomic::{AtomicU32, Ordering};
        static C: AtomicU32 = AtomicU32::new(0);
        let n = C.fetch_add(1, Ordering::Relaxed);
        let p = std::env::temp_dir()
            .join(format!("fs_core_ffi_{}_{n}.img", std::process::id()))
            .to_string_lossy()
            .into_owned();
        File::create(&p).unwrap().write_all(bytes).unwrap();
        p
    }

    #[test]
    fn open_read_close_round_trip() {
        let path = tmp_image(b"hello, fs-core ffi");
        let cpath = CString::new(path.as_str()).unwrap();
        let h = unsafe { fs_core_file_open(cpath.as_ptr(), false) };
        assert!(!h.is_null(), "open failed");

        unsafe {
            assert_eq!(fs_core_device_size_bytes(h), 18);
            assert!(!fs_core_device_is_writable(h));

            let mut buf = [0u8; 5];
            let rc = fs_core_device_read_at(h, 0, buf.as_mut_ptr(), buf.len());
            assert_eq!(rc, FsCoreErrorCode::Ok);
            assert_eq!(&buf, b"hello");

            // Write should fail with ReadOnly.
            let rc = fs_core_device_write_at(h, 0, b"x".as_ptr(), 1);
            assert_eq!(rc, FsCoreErrorCode::ReadOnly);

            fs_core_device_close(h);
        }
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn null_args_return_null_arg() {
        let mut buf = [0u8; 4];
        let rc = unsafe { fs_core_device_read_at(ptr::null(), 0, buf.as_mut_ptr(), buf.len()) };
        assert_eq!(rc, FsCoreErrorCode::NullArg);
        let rc = unsafe { fs_core_device_flush(ptr::null()) };
        assert_eq!(rc, FsCoreErrorCode::NullArg);
    }

    #[test]
    fn last_error_populated_on_open_failure() {
        let cpath = CString::new("/path/that/does/not/exist/we/hope").unwrap();
        let h = unsafe { fs_core_file_open(cpath.as_ptr(), false) };
        assert!(h.is_null());
        let msg = fs_core_last_error_message();
        assert!(!msg.is_null());
        let s = unsafe { std::ffi::CStr::from_ptr(msg).to_string_lossy().into_owned() };
        assert!(!s.is_empty(), "expected an error message");
    }

    // ---- callback-backed device tests --------------------------------

    use std::sync::{Arc as StdArc, Mutex as StdMutex};

    struct CbState {
        data: Vec<u8>,
        flushed: u32,
    }

    /// Trampoline that pulls a `*mut CbState` out of the opaque ctx.
    unsafe extern "C" fn t_read(ctx: *mut c_void, offset: u64, buf: *mut u8, len: usize) -> c_int {
        let st = unsafe { &mut *(ctx as *mut CbState) };
        let off = offset as usize;
        if off + len > st.data.len() {
            return 5; // out of bounds
        }
        unsafe {
            std::ptr::copy_nonoverlapping(st.data.as_ptr().add(off), buf, len);
        }
        0
    }
    unsafe extern "C" fn t_write(
        ctx: *mut c_void,
        offset: u64,
        buf: *const u8,
        len: usize,
    ) -> c_int {
        let st = unsafe { &mut *(ctx as *mut CbState) };
        let off = offset as usize;
        if off + len > st.data.len() {
            return 5;
        }
        unsafe {
            std::ptr::copy_nonoverlapping(buf, st.data.as_mut_ptr().add(off), len);
        }
        0
    }
    unsafe extern "C" fn t_flush(ctx: *mut c_void) -> c_int {
        let st = unsafe { &mut *(ctx as *mut CbState) };
        st.flushed += 1;
        0
    }

    #[test]
    fn callback_device_round_trip_rw() {
        let mut st = Box::new(CbState {
            data: vec![0u8; 32],
            flushed: 0,
        });
        for (i, b) in st.data.iter_mut().enumerate() {
            *b = i as u8;
        }
        let ctx = &mut *st as *mut CbState as *mut c_void;

        let cfg = FsCoreCallbackCfg {
            read: Some(t_read),
            write: Some(t_write),
            flush: Some(t_flush),
            ctx,
            size: 32,
        };
        let h = unsafe { fs_core_device_from_callbacks(&cfg) };
        assert!(!h.is_null(), "device_from_callbacks returned NULL");

        unsafe {
            assert_eq!(fs_core_device_size_bytes(h), 32);
            assert!(fs_core_device_is_writable(h));

            let mut buf = [0u8; 4];
            let rc = fs_core_device_read_at(h, 4, buf.as_mut_ptr(), buf.len());
            assert_eq!(rc, FsCoreErrorCode::Ok);
            assert_eq!(buf, [4, 5, 6, 7]);

            let payload = [0xDE, 0xAD, 0xBE, 0xEF];
            let rc = fs_core_device_write_at(h, 8, payload.as_ptr(), payload.len());
            assert_eq!(rc, FsCoreErrorCode::Ok);

            let rc = fs_core_device_flush(h);
            assert_eq!(rc, FsCoreErrorCode::Ok);

            let mut readback = [0u8; 4];
            let rc = fs_core_device_read_at(h, 8, readback.as_mut_ptr(), readback.len());
            assert_eq!(rc, FsCoreErrorCode::Ok);
            assert_eq!(readback, payload);

            fs_core_device_close(h);
        }
        assert_eq!(st.flushed, 1);
        assert_eq!(&st.data[8..12], &[0xDE, 0xAD, 0xBE, 0xEF]);
    }

    #[test]
    fn callback_device_readonly_when_write_null() {
        let mut st = Box::new(CbState {
            data: vec![0xAAu8; 16],
            flushed: 0,
        });
        let ctx = &mut *st as *mut CbState as *mut c_void;
        let cfg = FsCoreCallbackCfg {
            read: Some(t_read),
            write: None,
            flush: None,
            ctx,
            size: 16,
        };
        let h = unsafe { fs_core_device_from_callbacks(&cfg) };
        assert!(!h.is_null());
        unsafe {
            assert!(!fs_core_device_is_writable(h));
            let rc = fs_core_device_write_at(h, 0, [1u8].as_ptr(), 1);
            assert_eq!(rc, FsCoreErrorCode::ReadOnly);
            // Flush is a no-op when callback is NULL.
            assert_eq!(fs_core_device_flush(h), FsCoreErrorCode::Ok);
            fs_core_device_close(h);
        }
        // suppress unused warning
        let _ = StdArc::new(StdMutex::new(0u8));
    }

    #[test]
    fn callback_device_null_cfg_returns_null() {
        let h = unsafe { fs_core_device_from_callbacks(ptr::null()) };
        assert!(h.is_null());
        let msg = fs_core_last_error_message();
        assert!(!msg.is_null());
    }
}

#[cfg(test)]
mod panic_message_tests {
    use super::*;
    use crate::block::{BlockDevice, BlockRead};

    /// A device whose every method panics.
    ///
    /// Not a hypothetical: a driver's `size_bytes` computes a geometry
    /// from on-disk fields, and an arithmetic overflow there panics.
    /// The FFI boundary is where that has to stop being a panic and
    /// start being a reportable error.
    struct Panicking;

    impl BlockRead for Panicking {
        fn read_at(&self, _offset: u64, _buf: &mut [u8]) -> Result<(), Error> {
            panic!("read_at exploded")
        }
        fn size_bytes(&self) -> u64 {
            panic!("size_bytes exploded")
        }
    }
    impl BlockDevice for Panicking {
        fn is_writable(&self) -> bool {
            panic!("is_writable exploded")
        }
    }

    fn handle() -> *mut FsCoreDevice {
        FsCoreDevice::into_handle(std::sync::Arc::new(Panicking))
    }

    fn last_error() -> Option<String> {
        let p = fs_core_last_error_message();
        if p.is_null() {
            return None;
        }
        Some(
            unsafe { std::ffi::CStr::from_ptr(p) }
                .to_string_lossy()
                .into_owned(),
        )
    }

    /// A panic caught at the boundary must leave a message behind.
    ///
    /// `fs_core_device_size_bytes` returns 0 on panic — and 0 is also
    /// what a legitimately empty device returns. Without a message the
    /// caller cannot tell "this device is empty" from "the driver
    /// exploded computing its size", which is the whole reason the
    /// thread-local error slot exists.
    #[test]
    fn a_panic_computing_the_size_is_reported_not_just_swallowed() {
        clear_last_error();
        let h = handle();
        let size = unsafe { fs_core_device_size_bytes(h) };
        assert_eq!(size, 0, "the fallback value is still returned");
        let msg = last_error().expect("a caught panic must leave a message");
        assert!(
            msg.contains("size_bytes exploded"),
            "the message should carry the panic's own text, got: {msg}"
        );
        unsafe { fs_core_device_close(h) };
    }

    /// Same for the writability probe, whose fallback is `false` — the
    /// answer a perfectly good read-only device gives.
    #[test]
    fn a_panic_probing_writability_is_reported() {
        clear_last_error();
        let h = handle();
        let writable = unsafe { fs_core_device_is_writable(h) };
        assert!(!writable, "the fallback value is still returned");
        assert!(
            last_error().is_some(),
            "a caught panic must leave a message"
        );
        unsafe { fs_core_device_close(h) };
    }

    /// A call that succeeds must not leave a stale message behind for
    /// the next one to pick up.
    #[test]
    fn a_successful_call_clears_the_previous_error() {
        let h = handle();
        let _ = unsafe { fs_core_device_size_bytes(h) };
        assert!(last_error().is_some(), "setup: an error is recorded");
        unsafe { fs_core_device_close(h) };

        struct Sixteen;
        impl BlockRead for Sixteen {
            fn read_at(&self, _offset: u64, _buf: &mut [u8]) -> Result<(), Error> {
                Ok(())
            }
            fn size_bytes(&self) -> u64 {
                16
            }
        }
        impl BlockDevice for Sixteen {}
        let h2 = FsCoreDevice::into_handle(std::sync::Arc::new(Sixteen));
        assert_eq!(unsafe { fs_core_device_size_bytes(h2) }, 16);
        assert!(
            last_error().is_none(),
            "a call that worked must not leave the previous panic's message in place"
        );
        unsafe { fs_core_device_close(h2) };
    }
}