diff --git a/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs b/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs index 7b512589..91130a67 100644 --- a/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs +++ b/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs @@ -43,6 +43,7 @@ mod platform { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: `self.0` is the single non-null dlopen reference `load` took; closed once with the table. unsafe { libc::dlclose(self.0); } @@ -66,6 +67,7 @@ mod platform { } impl Api { pub(crate) fn load() -> Result { + // SAFETY: fixed NUL-terminated library name and flags. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -73,6 +75,7 @@ mod platform { return Err(Error::LibraryUnavailable); } fn symbol(l: &Library, n: &'static CStr) -> Result { + // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; if p.is_null() { Err(Error::MissingSymbol( @@ -82,9 +85,11 @@ mod platform { Ok(p) } } + // SAFETY: non-null `cuLaunchKernel` address; `Launch` is its exact Linux64 C signature. let launch = unsafe { std::mem::transmute::(symbol(&library, c"cuLaunchKernel")?) }; + // SAFETY: non-null `cuMemcpyHtoDAsync_v2` address; `H2D` is its exact Linux64 C signature. let copy = unsafe { std::mem::transmute::(symbol(&library, c"cuMemcpyHtoDAsync_v2")?) }; @@ -106,6 +111,8 @@ mod platform { return Err(Error::InvalidProjectionShape); } destination.validate_projection_extent(source.len(), 16)?; + // SAFETY: destination extent validated (16-byte aligned) and `source` is a registered immutable bank slice the ring keeps retained + // (`Ring.bank` Rc) until `Ring::drain`/close synchronized this non-default `stream`. check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy)( destination.0, @@ -175,6 +182,8 @@ mod platform { }; // Same literal launch geometries/owned ABI as ffi.rs old methods; // only the genuine private scheduling stream replaces null/default. + // SAFETY: `f` is an admitted module function; `parameters` points into the heap-boxed argument struct of `command`, which the ring/transport + // keeps (`commands` Vec, capacity reserved up front) until its stream drained; the driver copies the parameter values at launch. check("cuLaunchKernel", unsafe { (self.launch)( f.0 as Handle, diff --git a/crates/cuda-driver/src/mtp_original_full_ffi.rs b/crates/cuda-driver/src/mtp_original_full_ffi.rs index 8a27bc36..ca6eb50f 100644 --- a/crates/cuda-driver/src/mtp_original_full_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_full_ffi.rs @@ -34,6 +34,16 @@ impl Arguments { } #[repr(C)] pub(crate) struct Copy2D {src_x:usize,src_y:usize,src_type:u32,src_host:*const c_void,src_dev:u64,src_array:*mut c_void,src_pitch:usize,dst_x:usize,dst_y:usize,dst_type:u32,dst_host:*mut c_void,dst_dev:u64,dst_array:*mut c_void,dst_pitch:usize,width:usize,height:usize} +// Must stay bit-identical to CUDA_MEMCPY2D (LP64): the driver reads it through a raw pointer in `copy2d`. +#[cfg(target_pointer_width = "64")] +const _: () = { + assert!(std::mem::size_of::() == 128 && std::mem::align_of::() == 8); + assert!(std::mem::offset_of!(Copy2D, src_type) == 16 && std::mem::offset_of!(Copy2D, src_host) == 24); + assert!(std::mem::offset_of!(Copy2D, src_dev) == 32 && std::mem::offset_of!(Copy2D, src_pitch) == 48); + assert!(std::mem::offset_of!(Copy2D, dst_type) == 72 && std::mem::offset_of!(Copy2D, dst_host) == 80); + assert!(std::mem::offset_of!(Copy2D, dst_dev) == 88 && std::mem::offset_of!(Copy2D, dst_pitch) == 104); + assert!(std::mem::offset_of!(Copy2D, width) == 112 && std::mem::offset_of!(Copy2D, height) == 120); +}; impl Copy2D{pub(crate) fn q_split(src:u64,dst:u64)->Self{Self{src_x:0,src_y:0,src_type:2,src_host:std::ptr::null(),src_dev:src,src_array:std::ptr::null_mut(),src_pitch:512*4,dst_x:0,dst_y:0,dst_type:2,dst_host:std::ptr::null_mut(),dst_dev:dst,dst_array:std::ptr::null_mut(),dst_pitch:256*4,width:256*4,height:24}}} #[cfg(all( feature = "cuda-driver", @@ -70,6 +80,7 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -88,10 +99,13 @@ mod enabled { } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -114,6 +128,7 @@ mod enabled { if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { return Err(Error::UnsupportedQwenOperation); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -125,12 +140,18 @@ mod enabled { let dev = sym!(l, c"cuCtxGetDevice", Device); let attr = sym!(l, c"cuDeviceGetAttribute", Attr); let mut device = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuCtxGetDevice", unsafe { dev(&mut device) })?; let mut major = 0; let mut shared = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; @@ -156,6 +177,8 @@ mod enabled { .map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; @@ -165,6 +188,8 @@ mod enabled { owner.module = Some(m as usize); for n in entries { let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); @@ -183,9 +208,13 @@ mod enabled { pub(crate) fn configure_gr(&self)->Result<(usize,usize)> { let l=self.library.as_ref().ok_or(Error::ContextPoisoned)?; let device=sym!(l,c"cuCtxGetDevice",Device);let attr=sym!(l,c"cuDeviceGetAttribute",Attr); + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). let mut d=0;check("cuCtxGetDevice",unsafe{device(&mut d)})?; let mut optin=0;let mut major=0;let mut minor=0;let mut per_block=0; for (value,key) in [(&mut optin,97),(&mut major,75),(&mut minor,76),(&mut per_block,8)]{ + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute(GR)",unsafe{attr(value,key,d)})?; } let tile=if major*10+minor==75{1280}else{2560}; @@ -195,6 +224,8 @@ mod enabled { for (index,want) in [(if tile==1280{4}else{5},8*tile*4),(2,2*8*1280*4)]{ let want=if optin>0{want.min(optin as usize)}else{want}; let function=*self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; + // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); + // attribute id and value are plain integers. check("cuFuncSetAttribute",unsafe{(self.attr)(function as *mut c_void,8,want as i32)})?; } Ok((usable as usize,tile)) @@ -231,6 +262,11 @@ mod enabled { Arg::Params(x) => (x as *mut crate::SamplerParams).cast(), }); } + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. check("cuLaunchKernel", unsafe { (self.launch)( f as *mut c_void, @@ -250,13 +286,25 @@ mod enabled { // Addresses are derived only by this producer from actual whole owners. pub(crate) fn copy(&self,dst:u64,src:u64,n:usize,stream:usize)->Result<()> { if n==0 || stream==0 || dst==0 || src==0 { return Err(Error::InvalidSize); } + // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents + // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners + // must outlive the stream drain (graph resources / Context::synchronize on every close path). check("cuMemcpyAsync",unsafe{(self.copy)(dst,src,n,stream as *mut c_void)}) } + // SAFETY: same address provenance as `copy`; n > 0. cuMemcpy returns after completion only for device->host destinations; + // a device->device copy is merely ordered on the legacy default stream (callers: mtp_original_full_round.rs). pub(crate) fn copy_sync(&self,dst:u64,src:u64,n:usize)->Result<()>{if dst==0||src==0||n==0{return Err(Error::InvalidSize);}check("cuMemcpy",unsafe{(self.copy_sync)(dst,src,n)})} + // SAFETY: dst/n describe a device range the caller validated against a whole owner. cuMemsetD8_v2 is ordered on the legacy + // default stream but asynchronous with respect to the host; its only caller (FullOwned::new_internal) fences it. pub(crate) fn zero(&self,dst:u64,n:usize)->Result<()>{if dst==0||n==0{return Err(Error::InvalidSize);}check("cuMemsetD8_v2",unsafe{(self.memset)(dst,0,n)})} + // SAFETY: `descriptor` is a #[repr(C)] CUDA_MEMCPY2D (layout asserted at compile time above) read by the driver during + // this call only; its src/dst are device addresses of live whole owners sized for pitch*height (see the q_split test). pub(crate) fn copy2d(&self,descriptor:&Copy2D,stream:usize)->Result<()>{if stream==0{return Err(Error::InvalidQwenShape);}check("cuMemcpy2DAsync_v2",unsafe{(self.c2d)(descriptor,stream as *mut c_void)})} pub(crate) fn copy_host(&self,dst:u64,source:&[u8],stream:usize)->Result<()> { if dst==0||source.is_empty()||stream==0{return Err(Error::InvalidSize);} + // SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable source is staged by the + // driver before return; callers additionally retain the bytes (OriginalMtpScalarPrefill::pending_host) until the stream is + // drained, so even a pinned-source (fully asynchronous) copy would read valid memory. check("cuMemcpyHtoDAsync_v2",unsafe{(self.h2d)(dst,source.as_ptr().cast(),source.len(),stream as *mut c_void)}) } pub(crate) fn close(mut self) -> Result<()> { @@ -264,6 +312,8 @@ mod enabled { } fn close_inner(&mut self) -> Result<()> { if let Some(m) = self.module.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); if r.is_err() && let Some(l) = self.library.take() @@ -325,4 +375,25 @@ impl Module { Ok(()) } } - +#[cfg(test)] +mod tests { + use super::*; + /// `copy2d` hands the driver a raw descriptor of fixed extents; the two owners it names (`TailLayout` roles + /// 0 = qfull and 1 = qcur, both whole device owners) must cover the last byte it touches for every T. + #[test] + fn q_split_descriptor_stays_inside_both_tail_owners() { + let d = Copy2D::q_split(0x1000, 0x2000_0000); + assert!(d.width <= d.src_pitch && d.width <= d.dst_pitch); + let src_end = (d.height - 1) * d.src_pitch + d.width; + let dst_end = (d.height - 1) * d.dst_pitch + d.width; + for t in 1..=8 { + let layout = super::super::TailLayout::new(248_320, t, false).expect("tail layout"); + assert!(src_end <= layout.sizes[0], "T={t}: source span {src_end} > {}", layout.sizes[0]); + assert!(dst_end <= layout.sizes[1], "T={t}: destination span {dst_end} > {}", layout.sizes[1]); + } + // device -> device through UVA addresses only: no host pointer or array may be smuggled in. + assert_eq!((d.src_type, d.dst_type), (2, 2)); + assert!(d.src_host.is_null() && d.dst_host.is_null() && d.src_array.is_null() && d.dst_array.is_null()); + assert_eq!((d.src_x, d.src_y, d.dst_x, d.dst_y), (0, 0, 0, 0)); + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_mapped.rs b/crates/cuda-driver/src/mtp_original_full_mapped.rs index 0442e9b3..cefd5a36 100644 --- a/crates/cuda-driver/src/mtp_original_full_mapped.rs +++ b/crates/cuda-driver/src/mtp_original_full_mapped.rs @@ -15,6 +15,7 @@ mod mapped_enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -33,10 +34,13 @@ mod mapped_enabled { } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -55,6 +59,7 @@ mod mapped_enabled { } let records = max_t * 236 + 384 + if coupled { 64 + 4096 * 4 } else { 0 }; let bytes = ((records + 255) & !255) + max_t * 40960; + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -65,6 +70,8 @@ mod mapped_enabled { let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is + // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); @@ -77,6 +84,7 @@ mod mapped_enabled { bytes, shared: None, }; + // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); @@ -89,6 +97,8 @@ mod mapped_enabled { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } + // SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes + // the block fully initialized before the first CPU read. unsafe { std::ptr::write_bytes(ptr.cast::(), 0, bytes); } // initialized final whole owner; never resized. @@ -122,6 +132,9 @@ mod mapped_enabled { } pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and + // `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference + // ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range. unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); } @@ -130,6 +143,8 @@ mod mapped_enabled { pub(crate) fn read(&self, o: usize, b: &mut [u8]) -> Result<()> { let p = self.range(o, b.len())?; for (i, dst) in b.iter_mut().enumerate() { + // SAFETY: (p + i) < p + b.len() is inside the range proved by range(); volatile because the GPU may have written the + // byte, and callers read only after the producing stream was drained. *dst = unsafe { std::ptr::read_volatile((p + i) as *const u8) }; } Ok(()) @@ -143,6 +158,8 @@ mod mapped_enabled { { return Err(Error::InvalidQwenShape); } + // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every + // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; self.host = None; self.alias = 0; @@ -160,6 +177,99 @@ mod mapped_enabled { } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ } } + // Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting + // function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. + #[cfg(test)] + mod tests { + use super::*; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + use std::sync::Mutex; + static FREED: Mutex> = Mutex::new(Vec::new()); + extern "C" fn fake_free(p: *mut c_void) -> i32 { + FREED.lock().unwrap().push(p as usize); + 0 + } + fn frees(p: usize) -> usize { + FREED.lock().unwrap().iter().filter(|q| **q == p).count() + } + struct Block(*mut u8, Layout); + impl Block { + fn new(total: usize) -> Self { + let layout = Layout::from_size_align(total, 256).unwrap(); + // SAFETY: nonzero size and a valid layout; null is rejected below. + let p = unsafe { alloc_zeroed(layout) }; + assert!(!p.is_null()); + FREED.lock().unwrap().retain(|q| *q != p as usize); + Self(p, layout) + } + fn addr(&self) -> usize { + self.0 as usize + } + #[allow(dead_code)] + fn byte(&self, i: usize) -> u8 { + // SAFETY: tests only pass i < the block's total size. + unsafe { *self.0.add(i) } + } + } + impl Drop for Block { + fn drop(&mut self) { + // SAFETY: allocated in `new` with exactly this layout and freed once. + unsafe { dealloc(self.0, self.1) } + } + } + const BYTES: usize = 1024; + fn owner(b: &Block) -> MappedOwner { + MappedOwner { + library: None, + host: Some(b.addr()), + alias: b.addr() as u64, + free: fake_free, + bytes: BYTES, + shared: None, + } + } + #[test] + fn mapped_audit_full_write_and_read_never_leave_the_block() { + let b = Block::new(BYTES + 256); + let mut o = owner(&b); + o.write(BYTES - 1, &[7]).unwrap(); + assert_eq!(b.byte(BYTES - 1), 7); + assert_eq!(o.write(BYTES - 1, &[1, 2]), Err(Error::InvalidSize)); + assert_eq!(o.write(usize::MAX, &[1, 2]), Err(Error::InvalidSize)); + assert_eq!(o.write(0, &[]), Err(Error::InvalidSize)); + assert_eq!(b.byte(BYTES), 0, "the byte after the owner must stay untouched"); + let mut out = [0u8; 1]; + o.read(BYTES - 1, &mut out).unwrap(); + assert_eq!(out, [7]); + assert_eq!(o.read(BYTES, &mut out), Err(Error::InvalidSize)); + assert_eq!(o.address(BYTES - 8, 8), Ok(b.addr() as u64 + (BYTES - 8) as u64)); + assert_eq!(o.address(BYTES - 8, 9), Err(Error::InvalidSize)); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.write(0, &[1]), Err(Error::ContextPoisoned), "no access after the block was freed"); + assert_eq!(frees(b.addr()), 1); + } + #[test] + fn mapped_audit_full_close_refuses_while_a_view_holds_the_records() { + let b = Block::new(BYTES); + let records = Rc::new(RefCell::new(Records::borrowed(b.addr(), b.addr() as u64, BYTES).unwrap())); + let mut o = owner(&b); + o.shared = Some(Rc::clone(&records)); + let view = records; // what the scalar view / a captured graph resource retains + assert_eq!(o.close(), Err(Error::InvalidQwenShape)); + assert_eq!(frees(b.addr()), 0, "a live view must keep the host block allocated"); + assert!(o.host.is_some()); + drop(view); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.close(), Ok(())); + assert_eq!(frees(b.addr()), 1, "freed exactly once"); + } + #[test] + fn mapped_audit_full_drop_without_close_never_frees() { + let b = Block::new(BYTES); + drop(owner(&b)); + assert_eq!(frees(b.addr()), 0, "an unclosed owner leaks instead of freeing under possible DMA"); + } + } } #[cfg(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi.rs b/crates/cuda-driver/src/mtp_original_int8_ffi.rs index 52273cd2..22a34c4e 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi.rs @@ -59,6 +59,7 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -77,10 +78,13 @@ mod enabled { } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -97,6 +101,7 @@ mod enabled { if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { return Err(Error::UnsupportedQwenOperation); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -108,12 +113,18 @@ mod enabled { let dev = sym!(l, c"cuCtxGetDevice", Device); let attr = sym!(l, c"cuDeviceGetAttribute", Attr); let mut device = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuCtxGetDevice", unsafe { dev(&mut device) })?; let mut major = 0; let mut shared = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; @@ -134,6 +145,8 @@ mod enabled { .map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; @@ -143,6 +156,8 @@ mod enabled { owner.module = Some(m as usize); for n in entries { let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); @@ -188,6 +203,11 @@ mod enabled { Arg::F32(x) => (x as *mut f32).cast(), }); } + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. check("cuLaunchKernel", unsafe { (self.launch)( f as *mut c_void, @@ -209,6 +229,9 @@ mod enabled { if n == 0 || stream == 0 || dst == 0 || src == 0 { return Err(Error::InvalidSize); } + // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents + // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners + // must outlive the stream drain (graph resources / Context::synchronize on every close path). check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) }) @@ -218,6 +241,8 @@ mod enabled { } fn close_inner(&mut self) -> Result<()> { if let Some(m) = self.module.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); if r.is_err() && let Some(l) = self.library.take() @@ -292,6 +317,7 @@ mod host_enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -310,10 +336,13 @@ mod host_enabled { } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -338,6 +367,7 @@ mod host_enabled { if !matches!(bytes, 20 | 96 | HOST_BYTES) { return Err(Error::InvalidSize); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -348,6 +378,8 @@ mod host_enabled { let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is + // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); @@ -359,6 +391,7 @@ mod host_enabled { free, bytes, }; + // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); @@ -381,6 +414,8 @@ mod host_enabled { } return Err(Error::InvalidDriverValue("mapped-host-alignment")); } + // SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes + // the block fully initialized before the first CPU read. unsafe { std::ptr::write_bytes(ptr.cast::(), 0, bytes); } // initialized final whole owner; never resized. @@ -395,6 +430,8 @@ mod host_enabled { type Zero = unsafe extern "C" fn(u64, u8, usize, *mut c_void) -> i32; let library = self.library.as_ref().ok_or(Error::ContextPoisoned)?; let zero = sym!(library, c"cuMemsetD8Async", Zero); + // SAFETY: destination/bytes are a caller-validated whole device span; the memset is enqueued on the legacy default + // stream and the caller drains (Context::synchronize) before the span is read or freed. check("cuMemsetD8Async", unsafe { zero(destination, 0, bytes, std::ptr::null_mut()) }) @@ -417,6 +454,9 @@ mod host_enabled { } pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and + // `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference + // ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range. unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); } @@ -425,6 +465,8 @@ mod host_enabled { /// CPU access only after the real producer stream drained. pub(crate) fn read_into(&self, o: usize, b: &mut [u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation and `b` is a distinct Rust slice. CPU reads happen only + // after the producing stream was drained (documented at each call site); GPU-written bytes are plain integers. unsafe { std::ptr::copy_nonoverlapping(p as *const u8, b.as_mut_ptr(), b.len()); } @@ -432,6 +474,8 @@ mod host_enabled { } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { + // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every + // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; self.host = None; self.alias = 0; @@ -448,6 +492,83 @@ mod host_enabled { } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ } } + // Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting + // function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. + #[cfg(test)] + mod tests { + use super::*; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + use std::sync::Mutex; + static FREED: Mutex> = Mutex::new(Vec::new()); + extern "C" fn fake_free(p: *mut c_void) -> i32 { + FREED.lock().unwrap().push(p as usize); + 0 + } + fn frees(p: usize) -> usize { + FREED.lock().unwrap().iter().filter(|q| **q == p).count() + } + struct Block(*mut u8, Layout); + impl Block { + fn new(total: usize) -> Self { + let layout = Layout::from_size_align(total, 256).unwrap(); + // SAFETY: nonzero size and a valid layout; null is rejected below. + let p = unsafe { alloc_zeroed(layout) }; + assert!(!p.is_null()); + FREED.lock().unwrap().retain(|q| *q != p as usize); + Self(p, layout) + } + fn addr(&self) -> usize { + self.0 as usize + } + #[allow(dead_code)] + fn byte(&self, i: usize) -> u8 { + // SAFETY: tests only pass i < the block's total size. + unsafe { *self.0.add(i) } + } + } + impl Drop for Block { + fn drop(&mut self) { + // SAFETY: allocated in `new` with exactly this layout and freed once. + unsafe { dealloc(self.0, self.1) } + } + } + const BYTES: usize = 96; + fn owner(b: &Block) -> MappedOwner { + MappedOwner { + library: None, + host: Some(b.addr()), + alias: b.addr() as u64, + free: fake_free, + bytes: BYTES, + } + } + #[test] + fn mapped_audit_int8_write_read_into_stay_inside_and_close_frees_once() { + let b = Block::new(BYTES + 256); + let mut o = owner(&b); + o.write(BYTES - 4, &[1, 2, 3, 4]).unwrap(); + let mut out = [0u8; 4]; + o.read_into(BYTES - 4, &mut out).unwrap(); + assert_eq!(out, [1, 2, 3, 4]); + assert_eq!(o.write(BYTES - 3, &[1, 2, 3, 4]), Err(Error::InvalidSize)); + assert_eq!(o.read_into(BYTES - 3, &mut out), Err(Error::InvalidSize)); + assert_eq!(o.read_into(usize::MAX, &mut out), Err(Error::InvalidSize)); + assert_eq!(o.read_into(0, &mut []), Err(Error::InvalidSize)); + assert_eq!(b.byte(BYTES), 0); + assert_eq!(o.address(0, BYTES), Ok(b.addr() as u64)); + assert_eq!(o.address(1, BYTES), Err(Error::InvalidSize)); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.close(), Ok(())); + assert_eq!(frees(b.addr()), 1); + assert_eq!(o.read_into(0, &mut out), Err(Error::ContextPoisoned)); + } + #[test] + fn mapped_audit_int8_drop_without_close_never_frees() { + let b = Block::new(BYTES); + drop(owner(&b)); + assert_eq!(frees(b.addr()), 0); + } + } } #[cfg(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/mtp_original_physical_layout.rs b/crates/cuda-driver/src/mtp_original_physical_layout.rs index 42a14184..6d9bbaed 100644 --- a/crates/cuda-driver/src/mtp_original_physical_layout.rs +++ b/crates/cuda-driver/src/mtp_original_physical_layout.rs @@ -273,3 +273,58 @@ impl Records { .ok_or(Error::InvalidSize) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// `Records` is the ONLY bound the scalar view's raw `write` consults: a view holds no allocation of its own. + #[test] + fn records_borrow_rejects_null_and_unaligned_addresses() { + assert!(Records::borrowed(0, 4096, 64).is_err()); + assert!(Records::borrowed(4096, 0, 64).is_err()); + assert!(Records::borrowed(4096 + 8, 4096, 64).is_err()); + assert!(Records::borrowed(4096, 4096 + 8, 64).is_err()); + assert!(Records::borrowed(4096, 8192, 64).is_ok()); + } + + #[test] + fn records_range_is_exact_and_overflow_safe() { + let r = Records::borrowed(4096, 8192, 1024).unwrap(); + assert_eq!(r.range(0, 1024), Ok(4096)); + assert_eq!(r.range(1023, 1), Ok(4096 + 1023)); + assert_eq!(r.range(0, 0), Err(Error::InvalidSize)); + assert_eq!(r.range(0, 1025), Err(Error::InvalidSize)); + assert_eq!(r.range(1024, 1), Err(Error::InvalidSize)); + assert_eq!(r.range(usize::MAX, 2), Err(Error::InvalidSize)); + assert_eq!(r.range(2, usize::MAX), Err(Error::InvalidSize)); + assert_eq!(r.address(512, 8), Ok(8192 + 512)); + assert_eq!(r.address(512, 513), Err(Error::InvalidSize)); + } + + #[test] + fn records_address_arithmetic_never_wraps() { + let host_top = usize::MAX & !(ALIGN - 1); + let alias_top = !(ALIGN as u64 - 1); + let r = Records::borrowed(host_top, alias_top, 1024).unwrap(); + assert_eq!(r.range(0, 8), Ok(host_top)); + assert_eq!(r.range(512, 8), Err(Error::InvalidSize)); + assert_eq!(r.address(0, 8), Ok(alias_top)); + assert_eq!(r.address(512, 8), Err(Error::InvalidSize)); + } + + #[test] + fn planned_bytes_matches_the_mapped_owner_formula() { + for t in 1..=MAX_T { + for coupled in [false, true] { + let records = t * 236 + 384 + if coupled { 64 + 4096 * 4 } else { 0 }; + assert_eq!( + Records::planned_bytes(t, coupled), + Ok(((records + 255) & !255) + t * 40960) + ); + } + } + assert!(Records::planned_bytes(0, false).is_err()); + assert!(Records::planned_bytes(MAX_T + 1, true).is_err()); + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill_ffi.rs b/crates/cuda-driver/src/mtp_original_prefill_ffi.rs index 8b7bea61..d6de4608 100644 --- a/crates/cuda-driver/src/mtp_original_prefill_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_prefill_ffi.rs @@ -58,6 +58,7 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -76,10 +77,13 @@ mod enabled { } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -97,6 +101,7 @@ mod enabled { if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { return Err(Error::UnsupportedQwenOperation); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -108,12 +113,18 @@ mod enabled { let dev = sym!(l, c"cuCtxGetDevice", Device); let attr = sym!(l, c"cuDeviceGetAttribute", Attr); let mut device = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuCtxGetDevice", unsafe { dev(&mut device) })?; let mut major = 0; let mut shared = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; @@ -135,6 +146,8 @@ mod enabled { .map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; @@ -144,6 +157,8 @@ mod enabled { owner.module = Some(m as usize); for n in entries { let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); @@ -160,9 +175,15 @@ mod enabled { pub(crate) fn info(&self)->Result<(usize,u32)>{ let l=self.library.as_ref().ok_or(Error::ContextPoisoned)?; let device=sym!(l,c"cuCtxGetDevice",Device);let attr=sym!(l,c"cuDeviceGetAttribute",Attr); + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). let mut d=0;check("cuCtxGetDevice",unsafe{device(&mut d)})?; let mut sms=0;let mut shared=0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute(SM)",unsafe{attr(&mut sms,16,d)})?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute(shared optin)",unsafe{attr(&mut shared,97,d)})?; if sms<=0||sms>4096||shared<=0{return Err(Error::InvalidDriverValue("MTP MMQ device geometry"));} Ok((sms as usize,shared as u32)) @@ -199,7 +220,14 @@ mod enabled { Arg::Words8(x) => x.as_mut_ptr().cast(), }); } + // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); + // attribute id and value are plain integers. if shared != 0 {check("cuFuncSetAttribute",unsafe{(self.attr)(f as *mut c_void,8,shared as i32)})?;} + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. check("cuLaunchKernel", unsafe { (self.launch)( f as *mut c_void, @@ -219,6 +247,9 @@ mod enabled { // Addresses are derived only by this producer from actual whole owners. pub(crate) fn copy(&self,dst:u64,src:u64,n:usize,stream:usize)->Result<()> { if n==0 || stream==0 || dst==0 || src==0 { return Err(Error::InvalidSize); } + // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents + // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners + // must outlive the stream drain (graph resources / Context::synchronize on every close path). check("cuMemcpyAsync",unsafe{(self.copy)(dst,src,n,stream as *mut c_void)}) } pub(crate) fn close(mut self) -> Result<()> { @@ -226,6 +257,8 @@ mod enabled { } fn close_inner(&mut self) -> Result<()> { if let Some(m) = self.module.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); if r.is_err() && let Some(l) = self.library.take() diff --git a/crates/cuda-driver/src/mtp_original_scalar_ffi.rs b/crates/cuda-driver/src/mtp_original_scalar_ffi.rs index cc823fe9..fc62d399 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_ffi.rs @@ -63,6 +63,7 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -81,10 +82,13 @@ mod enabled { } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -103,6 +107,7 @@ mod enabled { if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { return Err(Error::UnsupportedQwenOperation); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -114,12 +119,18 @@ mod enabled { let dev = sym!(l, c"cuCtxGetDevice", Device); let attr = sym!(l, c"cuDeviceGetAttribute", Attr); let mut device = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuCtxGetDevice", unsafe { dev(&mut device) })?; let mut major = 0; let mut shared = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; @@ -142,6 +153,8 @@ mod enabled { .map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; @@ -151,6 +164,8 @@ mod enabled { owner.module = Some(m as usize); for n in entries { let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); @@ -169,9 +184,13 @@ mod enabled { pub(crate) fn configure_gr(&self)->Result<(usize,usize)> { let l=self.library.as_ref().ok_or(Error::ContextPoisoned)?; let device=sym!(l,c"cuCtxGetDevice",Device);let attr=sym!(l,c"cuDeviceGetAttribute",Attr); + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). let mut d=0;check("cuCtxGetDevice",unsafe{device(&mut d)})?; let mut optin=0;let mut major=0;let mut minor=0;let mut per_block=0; for (value,key) in [(&mut optin,97),(&mut major,75),(&mut minor,76),(&mut per_block,8)]{ + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). check("cuDeviceGetAttribute(GR)",unsafe{attr(value,key,d)})?; } let tile=if major*10+minor==75{1280}else{2560}; @@ -181,6 +200,8 @@ mod enabled { for (index,want) in [(if tile==1280{4}else{5},8*tile*4),(2,2*8*1280*4)]{ let want=if optin>0{want.min(optin as usize)}else{want}; let function=*self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; + // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); + // attribute id and value are plain integers. check("cuFuncSetAttribute",unsafe{(self.attr)(function as *mut c_void,8,want as i32)})?; } Ok((usable as usize,tile)) @@ -216,6 +237,11 @@ mod enabled { Arg::GrMulti(x) => x.as_mut_ptr().cast(), }); } + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. check("cuLaunchKernel", unsafe { (self.launch)( f as *mut c_void, @@ -235,10 +261,16 @@ mod enabled { // Addresses are derived only by this producer from actual whole owners. pub(crate) fn copy(&self,dst:u64,src:u64,n:usize,stream:usize)->Result<()> { if n==0 || stream==0 || dst==0 || src==0 { return Err(Error::InvalidSize); } + // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents + // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners + // must outlive the stream drain (graph resources / Context::synchronize on every close path). check("cuMemcpyAsync",unsafe{(self.copy)(dst,src,n,stream as *mut c_void)}) } pub(crate) fn copy_host(&self,dst:u64,source:&[u8],stream:usize)->Result<()> { if dst==0||source.is_empty()||stream==0{return Err(Error::InvalidSize);} + // SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable source is staged by the + // driver before return; callers additionally retain the bytes (OriginalMtpScalarPrefill::pending_host) until the stream is + // drained, so even a pinned-source (fully asynchronous) copy would read valid memory. check("cuMemcpyHtoDAsync_v2",unsafe{(self.h2d)(dst,source.as_ptr().cast(),source.len(),stream as *mut c_void)}) } pub(crate) fn close(mut self) -> Result<()> { @@ -246,6 +278,8 @@ mod enabled { } fn close_inner(&mut self) -> Result<()> { if let Some(m) = self.module.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); if r.is_err() && let Some(l) = self.library.take() diff --git a/crates/cuda-driver/src/mtp_original_scalar_mapped.rs b/crates/cuda-driver/src/mtp_original_scalar_mapped.rs index 987cad19..97c23a05 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_mapped.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_mapped.rs @@ -15,6 +15,7 @@ mod mapped_enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -33,10 +34,13 @@ mod mapped_enabled { } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -54,6 +58,7 @@ mod mapped_enabled { return Err(Error::InvalidQwenShape); } let bytes = max_t * 29 * 4; + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -64,6 +69,8 @@ mod mapped_enabled { let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is + // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); @@ -76,6 +83,7 @@ mod mapped_enabled { bytes, shared: None, }; + // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); @@ -88,6 +96,8 @@ mod mapped_enabled { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } + // SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes + // the block fully initialized before the first CPU read. unsafe { std::ptr::write_bytes(ptr.cast::(), 0, bytes); } // initialized final whole owner; never resized. @@ -125,6 +135,9 @@ mod mapped_enabled { } pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: range() delegates to the shared Records, which proved [p, p+len) lies inside the full owner's allocation; + // that block cannot be freed while this view's Rc is alive (full MappedOwner::close refuses at strong_count > 1) + // and `b` is a distinct Rust slice. Caller obligation: no enqueued GPU work reads or writes this range. unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); } @@ -132,6 +145,8 @@ mod mapped_enabled { } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { + // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every + // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. check("cuMemFreeHost", unsafe { (self.free.ok_or(Error::ContextPoisoned)?)(p as *mut c_void) })?; @@ -151,6 +166,86 @@ mod mapped_enabled { } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ } } + // Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting + // function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. + #[cfg(test)] + mod tests { + use super::*; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + use std::sync::Mutex; + static FREED: Mutex> = Mutex::new(Vec::new()); + extern "C" fn fake_free(p: *mut c_void) -> i32 { + FREED.lock().unwrap().push(p as usize); + 0 + } + fn frees(p: usize) -> usize { + FREED.lock().unwrap().iter().filter(|q| **q == p).count() + } + struct Block(*mut u8, Layout); + impl Block { + fn new(total: usize) -> Self { + let layout = Layout::from_size_align(total, 256).unwrap(); + // SAFETY: nonzero size and a valid layout; null is rejected below. + let p = unsafe { alloc_zeroed(layout) }; + assert!(!p.is_null()); + FREED.lock().unwrap().retain(|q| *q != p as usize); + Self(p, layout) + } + fn addr(&self) -> usize { + self.0 as usize + } + #[allow(dead_code)] + fn byte(&self, i: usize) -> u8 { + // SAFETY: tests only pass i < the block's total size. + unsafe { *self.0.add(i) } + } + } + impl Drop for Block { + fn drop(&mut self) { + // SAFETY: allocated in `new` with exactly this layout and freed once. + unsafe { dealloc(self.0, self.1) } + } + } + const BYTES: usize = 1024; + fn owner(b: &Block) -> MappedOwner { + MappedOwner { + library: None, + host: Some(b.addr()), + alias: b.addr() as u64, + free: Some(fake_free), + bytes: BYTES, + shared: None, + } + } + #[test] + fn mapped_audit_scalar_owner_bounds_and_free_once() { + let b = Block::new(BYTES + 256); + let mut o = owner(&b); + o.write(BYTES - 4, &[1, 2, 3, 4]).unwrap(); + assert_eq!(b.byte(BYTES - 1), 4); + assert_eq!(o.write(BYTES - 3, &[1, 2, 3, 4]), Err(Error::InvalidSize)); + assert_eq!(o.write(usize::MAX - 1, &[1, 2, 3, 4]), Err(Error::InvalidSize)); + assert_eq!(b.byte(BYTES), 0); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.close(), Ok(())); + assert_eq!(frees(b.addr()), 1); + } + #[test] + fn mapped_audit_scalar_view_writes_through_the_shared_records_and_never_frees() { + let b = Block::new(BYTES + 256); + let records = Rc::new(RefCell::new(Records::borrowed(b.addr(), b.addr() as u64, BYTES).unwrap())); + let mut view = MappedOwner::original(2, Rc::clone(&records)); + view.write(8, &[1, 2, 3, 4]).unwrap(); + assert_eq!(b.byte(9), 2); + assert_eq!(view.address(16, 4), Ok(b.addr() as u64 + 16)); + assert_eq!(view.write(BYTES, &[9]), Err(Error::InvalidSize), "bounded by the shared whole-owner Records"); + assert_eq!(b.byte(BYTES), 0); + assert_eq!(Rc::strong_count(&records), 2); + assert_eq!(view.close(), Ok(())); + assert_eq!(Rc::strong_count(&records), 1, "closing the view releases its claim on the owner"); + assert_eq!(frees(b.addr()), 0, "a view never frees the owner's block"); + } + } } #[cfg(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/native_head_ffi.rs b/crates/cuda-driver/src/native_head_ffi.rs index 04f94a4f..2da22768 100644 --- a/crates/cuda-driver/src/native_head_ffi.rs +++ b/crates/cuda-driver/src/native_head_ffi.rs @@ -74,6 +74,7 @@ struct Library(Handle); impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -102,6 +103,7 @@ impl Module { if ptx.last() != Some(&0) || entries.is_empty() { return Err(Error::InvalidDriverValue("NativeHead sealed PTX")); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -109,6 +111,7 @@ impl Module { return Err(Error::LibraryUnavailable); } fn sym(l: &Library, n: &'static CStr) -> Result { + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("NativeHead ABI"))) @@ -118,6 +121,8 @@ impl Module { } macro_rules! symbol { ($n:literal,$t:ty) => { + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::(sym(&library, $n)?) } }; } @@ -136,6 +141,8 @@ impl Module { .map_err(|_| Error::HostAllocation)?; let operation = (|| { let mut h = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. check("cuModuleLoadData", unsafe { load(&mut h, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; @@ -146,6 +153,8 @@ impl Module { for &name in entries { let c = std::ffi::CString::new(name).map_err(|_| Error::InvalidSize)?; let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. check("cuModuleGetFunction", unsafe { function(&mut f, h, c.as_ptr()) })?; @@ -183,6 +192,11 @@ impl Module { for arg in c.args.iter_mut() { c.pointers.push(arg.pointer()); } + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. check("cuLaunchKernel", unsafe { (self.launch)( f as Handle, @@ -204,6 +218,8 @@ impl Module { } fn close_inner(&mut self) -> Result<()> { if let Some(h) = self.handle.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. let result = check("cuModuleUnload", unsafe { (self.unload)(h as Handle) }); if result.is_err() { if let Some(l) = self.library.take() { diff --git a/crates/cuda-driver/src/native_head_mapped.rs b/crates/cuda-driver/src/native_head_mapped.rs index 3ed0ab21..bcadf1bc 100644 --- a/crates/cuda-driver/src/native_head_mapped.rs +++ b/crates/cuda-driver/src/native_head_mapped.rs @@ -16,6 +16,7 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -34,10 +35,13 @@ mod enabled { } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -53,6 +57,7 @@ mod enabled { if bytes == 0 { return Err(Error::InvalidSize); } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -63,6 +68,8 @@ mod enabled { let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is + // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); @@ -74,6 +81,7 @@ mod enabled { bytes, free, }; + // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); @@ -105,6 +113,9 @@ mod enabled { } pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and + // `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference + // ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range. unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); } @@ -116,12 +127,17 @@ mod enabled { out.try_reserve_exact(n) .map_err(|_| Error::HostAllocation)?; for i in 0..n { + // SAFETY: range(0, n*4) proved [p, p+4n) is inside the live allocation; p is 256-aligned (checked at alloc) so every + // i32 is aligned. The block is not CPU-zeroed: the sampler/embed kernels write all n words before this read (callers + // reach it only after a stream drain) and every value is range-checked against the vocabulary by the caller. out.push(unsafe { std::ptr::read_volatile((p as *const i32).add(i)) }); } Ok(out.into_boxed_slice()) } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { + // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every + // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; self.host = None; self.alias = 0; @@ -138,6 +154,80 @@ mod enabled { } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ } } + // Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting + // function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. + #[cfg(test)] + mod tests { + use super::*; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + use std::sync::Mutex; + static FREED: Mutex> = Mutex::new(Vec::new()); + extern "C" fn fake_free(p: *mut c_void) -> i32 { + FREED.lock().unwrap().push(p as usize); + 0 + } + fn frees(p: usize) -> usize { + FREED.lock().unwrap().iter().filter(|q| **q == p).count() + } + struct Block(*mut u8, Layout); + impl Block { + fn new(total: usize) -> Self { + let layout = Layout::from_size_align(total, 256).unwrap(); + // SAFETY: nonzero size and a valid layout; null is rejected below. + let p = unsafe { alloc_zeroed(layout) }; + assert!(!p.is_null()); + FREED.lock().unwrap().retain(|q| *q != p as usize); + Self(p, layout) + } + fn addr(&self) -> usize { + self.0 as usize + } + #[allow(dead_code)] + fn byte(&self, i: usize) -> u8 { + // SAFETY: tests only pass i < the block's total size. + unsafe { *self.0.add(i) } + } + } + impl Drop for Block { + fn drop(&mut self) { + // SAFETY: allocated in `new` with exactly this layout and freed once. + unsafe { dealloc(self.0, self.1) } + } + } + const BYTES: usize = 64; + fn owner(b: &Block) -> MappedAllocation { + MappedAllocation { + library: None, + host: Some(b.addr()), + alias: b.addr() as u64, + free: fake_free, + bytes: BYTES, + } + } + #[test] + fn mapped_audit_native_head_read_i32_is_bounded_and_aligned() { + let b = Block::new(BYTES + 256); + let mut o = owner(&b); + let words: Vec = (0..BYTES as i32 / 4).flat_map(|v| (v * 3).to_le_bytes()).collect(); + o.write(0, &words).unwrap(); + assert_eq!(&*o.read_i32(3).unwrap(), &[0, 3, 6]); + assert_eq!(o.read_i32(BYTES / 4).unwrap().len(), BYTES / 4); + assert_eq!(o.read_i32(BYTES / 4 + 1), Err(Error::InvalidSize)); + assert_eq!(o.read_i32(0), Err(Error::InvalidSize)); + assert_eq!(o.read_i32(usize::MAX / 2), Err(Error::InvalidSize), "n * 4 overflow is rejected"); + assert_eq!(b.addr() % 256, 0); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.close(), Ok(())); + assert_eq!(frees(b.addr()), 1); + assert_eq!(o.read_i32(1), Err(Error::ContextPoisoned)); + } + #[test] + fn mapped_audit_native_head_drop_without_close_never_frees() { + let b = Block::new(BYTES); + drop(owner(&b)); + assert_eq!(frees(b.addr()), 0); + } + } } #[cfg(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/original_expert_stager_ffi.rs b/crates/cuda-driver/src/original_expert_stager_ffi.rs index 2912d45f..d7754c4c 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi.rs @@ -40,6 +40,7 @@ pub(crate) struct Api { } impl Drop for Api { fn drop(&mut self) { + // SAFETY: `library` is the single dlopen reference taken by `load`; workers hold `Arc` clones, so this runs after the last user of any function pointer. unsafe { libc::dlclose(self.library as Handle); } @@ -47,11 +48,13 @@ impl Drop for Api { } impl Api { pub(crate) fn record(&self, event: usize, stream: usize) -> Result<()> { + // SAFETY: C ABI call with plain handle values; the event/stream are live handles owned by the caller (never dereferenced here). check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) }) } pub(crate) fn wait(&self, stream: usize, event: usize) -> Result<()> { + // SAFETY: C ABI call with plain handle values; the event/stream are live handles owned by the caller (never dereferenced here). check("cuStreamWaitEvent", unsafe { (self.stream_wait)(stream as Handle, event as Handle, 0) }) @@ -67,6 +70,8 @@ impl Api { if bytes == 0 || bytes > source.bytes || source.address == 0 { return Err(Error::InvalidSize); } + // SAFETY: destination extent validated, `0 < bytes <= source.bytes`, `source.address != 0`: a slot buffer the stager keeps + // (pinned: cuMemFreeHost'd, pageable: Vec dropped) only after the slot's recorded event was synchronized (`close_inner`). check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy)( destination.0, @@ -79,6 +84,7 @@ impl Api { pub(crate) fn load() -> Result { let l = + // SAFETY: fixed NUL-terminated library name and flags. unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if l.is_null() { return Err(Error::LibraryUnavailable); @@ -86,6 +92,7 @@ impl Api { struct Opening(Handle); impl Drop for Opening { fn drop(&mut self) { + // SAFETY: `self.0` is the live handle `dlopen` returned above; closed once, only on the early-return paths of `load`. unsafe { libc::dlclose(self.0); } @@ -93,6 +100,7 @@ impl Api { } let opening = Opening(l); fn symbol(l: Handle, n: &'static CStr) -> Result { + // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l, n.as_ptr()) }; if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("Stager symbol"))) @@ -102,6 +110,7 @@ impl Api { } macro_rules! sym { ($n:literal,$t:ty) => { + // SAFETY: non-null address of the named CUDA Driver symbol; every `$t` is that symbol's exact Linux64 C signature. unsafe { std::mem::transmute::(symbol(l, $n)?) } }; } @@ -127,6 +136,7 @@ impl Api { return Err(Error::InvalidSize); } let mut p = std::ptr::null_mut(); + // SAFETY: valid out pointer and non-zero size; flags 0. A zero code with a null pointer is rejected right after. let code = unsafe { (self.host_alloc)(&mut p, bytes, 0) }; if code == 0 { if p.is_null() { @@ -158,6 +168,8 @@ impl Api { return Ok(()); } if buffer.pinned { + // SAFETY: `address` is the base `cuMemHostAlloc` returned for this (`pinned`) buffer and is freed once (zeroed after). + // Callers free only after every DMA from it completed (events synchronized) and the Context is entered. check("cuMemFreeHost", unsafe { (self.host_free)(buffer.address as Handle) })?; @@ -168,6 +180,7 @@ impl Api { } pub(crate) fn event_create(&self) -> Result { let mut p = std::ptr::null_mut(); + // SAFETY: valid out pointer; flags DISABLE_TIMING. check("cuEventCreate", unsafe { (self.event_create)(&mut p, 2) })?; if p.is_null() { Err(Error::InvalidDriverValue("cuEventCreate")) @@ -176,17 +189,20 @@ impl Api { } } pub(crate) fn event_destroy(&self, event: usize) -> Result<()> { + // SAFETY: event created by `event_create`, destroyed once by the owner after it was synchronized. check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event as Handle) }) } pub(crate) fn event_sync(&self, event: usize) -> Result<()> { + // SAFETY: live event handle owned by the caller. check("cuEventSynchronize", unsafe { (self.event_sync)(event as Handle) }) } /// `cuEventQuery`: `Ok(true)` once complete, `Ok(false)` while pending (CUDA_ERROR_NOT_READY = 600). pub(crate) fn event_query(&self, event: usize) -> Result { + // SAFETY: live event handle owned by the caller. match unsafe { (self.event_query)(event as Handle) } { 0 => Ok(true), 600 => Ok(false), @@ -206,6 +222,8 @@ impl Api { if bytes == 0 || source == 0 { return Err(Error::InvalidSize); } + // SAFETY: destination extent validated, `source` is a page-locked bank range the caller keeps registered and alive + // (bank `Rc` retained) until the stream that carries this copy is drained. check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy)(destination.0, source as *const c_void, bytes, stream as Handle) }) @@ -214,12 +232,14 @@ impl Api { handle.0 } pub(crate) fn worker_enter(&self, context: usize) -> Result<()> { + // SAFETY: `context` is the live CUcontext token of the actor's Context; popped again by `worker_leave` on the same thread. check("cuCtxPushCurrent_v2", unsafe { (self.push)(context as Handle) }) } pub(crate) fn worker_leave(&self, context: usize) -> Result<()> { let mut p = std::ptr::null_mut(); + // SAFETY: valid out pointer. check("cuCtxPopCurrent_v2", unsafe { (self.pop)(&mut p) })?; if p as usize == context { Ok(()) @@ -239,6 +259,7 @@ impl Api { if bytes == 0 || bytes > source.bytes || source.address == 0 { return Err(Error::InvalidSize); } + // SAFETY: as `copy_slot`: validated destination extent; `source` is a slot buffer owned by the stager until its event (recorded below) completed. check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy)( destination.0, @@ -247,6 +268,7 @@ impl Api { stream as Handle, ) })?; + // SAFETY: C ABI call with plain handle values; the event/stream are live handles owned by the caller (never dereferenced here). check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) }) @@ -287,6 +309,9 @@ pub(crate) struct CopyJob { bytes: usize, } impl CopyJob { + // Audit: the slices' lifetimes are erased into raw addresses here, and `copy_to` (a safe fn) dereferences + // them later on a worker thread. Crate-private; sound only because every caller (`Source::job`/`raw_at`) + // borrows them from owners the stager retains until its workers are joined. pub(crate) fn from_slices(parts: [&[u8]; 3], slot_capacity: usize) -> Result { let mut bytes = 0usize; let mut source = [(0, 0); 3]; @@ -321,6 +346,10 @@ impl CopyJob { // slices; actor holds them until active==0. The claimed ring slot cannot // be overwritten until its recorded DMA event completes, and every active // claim is generation-fenced. Buffers outlive all joined workers. + // Audit: after `Shared::stop` (abort/drain) the `issued` wait is released, so a late + // worker may write a slot whose earlier job is still being copied by another worker or + // whose DMA was never issued; that batch is being abandoned (never read), and the slot + // buffers are freed only after every worker joined, so this stays confined to dead bytes. unsafe { std::ptr::copy_nonoverlapping(source as *const u8, destination as *mut u8, bytes); } @@ -346,6 +375,8 @@ impl ExpertFileMap { } // SAFETY: actual admitted regular-file FD/extent, retained by Source through // all workers and DMA. Published stable-source contract forbids in-place writes. + // Audit RISK: a file truncated after the `validate_current` checks faults (SIGBUS) on the + // missing pages; this is the same contract as `VerifiedGgufFile`, not detectable here. let ptr = unsafe { libc::mmap( std::ptr::null_mut(), @@ -360,6 +391,7 @@ impl ExpertFileMap { return Err(Error::HostAllocation); } if ptr.is_null() { + // SAFETY: `ptr` is the mapping (at address 0) that `mmap` just returned, `bytes` the length mapped; nothing references it yet. unsafe { libc::munmap(ptr, bytes); } @@ -383,6 +415,8 @@ impl ExpertFileMap { } impl Drop for ExpertFileMap { fn drop(&mut self) { + // SAFETY: exact base/length `mmap` returned. Every `&[u8]` from `part` borrows `&self`; the raw addresses copied into worker `CopyJob`s + // are only dereferenced until the stager has joined its workers (`close_inner`), which happens before the `Source` holding this map drops. unsafe { libc::munmap(self.address as *mut c_void, self.bytes); } @@ -405,3 +439,56 @@ impl CopyJob { Ok(data.into_boxed_slice()) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A `CopyJob` keeps only raw addresses; its own checks are what bound the worker's `copy_nonoverlapping`. + #[test] + fn copy_job_is_bounded_by_the_slot_and_refuses_empty_or_overlapping_parts() { + let (a, b, c) = ([1u8; 4], [2u8; 6], [3u8; 2]); + assert!(CopyJob::from_slices([&a, &b, &c], 11).is_err(), "12 bytes into an 11-byte slot"); + assert!(CopyJob::from_slices([&a, &[], &c], 64).is_err(), "empty part"); + let job = CopyJob::from_slices([&a, &b, &c], 12).unwrap(); + assert_eq!(job.bytes(), 12); + let mut slot = vec![0u8; 12]; + let at = |bytes| WorkerSlot { address: slot.as_ptr() as usize, bytes, event: 0 }; + assert!(job.copy_to(at(11)).is_err(), "slot smaller than the job"); + assert!(slot.iter().all(|b| *b == 0), "nothing written on refusal"); + assert!(job.copy_to(WorkerSlot { address: 0, bytes: 12, event: 0 }).is_err()); + job.copy_to(WorkerSlot { address: slot.as_mut_ptr() as usize, bytes: 12, event: 0 }).unwrap(); + assert_eq!(slot, [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3]); + // a destination that overlaps a source is refused before any byte moves + let mut shared = vec![9u8; 16]; + let overlapping = CopyJob::from_slices([&shared[0..4], &shared[4..10], &shared[10..12]], 12).unwrap(); + let base = shared.as_mut_ptr() as usize; + assert!(overlapping.copy_to(WorkerSlot { address: base + 2, bytes: 12, event: 0 }).is_err()); + assert!(shared.iter().all(|b| *b == 9)); + } + + /// `part` is the only way a worker source slice is made from the mapping. + #[test] + fn expert_file_map_part_is_bounded_by_the_mapping() { + // SAFETY: anonymous private mapping; unmapped by the map's own Drop. + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + 8192, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + assert_ne!(ptr, libc::MAP_FAILED); + let map = ExpertFileMap { address: ptr as usize, bytes: 8192 }; + assert_eq!(map.part(0, 8192).unwrap().len(), 8192); + assert_eq!(map.part(8191, 1).unwrap().len(), 1); + assert!(map.part(0, 8193).is_err()); + assert!(map.part(8192, 1).is_err()); + assert!(map.part(8191, 2).is_err()); + assert!(map.part(u64::MAX, 1).is_err()); + assert!(map.part(1, usize::MAX).is_err()); + } +} diff --git a/crates/cuda-driver/src/original_file_expert_source_ffi.rs b/crates/cuda-driver/src/original_file_expert_source_ffi.rs index 481adecd..43b3e3a0 100644 --- a/crates/cuda-driver/src/original_file_expert_source_ffi.rs +++ b/crates/cuda-driver/src/original_file_expert_source_ffi.rs @@ -32,6 +32,7 @@ pub(crate) struct Api { } impl Drop for Api { fn drop(&mut self) { + // SAFETY: `library` is the single dlopen reference taken by `load`; the table is shared as `Arc`, so this runs after its last user. unsafe { libc::dlclose(self.library as P); } @@ -40,6 +41,7 @@ impl Drop for Api { impl Api { pub(crate) fn load() -> Result> { let l = + // SAFETY: fixed NUL-terminated library name and flags. unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if l.is_null() { return Err(Error::LibraryUnavailable); @@ -47,6 +49,7 @@ impl Api { struct Opening(P); impl Drop for Opening { fn drop(&mut self) { + // SAFETY: `self.0` is the live handle `dlopen` returned; closed once, only on the early-return paths of `load`. unsafe { libc::dlclose(self.0); } @@ -54,6 +57,7 @@ impl Api { } let opening = Opening(l); fn symbol(l: P, n: &'static CStr) -> Result

{ + // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l, n.as_ptr()) }; if p.is_null() { Err(Error::MissingSymbol( @@ -65,6 +69,7 @@ impl Api { } macro_rules! sym { ($n:literal,$t:ty) => { + // SAFETY: non-null address of the named CUDA Driver symbol; every `$t` is that symbol's exact Linux64 C signature. unsafe { std::mem::transmute::(symbol(l, $n)?) } }; } @@ -94,8 +99,10 @@ impl Api { } if pin { let mut p = std::ptr::null_mut(); + // SAFETY: valid out pointer and non-zero size; flags PORTABLE|DEVICEMAP. A zero code with a null pointer is treated as failure. if unsafe { (self.alloc)(&mut p, bytes, 3) } == 0 && !p.is_null() { let mut alias = 0; + // SAFETY: `p` is the live allocation just returned; valid out pointer for the device alias. if unsafe { (self.alias)(&mut alias, p, 0) } == 0 && alias != 0 { return Ok(Arena { address: p as usize, @@ -107,9 +114,11 @@ impl Api { lock_off: 0, }); } + // SAFETY: `p` is the base `cuMemHostAlloc` just returned and nothing else saw it; freed once. check("cuMemFreeHost", unsafe { (self.free)(p) })?; } } + // SAFETY: plain `malloc` of a non-zero size; null is checked. The block is uninitialised: `Arena::part` is only reachable after every byte was written (see its comment). let p = unsafe { libc::malloc(bytes) }; if p.is_null() { return Err(Error::HostAllocation); @@ -129,6 +138,7 @@ impl Api { return Err(Error::InvalidSize); } let mut p = std::ptr::null_mut(); + // SAFETY: valid out pointer and non-zero size; flags 0 (plain page-locked, no device mapping). if unsafe { (self.alloc)(&mut p, bytes, 0) } == 0 && !p.is_null() { return Ok(Arena { address: p as usize, @@ -140,6 +150,7 @@ impl Api { lock_off: 0, }); } + // SAFETY: plain `malloc` of a non-zero size; null is checked. Only read (`part`) after a full device write. let p = unsafe { libc::malloc(bytes) }; if p.is_null() { return Err(Error::HostAllocation); @@ -169,6 +180,9 @@ impl Api { { return Err(Error::InvalidSize); } + // SAFETY: `offset + bytes <= arena.bytes` (checked above), so the destination is inside the live arena; `source` extent validated. + // A pinned (`full_pin`) arena is written asynchronously: `stage_swaps` synchronizes the stream before any `part` read and before `close`; + // a `malloc` arena is pageable, so the driver completes the copy before returning. check("cuMemcpyDtoHAsync_v2", unsafe { (self.dtoh)( (arena.address + offset) as P, @@ -182,14 +196,17 @@ impl Api { if arena.full_pin || arena.partial != 0 || bytes == 0 || bytes > arena.bytes { return Err(Error::InvalidSize); } + // SAFETY: `arena.address..+bytes` (`bytes <= arena.bytes`) is the live `malloc` block, not resized or freed until `close` unregisters it first. if unsafe { (self.register)(arena.address as P, bytes, 3) } != 0 { return Ok(false); } arena.partial = bytes; let mut alias = 0; + // SAFETY: the base was just registered with DEVICEMAP; valid out pointer. if unsafe { (self.alias)(&mut alias, arena.address as P, 0) } == 0 && alias != 0 { arena.alias = alias; } else { + // SAFETY: identical base that was just registered. check("cuMemHostUnregister", unsafe { (self.unregister)(arena.address as P) })?; @@ -203,19 +220,23 @@ impl Api { return Ok(()); } if arena.full_pin { + // SAFETY: base returned by `cuMemHostAlloc` for this `full_pin` arena; `close` frees it once (address zeroed) after `context.synchronize()`. check("cuMemFreeHost", unsafe { (self.free)(arena.address as P) })?; } else { if arena.partial > 0 { + // SAFETY: identical base that `register_prefix` registered (`partial > 0`); unregistered once, before the block is freed. check("cuMemHostUnregister", unsafe { (self.unregister)(arena.address as P) })?; arena.partial = 0; } if arena.locked > 0 { + // SAFETY: the exact range `lock_remainder` mlock'd, still inside the live `malloc` block. unsafe { libc::munlock((arena.address + arena.lock_offset()) as P, arena.locked); } } + // SAFETY: `malloc`ed base, unregistered above; freed once (address zeroed). unsafe { libc::free(arena.address as P); } @@ -256,6 +277,7 @@ impl Arena { pub(crate) fn lock_remainder(&mut self) { self.lock_off = self.partial; let n = self.bytes - self.partial; + // SAFETY: `partial..bytes` lies inside the live `malloc` block; mlock only pins pages, failure is tolerated. if n > 0 && unsafe { libc::mlock((self.address + self.partial) as P, n) } == 0 { self.locked = n; } @@ -284,6 +306,9 @@ impl Arena { return Err(Error::InvalidSize); } // SAFETY: caller only exposes this after all initialization workers joined. + // Audit: the block comes from `malloc`/`cuMemHostAlloc` uninitialised. `build_cache_complement` assigns + // contiguous offsets covering `[0, bytes)` and writes every one before `ready`; the exchange arena is read + // only for experts `stage_swaps` copied into (after its stream synchronize). Ok(unsafe { std::slice::from_raw_parts((self.address + offset) as *const u8, bytes) }) } pub(crate) fn overwrite(&self, offset: usize, source: &[u8]) -> Result<()> { @@ -302,6 +327,8 @@ impl Arena { } // SAFETY: source actor owns the exclusive mutable complement and all earlier // blob loans/DMA consumers have ended before actual cache-completion commit. + // (`commit_exchanges` takes `&mut self`, so no `OriginalFileSourceBlob` borrowing this arena is alive; + // `d..d+len` is inside the arena and checked disjoint from `source`.) unsafe { std::ptr::copy_nonoverlapping(source.as_ptr(), d as *mut u8, source.len()); } @@ -347,6 +374,7 @@ impl Copy { if p == 0 || n == 0 || p.checked_add(n).is_none_or(|e| p < d + n && d < e) { return Err(Error::InvalidSize); } + // SAFETY: `run` checked each source/destination pair for overlap and overflow; the destination is inside the arena/stage (checked by `write`/`into_slice`), sources are retained mapped file bytes. Callers run it before the owners are released. unsafe { std::ptr::copy_nonoverlapping(p as *const u8, d as *mut u8, n); } @@ -363,6 +391,7 @@ pub(crate) fn warm(parts: [&[u8]; 3]) { let first = (p.as_ptr() as usize) & !4095usize; let end = (p.as_ptr() as usize).saturating_add(p.len()); if end > first { + // SAFETY: `madvise(WILLNEED)` is advice only; a range outside a mapping merely fails with ENOMEM. unsafe { libc::madvise(first as P, end - first, libc::MADV_WILLNEED); } @@ -397,6 +426,7 @@ pub(crate) fn worker_stack_bytes() -> Result { rlim_cur: 0, rlim_max: 0, }; + // SAFETY: valid pointer to a local `rlimit`. if unsafe { libc::getrlimit(libc::RLIMIT_STACK, &mut limit) } != 0 || limit.rlim_cur == 0 || limit.rlim_cur == libc::RLIM_INFINITY @@ -412,9 +442,77 @@ pub(crate) fn worker_stack_bytes() -> Result { pub(crate) fn partial_pin_cap(value: Option<&str>) -> usize { let v = value.and_then(|v| std::ffi::CString::new(v).ok()); // Original atof positive-prefix semantics (including whitespace/exponent). + // SAFETY: `v` is a NUL-terminated `CString`; the end pointer is null. let n = v.as_ref().map_or(24.0, |v| unsafe { libc::strtod(v.as_ptr(), std::ptr::null_mut()) }); let n = if n > 0.0 { n } else { 24.0 }; (n * 1073741824.0) as usize } + +#[cfg(test)] +mod tests { + use super::*; + + fn arena(bytes: usize) -> Arena { + // SAFETY: zeroed allocation of a non-zero size; released by `release` below. + let p = unsafe { libc::calloc(1, bytes) }; + assert!(!p.is_null()); + Arena { address: p as usize, bytes, alias: 0, full_pin: false, partial: 0, locked: 0, lock_off: 0 } + } + fn release(arena: Arena) { + // SAFETY: the block `arena` above allocated, freed once. + unsafe { libc::free(arena.address as P) }; + } + + /// Every raw view of the arena (`write` record, `part`, `overwrite`) is bounded by the allocation. + #[test] + fn arena_write_part_and_overwrite_stay_inside_the_block() { + let a = arena(64); + let (x, y, z) = ([1u8; 8], [2u8; 8], [3u8; 8]); + assert!(a.write(41, [&x, &y, &z]).is_err(), "41 + 24 > 64"); + assert!(a.write(usize::MAX - 3, [&x, &y, &z]).is_err(), "offset overflow"); + assert!(a.write(0, [&x, &[], &z]).is_err(), "empty part"); + a.write(40, [&x, &y, &z]).unwrap().run().unwrap(); + assert_eq!(a.part(40, 24).unwrap(), [&x[..], &y, &z].concat()); + assert!(a.part(41, 24).is_err()); + assert!(a.part(usize::MAX, 2).is_err()); + assert!(a.overwrite(61, &[0u8; 4]).is_err()); + assert!(a.overwrite(0, &[]).is_err()); + a.overwrite(60, &[7u8; 4]).unwrap(); + assert_eq!(a.part(60, 4).unwrap(), [7u8; 4]); + let inside = a.part(0, 8).unwrap(); + assert!(a.overwrite(4, inside).is_err(), "source overlapping the destination"); + release(a); + } + + /// A `Copy` record is raw addresses; `run` refuses overlap, null/empty pieces and oversize before moving a byte. + #[test] + fn copy_records_refuse_overlap_empty_null_and_oversize_parts() { + let mut out = vec![0u8; 12]; + let base = out.as_ptr() as usize; + let src = [5u8; 12]; + let at = |i: usize| src[i..].as_ptr() as usize; + assert!(copy_parts_record([(at(0), 4), (at(4), 4), (at(8), 5)], &mut out).is_err(), "13 > 12"); + assert!(copy_parts_record([(at(0), 4), (0, 4), (at(8), 4)], &mut out).is_err(), "null piece"); + assert!(copy_parts_record([(at(0), 4), (at(4), 0), (at(8), 4)], &mut out).is_err(), "empty piece"); + assert!(copy_parts_record([(at(0), 4), (usize::MAX - 1, 4), (at(8), 4)], &mut out).is_err(), "address overflow"); + assert!(copy_parts_to([(base + 2, 4), (at(4), 4), (at(8), 4)], &mut out).is_err(), "source overlapping the output"); + assert!(out.iter().all(|b| *b == 0)); + copy_parts_to([(at(0), 4), (at(4), 4), (at(8), 4)], &mut out).unwrap(); + assert_eq!(out, src); + } + + #[test] + fn partial_pin_cap_parses_a_positive_prefix_and_falls_back_to_24_gib() { + const GIB: usize = 1 << 30; + assert_eq!(partial_pin_cap(None), 24 * GIB); + assert_eq!(partial_pin_cap(Some("")), 24 * GIB); + assert_eq!(partial_pin_cap(Some("-3")), 24 * GIB); + assert_eq!(partial_pin_cap(Some("nan")), 24 * GIB); + assert_eq!(partial_pin_cap(Some("0.5")), GIB / 2); + assert_eq!(partial_pin_cap(Some(" 2x")), 2 * GIB); + assert_eq!(partial_pin_cap(Some("1e999")), usize::MAX); + assert_eq!(partial_pin_cap(Some("1\0")), 24 * GIB, "an interior NUL cannot be passed to strtod"); + } +} diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs index edcbbd9e..f58bdd1d 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs @@ -13,6 +13,7 @@ mod platform { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: `self.0` is the live, non-null dlopen handle; closed once when the table (or a failed `load`) drops. unsafe { libc::dlclose(self.0); } @@ -105,6 +106,7 @@ mod platform { } impl Api { pub(crate) fn load() -> Result { + // SAFETY: fixed NUL-terminated library name and flags. let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -112,6 +114,7 @@ mod platform { return Err(Error::LibraryUnavailable); } fn symbol(l: &Library, n: &'static CStr) -> Result { + // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; if p.is_null() { Err(Error::MissingSymbol( @@ -123,6 +126,7 @@ mod platform { } macro_rules! sym { ($n:literal,$t:ty) => { + // SAFETY: non-null address of the named CUDA Driver symbol; every `$t` is that symbol's exact Linux64 C signature. unsafe { std::mem::transmute::(symbol(&l, $n)?) } }; } @@ -150,11 +154,15 @@ mod platform { copy_h2d: sym!(c"cuMemcpyHtoDAsync_v2", CopyH2d), host_fn: sym!(c"cuLaunchHostFunc", LaunchHostFn), copy_batch: { + // SAFETY: optional symbol; a null address is mapped to `None` below. let p = unsafe { libc::dlsym(l.0, c"cuMemcpyBatchAsync_v2".as_ptr()) }; + // SAFETY: non-null `cuMemcpyBatchAsync_v2` (CUDA 13 signature without `failIdx`); `CopyBatch` is that exact C signature. (!p.is_null()).then(|| unsafe { std::mem::transmute::(p) }) }, write_value: { + // SAFETY: optional symbol; a null address is mapped to `None` below. let p = unsafe { libc::dlsym(l.0, c"cuStreamWriteValue32_v2".as_ptr()) }; + // SAFETY: non-null `cuStreamWriteValue32_v2`; `WriteValue` is its exact C signature. (!p.is_null()).then(|| unsafe { std::mem::transmute::(p) }) }, batch_refused: std::sync::atomic::AtomicBool::new(false), @@ -164,6 +172,7 @@ mod platform { } pub(crate) fn stream_create(&self, nonblocking: bool) -> Result { let mut s = std::ptr::null_mut(); + // SAFETY: valid out pointer; the caller's Context is entered. check("cuStreamCreate", unsafe { (self.create)(&mut s, u32::from(nonblocking)) })?; @@ -173,12 +182,15 @@ mod platform { Ok(s as usize) } pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> { + // SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included). check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) }) } pub(crate) fn stream_sync(&self, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) }) } pub(crate) fn stream_query(&self, s: usize) -> Result { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. let q = unsafe { (self.query)(s as Handle) }; if q == 600 { Ok(false) @@ -188,18 +200,21 @@ mod platform { } pub(crate) fn stream_priority(&self, s: usize) -> Result { let mut p = 0; + // SAFETY: C ABI call on a live handle; the out pointer is a valid local. check("cuStreamGetPriority", unsafe { (self.priority)(s as Handle, &mut p) })?; Ok(p) } pub(crate) fn stream_wait(&self, s: usize, e: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuStreamWaitEvent", unsafe { (self.wait)(s as Handle, e as Handle, 0) }) } pub(crate) fn event_create(&self, timing: bool) -> Result { let mut e = std::ptr::null_mut(); + // SAFETY: valid out pointer; flags select timing / DISABLE_TIMING. check("cuEventCreate", unsafe { (self.event_create)(&mut e, if timing { 0 } else { 2 }) })?; @@ -209,16 +224,19 @@ mod platform { Ok(e as usize) } pub(crate) fn event_destroy(&self, e: usize) -> Result<()> { + // SAFETY: event created through this Api; destroyed once by `OriginalGpuEvent::close_inner` after it (and its waiter streams) were synchronized. check("cuEventDestroy_v2", unsafe { (self.event_destroy)(e as Handle) }) } pub(crate) fn event_record(&self, e: usize, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuEventRecord", unsafe { (self.event_record)(e as Handle, s as Handle) }) } pub(crate) fn event_query(&self, e: usize) -> Result { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. let q = unsafe { (self.event_query)(e as Handle) }; if q == 600 { Ok(false) @@ -227,12 +245,14 @@ mod platform { } } pub(crate) fn event_sync(&self, e: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuEventSynchronize", unsafe { (self.event_sync)(e as Handle) }) } pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result { let mut ms = 0.; + // SAFETY: valid out pointer; both events were created with timing enabled and recorded (checked by the caller). check("cuEventElapsedTime", unsafe { (self.elapsed)(&mut ms, a as Handle, b as Handle) })?; @@ -242,12 +262,14 @@ mod platform { Ok(ms) } pub(crate) fn begin(&self, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuStreamBeginCapture_v2", unsafe { (self.begin)(s as Handle, 1) }) } // ThreadLocal pub(crate) fn end(&self, s: usize) -> Result { let mut g = std::ptr::null_mut(); + // SAFETY: C ABI call on a live handle; the out pointer is a valid local. check("cuStreamEndCapture", unsafe { (self.end)(s as Handle, &mut g) })?; @@ -258,6 +280,7 @@ mod platform { } pub(crate) fn nodes(&self, g: usize) -> Result { let mut n = 0; + // SAFETY: live graph; a null node array with a valid count out pointer only queries the count. check("cuGraphGetNodes", unsafe { (self.nodes)(g as Handle, std::ptr::null_mut(), &mut n) })?; @@ -265,6 +288,7 @@ mod platform { } pub(crate) fn instantiate(&self, g: usize) -> Result { let mut e = std::ptr::null_mut(); + // SAFETY: C ABI call on a live handle; the out pointer is a valid local. check("cuGraphInstantiateWithFlags", unsafe { (self.instantiate)(&mut e, g as Handle, 0) })?; @@ -274,21 +298,25 @@ mod platform { Ok(e as usize) } pub(crate) fn graph_destroy(&self, g: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuGraphDestroy", unsafe { (self.graph_destroy)(g as Handle) }) } pub(crate) fn exec_destroy(&self, e: usize) -> Result<()> { + // SAFETY: executable created through this Api; destroyed once by `OriginalGpuGraph::close_inner` after its stream was drained. check("cuGraphExecDestroy", unsafe { (self.exec_destroy)(e as Handle) }) } pub(crate) fn upload(&self, e: usize, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. check("cuGraphUpload", unsafe { (self.upload)(e as Handle, s as Handle) }) } pub(crate) fn launch(&self, e: usize, s: usize) -> Result<()> { + // SAFETY: live executable and stream; the graph's resources (`R`: device/mapped owners) are retained by `OriginalGpuGraph` until drained. check("cuGraphLaunch", unsafe { (self.launch)(e as Handle, s as Handle) }) @@ -296,6 +324,8 @@ mod platform { /// `cudaMemcpyAsync(H2D)` of `fetch_dma`. The caller keeps `src` (a registered bank) and `dst` alive /// until the stream's fence. pub(crate) fn copy_h2d(&self, dst: u64, src: &[u8], s: usize) -> Result<()> { + // SAFETY: `dst` is a validated device range; `src` is a registered bank slice the caller keeps alive and registered + // until this stream's next fence (documented contract of `enqueue_copy_h2d`). check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle) }) @@ -311,6 +341,8 @@ mod platform { // srcAccessOrder STREAM (1): the registered bank stays valid until the stream's fence let mut attr = BatchAttributes { src_access_order: 1, src_loc: [0, 0], dst_loc: [0, 0], flags: 0 }; let mut index = 0usize; + // SAFETY: `dsts/srcs/sizes/attr/index` are locals alive across the call and consumed by the driver during it (CUDA copies the + // descriptor arrays); `count`/`numAttrs` match; the source bytes stay retained by the caller until the stream fence (srcAccessOrder STREAM). let code = unsafe { f(dsts.as_mut_ptr(), srcs.as_mut_ptr(), sizes.as_mut_ptr(), pieces.len(), &mut attr, &mut index, 1, s as Handle) }; @@ -333,6 +365,7 @@ mod platform { /// (no host callback thread). `MissingSymbol` when the driver lacks the call. pub(crate) fn write_u32_after(&self, s: usize, device_address: u64, value: u32) -> Result<()> { let f = self.write_value.ok_or(Error::MissingSymbol("cuStreamWriteValue32_v2"))?; + // SAFETY: `device_address` is the device alias of a live 4-byte mapped host word the caller keeps allocated past this stream's fence. check("cuStreamWriteValue32_v2", unsafe { f(s as Handle, device_address, value, 0) }) } /// Flag B after the copies: a stream write of the device alias when the driver takes it, else (or after one @@ -340,6 +373,7 @@ mod platform { pub(crate) fn raise_flag_after(&self, s: usize, host_word: usize, device_address: u64, value: u32) -> Result<()> { use std::sync::atomic::Ordering::Relaxed; if let (Some(f), false, true) = (self.write_value, self.write_refused.load(Relaxed), device_address != 0 && device_address % 4 == 0) { + // SAFETY: as `write_u32_after`; the alias is non-null and 4-byte aligned (checked in the condition). if unsafe { f(s as Handle, device_address, value, 0) } == 0 { return Ok(()); } @@ -354,6 +388,8 @@ mod platform { return Err(Error::InvalidSize); } let data = Box::into_raw(Box::new(Raise { word, value })); + // SAFETY: `data` is a leaked `Box` owned by the callback from here on (reclaimed there, or below if the launch is refused); + // `word` is a live 4-byte-aligned mapped host word whose owner synchronizes the Context before freeing it. let launched = check("cuLaunchHostFunc", unsafe { (self.host_fn)(s as Handle, raise_after_copies, data.cast()) }); diff --git a/crates/cuda-driver/src/original_sampler_mapped.rs b/crates/cuda-driver/src/original_sampler_mapped.rs index 14ef759d..48cbbb27 100644 --- a/crates/cuda-driver/src/original_sampler_mapped.rs +++ b/crates/cuda-driver/src/original_sampler_mapped.rs @@ -16,6 +16,7 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. unsafe { libc::dlclose(self.0); } @@ -34,10 +35,13 @@ mod enabled { } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -49,6 +53,7 @@ mod enabled { } impl MappedAllocation { pub(crate) fn new() -> Result { + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -59,6 +64,8 @@ mod enabled { let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); let free = sym!(library, c"cuMemFreeHost", Free); let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is + // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). check("cuMemHostAlloc", unsafe { alloc(&mut ptr, BYTES, 3) })?; if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); @@ -69,6 +76,7 @@ mod enabled { alias: 0, free, }; + // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); @@ -81,6 +89,8 @@ mod enabled { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } + // SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes + // the block fully initialized before the first CPU read. unsafe { std::ptr::write_bytes(ptr.cast::(), 0, BYTES); } // initialized final whole owner; never resized. @@ -104,6 +114,9 @@ mod enabled { } pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and + // `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference + // ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range. unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); } @@ -111,6 +124,8 @@ mod enabled { } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { + // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every + // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; self.host = None; self.alias = 0; @@ -127,6 +142,76 @@ mod enabled { } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ } } + // Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting + // function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. + #[cfg(test)] + mod tests { + use super::*; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + use std::sync::Mutex; + static FREED: Mutex> = Mutex::new(Vec::new()); + extern "C" fn fake_free(p: *mut c_void) -> i32 { + FREED.lock().unwrap().push(p as usize); + 0 + } + fn frees(p: usize) -> usize { + FREED.lock().unwrap().iter().filter(|q| **q == p).count() + } + struct Block(*mut u8, Layout); + impl Block { + fn new(total: usize) -> Self { + let layout = Layout::from_size_align(total, 256).unwrap(); + // SAFETY: nonzero size and a valid layout; null is rejected below. + let p = unsafe { alloc_zeroed(layout) }; + assert!(!p.is_null()); + FREED.lock().unwrap().retain(|q| *q != p as usize); + Self(p, layout) + } + fn addr(&self) -> usize { + self.0 as usize + } + #[allow(dead_code)] + fn byte(&self, i: usize) -> u8 { + // SAFETY: tests only pass i < the block's total size. + unsafe { *self.0.add(i) } + } + } + impl Drop for Block { + fn drop(&mut self) { + // SAFETY: allocated in `new` with exactly this layout and freed once. + unsafe { dealloc(self.0, self.1) } + } + } + fn owner(b: &Block) -> MappedAllocation { + MappedAllocation { + library: None, + host: Some(b.addr()), + alias: b.addr() as u64, + free: fake_free, + } + } + #[test] + fn mapped_audit_sampler_params_and_history_fit_exactly_and_close_frees_once() { + let b = Block::new(BYTES + 256); + let mut o = owner(&b); + o.write(0, &[0u8; 64]).unwrap(); + o.write(64, &vec![0xAAu8; 4096 * 4]).unwrap(); + assert_eq!(b.byte(BYTES - 1), 0xAA); + assert_eq!(o.write(64, &vec![0u8; 4096 * 4 + 1]), Err(Error::InvalidSize)); + assert_eq!(o.address(64, 4096 * 4), Ok(b.addr() as u64 + 64)); + assert_eq!(o.address(64, 4096 * 4 + 1), Err(Error::InvalidSize)); + assert_eq!(b.byte(BYTES), 0); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.close(), Ok(())); + assert_eq!(frees(b.addr()), 1); + } + #[test] + fn mapped_audit_sampler_drop_without_close_never_frees() { + let b = Block::new(BYTES); + drop(owner(&b)); + assert_eq!(frees(b.addr()), 0); + } + } } #[cfg(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs index e257b6fa..16893bba 100644 --- a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs @@ -22,6 +22,9 @@ mod enabled { impl Drop for Library { fn drop(&mut self) { if !self.0.is_null() { + // SAFETY: `self.0` is the one dlopen reference this wrapper owns; it is closed exactly once, here. + // No function pointer resolved from it is called after the owning `MappedAllocation` is gone (a + // still-allocated owner `forget`s the Library instead, see `Drop for MappedAllocation`). unsafe { libc::dlclose(self.0); } @@ -40,10 +43,12 @@ mod enabled { } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: `$l.0` is a live dlopen handle and `$s` a NUL-terminated literal. let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; if p.is_null() { return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); } + // SAFETY: `$t` is the exact Linux64 C signature of the named CUDA driver entry point. unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } @@ -56,6 +61,7 @@ mod enabled { } impl MappedAllocation { pub(crate) fn new() -> Result { + // SAFETY: fixed library name and flags; the returned handle (checked non-null next) is owned by `Library`. let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); @@ -67,6 +73,8 @@ mod enabled { let free = sym!(library, c"cuMemFreeHost", Free); let bytes = configured_bytes()?; let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out pointer; flags 3 = PORTABLE|DEVICEMAP; a context is current (the caller holds the Context). + // On success the allocation is `bytes` long, page-aligned, and owned by `MappedAllocation` until `close`. check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); @@ -78,6 +86,7 @@ mod enabled { bytes, free, }; + // SAFETY: `ptr` is the base of the live cuMemHostAlloc allocation above (DEVICEMAP), valid out pointer. let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); @@ -90,9 +99,11 @@ mod enabled { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } + // SAFETY: `ptr` is the base of the live `bytes`-long host allocation, no other reference to it exists yet and + // no GPU work has been enqueued; after this the whole allocation is initialized and never resized. unsafe { std::ptr::write_bytes(ptr.cast::(), 0, bytes); - } // initialized final whole owner; never resized. + } Ok(owner) } pub(crate) fn bytes(&self) -> usize { @@ -113,6 +124,10 @@ mod enabled { } pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { let p = self.range(o, b.len())?; + // SAFETY: `range` proved `[p, p + b.len())` lies inside the live allocation (`host` is Some, offset+len <= + // `bytes`, no wrap) and `&mut self` excludes other CPU access. `b` is a caller slice and cannot overlap the + // driver allocation. The caller drains the GPU before writing (every public caller synchronizes first: + // no kernel may read these cells while the CPU writes them). unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); } @@ -121,6 +136,8 @@ mod enabled { /// Copy `out.len()` bytes of the mapped host image starting at `o` (the prefix-cache export of K/V cells). pub(crate) fn read(&self, o: usize, out: &mut [u8]) -> Result<()> { let p = self.range(o, out.len())?; + // SAFETY: `range` proved `[p, p + out.len())` lies inside the live allocation; `out` is a caller slice that + // cannot overlap it. Reads of cells the GPU wrote are ordered by the caller's prior context synchronize. unsafe { std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr(), out.len()); } @@ -128,6 +145,9 @@ mod enabled { } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { + // SAFETY: `p` is the base returned by cuMemHostAlloc and not yet freed (`host` is cleared only after a + // successful free). The caller (`QsaPromptKv::close_inner`) frees only after a successful context + // synchronize, so no copy or kernel still references the allocation; on any doubt it `forget`s it. check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; self.host = None; self.alias = 0; diff --git a/crates/cuda-driver/src/qsa_resident_index.rs b/crates/cuda-driver/src/qsa_resident_index.rs index ffb54c87..365c06c9 100644 --- a/crates/cuda-driver/src/qsa_resident_index.rs +++ b/crates/cuda-driver/src/qsa_resident_index.rs @@ -148,7 +148,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx>{ pub fn import(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,spans:&[(usize,&[u8])],tail:&[u8],end:usize)->Result>{ self.validate()?;if self.in_flight{return Err(Error::InvalidQwenShape)} if tail.len()!=CHECKPOINT_BYTES||end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)} - for(first,bytes)in spans{if bytes.is_empty()||bytes.len()%Self::ROW_BYTES!=0||first+bytes.len()/Self::ROW_BYTES>end/4{return Err(Error::InvalidQwenShape)}} + for(first,bytes)in spans{if bytes.is_empty()||bytes.len()%Self::ROW_BYTES!=0||first.checked_add(bytes.len()/Self::ROW_BYTES).is_none_or(|e|e>end/4){return Err(Error::InvalidQwenShape)}} for(first,bytes)in spans{self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(first*Self::ROW_BYTES,bytes)?;} let mut b=self.checkpoint_buffer()?; if let Err(e)=b.copy_from(tail){if self.context.is_poisoned(){std::mem::forget(b)}else{let _=b.release();}return Err(e)} diff --git a/crates/cuda-driver/src/qsa_resident_transfer.rs b/crates/cuda-driver/src/qsa_resident_transfer.rs index 7b18271d..f31ec704 100644 --- a/crates/cuda-driver/src/qsa_resident_transfer.rs +++ b/crates/cuda-driver/src/qsa_resident_transfer.rs @@ -8,12 +8,15 @@ mod enabled { pub(crate) struct Transfer{library:*mut c_void,copy:Copy} impl Transfer{ pub(crate) fn new()->Result{ - // SAFETY: fixed libcuda ABI; no caller resolver or host pointer conversion. + // SAFETY: fixed libcuda ABI; no caller resolver or host pointer conversion. The handle is owned by `Transfer` + // (closed in Drop, or on the missing-symbol path below). let library=unsafe{libc::dlopen(c"libcuda.so.1".as_ptr(),libc::RTLD_NOW|libc::RTLD_LOCAL)}; if library.is_null(){return Err(Error::LibraryUnavailable)} // SAFETY: cuMemcpyAsync unified-address Linux64 signature. let p=unsafe{libc::dlsym(library,c"cuMemcpyAsync".as_ptr())}; + // SAFETY: `library` is the handle just opened and not yet shared; closed once on this error path. if p.is_null(){unsafe{libc::dlclose(library)};return Err(Error::MissingSymbol("cuMemcpyAsync"))} + // SAFETY: `Copy` is the exact cuMemcpyAsync(dst, src, bytes, stream) signature. let copy=unsafe{std::mem::transmute::<*mut c_void,Copy>(p)};Ok(Self{library,copy}) } pub(crate) fn copy<'ctx>(&self,c:&'ctx Context<'ctx>,w:&mut NativeBatchWorkspace<'ctx>,ranges:&[(u64,u64,usize)])->Result<()>{ @@ -44,7 +47,9 @@ mod enabled { combine(combine(op,sync),pop) } } - impl Drop for Transfer{fn drop(&mut self){if !self.library.is_null(){unsafe{libc::dlclose(self.library)};self.library=std::ptr::null_mut();}}} + // SAFETY (Drop): `copy` is never called after drop; libcuda itself stays loaded (the driver holds its own reference), and +// every `Transfer::copy*` drains its stream before returning, so no enqueued copy outlives the dlclose. +impl Drop for Transfer{fn drop(&mut self){if !self.library.is_null(){unsafe{libc::dlclose(self.library)};self.library=std::ptr::null_mut();}}} } #[cfg(not(all(feature="cuda-driver",target_os="linux",target_pointer_width="64")))] mod enabled{use super::*;pub(crate) struct Transfer;impl Transfer{pub(crate) fn new()->Result{Err(Error::LibraryUnavailable)}pub(crate) fn copy<'ctx>(&self,_:&'ctx Context<'ctx>,_:&mut NativeBatchWorkspace<'ctx>,_:&[(u64,u64,usize)])->Result<()>{Err(Error::LibraryUnavailable)}pub(crate) fn copy_fenced<'ctx>(&self,_:&'ctx Context<'ctx>,_:&mut NativeBatchWorkspace<'ctx>,_:&[(u64,u64,usize)])->Result<()>{Err(Error::LibraryUnavailable)}}} diff --git a/crates/model-format/src/gguf_resident.rs b/crates/model-format/src/gguf_resident.rs index 1ead9d26..48883484 100644 --- a/crates/model-format/src/gguf_resident.rs +++ b/crates/model-format/src/gguf_resident.rs @@ -542,4 +542,47 @@ mod retained_lease_test { drop(mapped); std::fs::remove_file(path).unwrap(); } + + /// A shortened file must never be mapped: the mapping would extend past EOF and fault (SIGBUS) on the missing + /// tail. `map_resident_tensor` compares the file length with the verified size before it maps. + #[cfg(target_os = "linux")] + #[test] + fn mapped_tensor_refuses_a_file_shortened_after_verification() { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "strata-bank-map-short-{}-{nonce}.gguf", + std::process::id() + )); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend(1u64.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + let name = b"public.mapped.short"; + bytes.extend((name.len() as u64).to_le_bytes()); + bytes.extend(name); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(16u64.to_le_bytes()); + bytes.extend(0u32.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + for word in [0x80000000u32, 0x3f800000, 0xbf800000, 0x40490fdb].into_iter().cycle().take(16) { + bytes.extend(word.to_le_bytes()); + } + std::fs::write(&path, &bytes).unwrap(); + let hex = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::(); + let mut source = VerifiedGgufFile::open(&path, &format!("sha256:{hex}")).unwrap(); + assert!(source.map_resident_tensor(0).is_ok()); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len((bytes.len() - 1) as u64) + .unwrap(); + assert!(source.map_resident_tensor(0).is_err()); + drop(source); + std::fs::remove_file(path).unwrap(); + } }