Skip to main content

singe_cuda/module/
image.rs

1use std::borrow::Cow;
2
3use crate::error::{Error, Result};
4
5/// Borrowed or owned bytes containing CUDA device code.
6///
7/// Every image is nonempty and is either NUL-terminated PTX text or a self-describing binary image.
8/// [`ModuleImage::from_ptx`] checks PTX text, compilers in this crate produce their images directly, and [`ModuleImage::from_bytes_unchecked`] takes binaries on the caller's word.
9#[derive(Debug, Clone)]
10pub struct ModuleImage<'a> {
11    data: Cow<'a, [u8]>,
12}
13
14impl<'a> ModuleImage<'a> {
15    /// Creates an image from PTX text, appending a NUL terminator if `ptx` does not end with one.
16    ///
17    /// Borrowed text that already ends with a NUL byte stays borrowed.
18    ///
19    /// # Errors
20    ///
21    /// Returns `Error::Empty` if `ptx` holds no text before its optional NUL terminator.
22    /// Returns `Error::InteriorNul` if the text contains a NUL byte before its end.
23    pub fn from_ptx(ptx: impl Into<Cow<'a, [u8]>>) -> Result<Self> {
24        let ptx = ptx.into();
25        let text = ptx.strip_suffix(&[0]).unwrap_or(&ptx[..]);
26        if text.is_empty() {
27            return Err(Error::empty("module image"));
28        }
29
30        if text.contains(&0) {
31            return Err(Error::InteriorNul);
32        }
33
34        let data = if ptx.last() == Some(&0) {
35            ptx
36        } else {
37            let mut terminated = ptx.into_owned();
38            terminated.push(0);
39            Cow::Owned(terminated)
40        };
41        Ok(Self { data })
42    }
43
44    // NVRTC and nvJitLink return NUL-terminated PTX or self-describing binaries, so only emptiness needs checking.
45    #[cfg(any(feature = "nvrtc_13_4", feature = "nvjitlink_13_4"))]
46    pub(crate) fn from_compiler_output(data: impl Into<Cow<'a, [u8]>>) -> Result<Self> {
47        let data = data.into();
48        if data.is_empty() {
49            return Err(Error::empty("module image"));
50        }
51        Ok(Self { data })
52    }
53
54    /// Creates an image from device-code bytes without checking them.
55    ///
56    /// # Safety
57    ///
58    /// `data` must be nonempty and must be a complete cubin, fatbin, ELF, or Tile IR image whose headers describe sizes and offsets within `data`, or PTX text ending in its only NUL byte.
59    /// CUDA's loaders take no length and trust the image headers, so other bytes make them read out of bounds.
60    #[must_use]
61    pub unsafe fn from_bytes_unchecked(data: impl Into<Cow<'a, [u8]>>) -> Self {
62        Self { data: data.into() }
63    }
64
65    /// Returns a pointer to the image bytes, valid while the image storage remains alive.
66    #[must_use]
67    pub fn as_ptr(&self) -> *const () {
68        self.data.as_ptr().cast()
69    }
70
71    /// Borrows the complete image bytes, including the NUL terminator of PTX text.
72    #[must_use]
73    pub fn as_bytes(&self) -> &[u8] {
74        self.data.as_ref()
75    }
76}