Skip to main content

singe_cuda/
nvjitlink.rs

1//! Runtime linking of PTX, cubin and link-time optimization IR.
2
3use std::{ffi::CString, mem, ptr, result::Result as StdResult};
4
5use singe_core::{impl_enum_display, report_cleanup_failure};
6use singe_cuda_sys::nvjitlink as sys;
7
8use crate::{
9    architecture::GpuArchitecture,
10    error::{Error, Result},
11};
12
13singe_core::wrapper_status! {
14    library = "nvjitlink",
15    error = Error::NvJitLink,
16    raw = sys::nvJitLinkResult,
17    success = NVJITLINK_SUCCESS,
18    absence = singe_cuda_sys::take_absence,
19    check = check_nvjitlink,
20    diagnostic = String::new,
21    unknown = "UNKNOWN_NVJITLINK_STATUS",
22    /// API call result codes returned by nvJitLink.
23    pub enum Status: u32 {
24        /// Successful completion.
25        Success = NVJITLINK_SUCCESS => "success",
26        /// Unrecognized Option
27        UnrecognizedOption = NVJITLINK_ERROR_UNRECOGNIZED_OPTION => "unrecognized option",
28        /// Option `-arch=sm_NN` not specified
29        MissingArch = NVJITLINK_ERROR_MISSING_ARCH => "missing arch",
30        /// Invalid Input
31        InvalidInput = NVJITLINK_ERROR_INVALID_INPUT => "invalid input",
32        /// Issue during PTX Compilation
33        PtxCompile = NVJITLINK_ERROR_PTX_COMPILE => "ptx compile",
34        /// Issue during NVVM Compilation
35        NvvmCompile = NVJITLINK_ERROR_NVVM_COMPILE => "nvvm compile",
36        /// Internal Error
37        Internal = NVJITLINK_ERROR_INTERNAL => "internal",
38        /// Issue with Thread Pool
39        Threadpool = NVJITLINK_ERROR_THREADPOOL => "threadpool",
40        /// Unrecognized Input
41        UnrecognizedInput = NVJITLINK_ERROR_UNRECOGNIZED_INPUT => "unrecognized input",
42        /// Finalizer Error
43        Finalize = NVJITLINK_ERROR_FINALIZE => "finalize",
44        /// Null Input
45        NullInput = NVJITLINK_ERROR_NULL_INPUT => "null input",
46        /// Incompatible Options
47        IncompatibleOptions = NVJITLINK_ERROR_INCOMPATIBLE_OPTIONS => "incompatible options",
48        /// Incorrect Input Type
49        IncorrectInputType = NVJITLINK_ERROR_INCORRECT_INPUT_TYPE => "incorrect input type",
50        /// Arch Mismatch
51        ArchMismatch = NVJITLINK_ERROR_ARCH_MISMATCH => "arch mismatch",
52        /// Outdated Library
53        OutdatedLibrary = NVJITLINK_ERROR_OUTDATED_LIBRARY => "outdated library",
54        /// Missing Fatbin
55        MissingFatbin = NVJITLINK_ERROR_MISSING_FATBIN => "missing fatbin",
56        /// Unrecognized -arch value
57        UnrecognizedArch = NVJITLINK_ERROR_UNRECOGNIZED_ARCH => "unrecognized arch",
58        /// Unsupported -arch value
59        UnsupportedArch = NVJITLINK_ERROR_UNSUPPORTED_ARCH => "unsupported arch",
60        /// Requires -lto
61        LtoNotEnabled = NVJITLINK_ERROR_LTO_NOT_ENABLED => "lto not enabled",
62    }
63}
64
65/// The kind of inputs that can be passed to the linker.
66#[derive(Debug, Clone, Copy)]
67#[repr(u32)]
68#[non_exhaustive]
69pub enum InputType {
70    /// CUDA binaries.
71    Cubin = sys::nvJitLinkInputType::NVJITLINK_INPUT_CUBIN.0,
72    /// PTX.
73    Ptx = sys::nvJitLinkInputType::NVJITLINK_INPUT_PTX.0,
74    /// LTO-IR.
75    LtoIr = sys::nvJitLinkInputType::NVJITLINK_INPUT_LTOIR.0,
76    /// Fatbin.
77    Fatbin = sys::nvJitLinkInputType::NVJITLINK_INPUT_FATBIN.0,
78    /// Host object.
79    Object = sys::nvJitLinkInputType::NVJITLINK_INPUT_OBJECT.0,
80    /// Host library.
81    Library = sys::nvJitLinkInputType::NVJITLINK_INPUT_LIBRARY.0,
82    /// Index file.
83    Index = sys::nvJitLinkInputType::NVJITLINK_INPUT_INDEX.0,
84    /// Dynamically chooses from the valid types.
85    Any = sys::nvJitLinkInputType::NVJITLINK_INPUT_ANY.0,
86}
87
88impl InputType {
89    fn raw(self) -> sys::nvJitLinkInputType {
90        match self {
91            Self::Cubin => sys::nvJitLinkInputType::NVJITLINK_INPUT_CUBIN,
92            Self::Ptx => sys::nvJitLinkInputType::NVJITLINK_INPUT_PTX,
93            Self::LtoIr => sys::nvJitLinkInputType::NVJITLINK_INPUT_LTOIR,
94            Self::Fatbin => sys::nvJitLinkInputType::NVJITLINK_INPUT_FATBIN,
95            Self::Object => sys::nvJitLinkInputType::NVJITLINK_INPUT_OBJECT,
96            Self::Library => sys::nvJitLinkInputType::NVJITLINK_INPUT_LIBRARY,
97            Self::Index => sys::nvJitLinkInputType::NVJITLINK_INPUT_INDEX,
98            Self::Any => sys::nvJitLinkInputType::NVJITLINK_INPUT_ANY,
99        }
100    }
101}
102
103/// Output produced after linking.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum OutputKind {
106    /// Linked CUDA binary.
107    Cubin,
108    /// PTX after linking; requires link-time optimization.
109    Ptx,
110    /// Linked LTO-IR in LTOIR container format, rather than raw bitcode.
111    /// Requires link-time optimization.
112    LtoIr,
113}
114
115/// Supported link options.
116/// Architecture is required by nvJitLink.
117#[derive(Debug, Clone)]
118pub struct LinkOptions {
119    /// Target architecture; nvJitLink requires `-arch=sm_NN`.
120    pub architecture: GpuArchitecture,
121    /// Do link time optimization.
122    pub lto: bool,
123    /// Linked output to retrieve after completion.
124    pub output: OutputKind,
125    /// Generate line information.
126    pub line_info: bool,
127    /// Additional nvJitLink options, passed without shell interpretation.
128    pub raw_options: Vec<String>,
129}
130
131impl LinkOptions {
132    /// Creates linker settings for the target architecture, with cubin output, link-time optimization disabled, and no additional options.
133    #[must_use]
134    pub fn new(architecture: GpuArchitecture) -> Self {
135        Self {
136            architecture,
137            lto: false,
138            output: OutputKind::Cubin,
139            line_info: false,
140            raw_options: Vec::new(),
141        }
142    }
143}
144
145/// Owned linked output and informational diagnostics.
146#[derive(Debug)]
147pub struct LinkedArtifact {
148    /// Format of the owned linked output.
149    pub kind: OutputKind,
150    bytes: Vec<u8>,
151    /// Linker informational diagnostics.
152    /// Empty if the native log is unavailable or its retrieval failed.
153    pub info_log: String,
154}
155
156impl LinkedArtifact {
157    /// Borrows the linked output bytes.
158    #[must_use]
159    pub fn as_bytes(&self) -> &[u8] {
160        &self.bytes
161    }
162
163    /// Consumes the artifact and returns the owned linked output bytes.
164    #[must_use]
165    pub fn into_bytes(self) -> Vec<u8> {
166        self.bytes
167    }
168}
169
170/// Linker handle used during linking operations.
171#[derive(Debug)]
172pub struct Linker {
173    handle: sys::nvJitLinkHandle,
174    output: OutputKind,
175}
176
177/// Raw ownership of a linker and the output mode it was created with.
178///
179/// Destroy `handle` with nvJitLink, or re-adopt the value with [`Linker::from_raw`].
180#[derive(Debug)]
181pub struct RawLinker {
182    /// Native linker handle.
183    pub handle: sys::nvJitLinkHandle,
184    /// Output mode the linker was created with.
185    pub output: OutputKind,
186}
187
188impl Linker {
189    /// Creates an instance of the linker with the given input options.
190    ///
191    /// # Errors
192    ///
193    /// Returns an error if PTX or LTO IR output is requested without link-time optimization, the option count does not fit a `u32`, an option contains an interior NUL byte, nvJitLink cannot create the linker, or it returns a null handle.
194    pub fn create(options: LinkOptions) -> Result<Self> {
195        if options.output != OutputKind::Cubin && !options.lto {
196            return Err(Error::out_of_range("output kind"));
197        }
198
199        let mut arguments = vec![format!("-arch={}", options.architecture)];
200        if options.lto {
201            arguments.push("-lto".into());
202        }
203
204        if options.output == OutputKind::Ptx {
205            arguments.push("-ptx".into());
206        }
207
208        if options.line_info {
209            arguments.push("-lineinfo".into());
210        }
211
212        arguments.extend(options.raw_options);
213        let args = arguments
214            .into_iter()
215            .map(CString::new)
216            .collect::<StdResult<Vec<_>, _>>()?;
217        let pointers = args.iter().map(|s| s.as_ptr()).collect::<Vec<_>>();
218        let mut handle = ptr::null_mut();
219        // SAFETY: `handle` is a local output, and `pointers` holds the counted NUL-terminated options in `args`, which outlive the call.
220        let code = unsafe {
221            sys::__nvJitLinkCreate_13_4(
222                &raw mut handle,
223                pointers
224                    .len()
225                    .try_into()
226                    .map_err(|_| Error::out_of_range("linker option count"))?,
227                pointers.as_ptr(),
228            )
229        };
230        let linker = Self {
231            handle,
232            output: options.output,
233        };
234        linker.check(code)?;
235        if linker.handle.is_null() {
236            return Err(Error::NullHandle);
237        }
238        Ok(linker)
239    }
240
241    /// Borrows the linker handle.
242    #[must_use]
243    pub fn as_raw(&self) -> sys::nvJitLinkHandle {
244        self.handle
245    }
246
247    /// Takes ownership of a linker created with the specified output mode.
248    ///
249    /// # Safety
250    ///
251    /// `raw.handle` must be live and uniquely owned, and its options must match `raw.output`.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error if `raw.handle` is null.
256    #[expect(
257        clippy::needless_pass_by_value,
258        reason = "taking the raw owner by value transfers ownership of its handle"
259    )]
260    pub unsafe fn from_raw(raw: RawLinker) -> Result<Self> {
261        if raw.handle.is_null() {
262            return Err(Error::NullHandle);
263        }
264        Ok(Self {
265            handle: raw.handle,
266            output: raw.output,
267        })
268    }
269
270    /// Transfers ownership of the linker handle and its output mode to the caller.
271    #[must_use]
272    pub fn into_raw(mut self) -> RawLinker {
273        RawLinker {
274            handle: mem::replace(&mut self.handle, ptr::null_mut()),
275            output: self.output,
276        }
277    }
278
279    /// Adds data to the link.
280    ///
281    /// # Errors
282    ///
283    /// Returns an error if `name` contains an interior NUL or the native linker rejects the input image, format, or handle.
284    /// Native failure status and linker diagnostics are retained in `Error::NvJitLink`.
285    pub fn add_data(&mut self, kind: InputType, bytes: &[u8], name: &str) -> Result<()> {
286        let name = CString::new(name)?;
287        // SAFETY: `self` owns the live linker exclusively, and `bytes` and the NUL-terminated `name` are borrowed for the call, which copies them.
288        self.check(unsafe {
289            sys::__nvJitLinkAddData_13_4(
290                self.handle,
291                kind.raw(),
292                bytes.as_ptr().cast(),
293                bytes.len(),
294                name.as_ptr(),
295            )
296        })
297    }
298
299    /// Adds a file to the link.
300    ///
301    /// # Errors
302    ///
303    /// Returns an error if `file` contains an interior NUL or the native linker cannot read or accept the file for the selected input type.
304    /// Native failure status and linker diagnostics are retained in `Error::NvJitLink`.
305    pub fn add_file(&mut self, kind: InputType, file: &str) -> Result<()> {
306        let file = CString::new(file)?;
307        // SAFETY: `self` owns the live linker exclusively, and `file` is a NUL-terminated path borrowed for the call.
308        self.check(unsafe { sys::__nvJitLinkAddFile_13_4(self.handle, kind.raw(), file.as_ptr()) })
309    }
310
311    /// Does the actual link and retrieves the linked output.
312    ///
313    /// # Errors
314    ///
315    /// Returns an error if native linking fails or the selected output size or contents cannot be retrieved.
316    /// The consumed linker is destroyed on both success and failure; successful output owns its bytes independently.
317    pub fn complete(self) -> Result<LinkedArtifact> {
318        // SAFETY: `self` owns the live linker, consumed by this call.
319        self.check(unsafe { sys::__nvJitLinkComplete_13_4(self.handle) })?;
320        let mut size = 0;
321        // SAFETY: the linker completed above, and `size` is a local output.
322        self.check(unsafe {
323            match self.output {
324                OutputKind::Cubin => {
325                    sys::__nvJitLinkGetLinkedCubinSize_13_4(self.handle, &raw mut size)
326                }
327                OutputKind::Ptx => {
328                    sys::__nvJitLinkGetLinkedPtxSize_13_4(self.handle, &raw mut size)
329                }
330                OutputKind::LtoIr => {
331                    sys::__nvJitLinkGetLinkedLTOIRSize_13_4(self.handle, &raw mut size)
332                }
333            }
334        })?;
335        let mut bytes = vec![0; size];
336        // SAFETY: `bytes` holds the `size` bytes the linker reported for the same output kind.
337        self.check(unsafe {
338            match self.output {
339                OutputKind::Cubin => {
340                    sys::__nvJitLinkGetLinkedCubin_13_4(self.handle, bytes.as_mut_ptr().cast())
341                }
342                OutputKind::Ptx => {
343                    sys::__nvJitLinkGetLinkedPtx_13_4(self.handle, bytes.as_mut_ptr().cast())
344                }
345                OutputKind::LtoIr => {
346                    sys::__nvJitLinkGetLinkedLTOIR_13_4(self.handle, bytes.as_mut_ptr().cast())
347                }
348            }
349        })?;
350        Ok(LinkedArtifact {
351            kind: self.output,
352            bytes,
353            info_log: self.log(false),
354        })
355    }
356
357    /// Returns the informational log generated by the linker.
358    #[must_use]
359    pub fn info_log(&self) -> String {
360        self.log(false)
361    }
362
363    fn check(&self, status: sys::nvJitLinkResult) -> Result<()> {
364        Error::check_nvjitlink(status).map_err(|error| match error {
365            Error::NvJitLink { code, .. } => Error::NvJitLink {
366                code,
367                diagnostic: self.log(true),
368            },
369            error => error,
370        })
371    }
372
373    fn log(&self, error: bool) -> String {
374        if self.handle.is_null() {
375            return String::new();
376        }
377        // SAFETY: the handle is non-null and owned by `self`, `size` is a local output, and `bytes` holds the `size` bytes reported for the same log.
378        unsafe {
379            let mut size = 0;
380            let result = if error {
381                sys::__nvJitLinkGetErrorLogSize_13_4(self.handle, &raw mut size)
382            } else {
383                sys::__nvJitLinkGetInfoLogSize_13_4(self.handle, &raw mut size)
384            };
385            if result != sys::nvJitLinkResult::NVJITLINK_SUCCESS || size == 0 {
386                return String::new();
387            }
388
389            let mut bytes = vec![0u8; size];
390            let result = if error {
391                sys::__nvJitLinkGetErrorLog_13_4(self.handle, bytes.as_mut_ptr().cast())
392            } else {
393                sys::__nvJitLinkGetInfoLog_13_4(self.handle, bytes.as_mut_ptr().cast())
394            };
395            if result != sys::nvJitLinkResult::NVJITLINK_SUCCESS {
396                return String::new();
397            }
398            String::from_utf8_lossy(&bytes)
399                .trim_end_matches('\0')
400                .to_owned()
401        }
402    }
403}
404
405impl Drop for Linker {
406    fn drop(&mut self) {
407        if !self.handle.is_null() {
408            // SAFETY: this wrapper owns the non-null linker, and nvJitLink nulls the handle field it destroys.
409            let status = unsafe { sys::__nvJitLinkDestroy_13_4(&raw mut self.handle) };
410            if status != sys::nvJitLinkResult::NVJITLINK_SUCCESS {
411                // The linker log is not read through a handle whose destruction failed.
412                let error = Error::from(Status::from(status));
413                report_cleanup_failure("destroy", "nvjitlink linker", &error);
414            }
415        }
416    }
417}
418
419impl_enum_display!(InputType, {
420    InputType::Cubin => "NVJITLINK_INPUT_CUBIN",
421    InputType::Ptx => "NVJITLINK_INPUT_PTX",
422    InputType::LtoIr => "NVJITLINK_INPUT_LTOIR",
423    InputType::Fatbin => "NVJITLINK_INPUT_FATBIN",
424    InputType::Object => "NVJITLINK_INPUT_OBJECT",
425    InputType::Library => "NVJITLINK_INPUT_LIBRARY",
426    InputType::Index => "NVJITLINK_INPUT_INDEX",
427    InputType::Any => "NVJITLINK_INPUT_ANY",
428});