1use 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 pub enum Status: u32 {
24 Success = NVJITLINK_SUCCESS => "success",
26 UnrecognizedOption = NVJITLINK_ERROR_UNRECOGNIZED_OPTION => "unrecognized option",
28 MissingArch = NVJITLINK_ERROR_MISSING_ARCH => "missing arch",
30 InvalidInput = NVJITLINK_ERROR_INVALID_INPUT => "invalid input",
32 PtxCompile = NVJITLINK_ERROR_PTX_COMPILE => "ptx compile",
34 NvvmCompile = NVJITLINK_ERROR_NVVM_COMPILE => "nvvm compile",
36 Internal = NVJITLINK_ERROR_INTERNAL => "internal",
38 Threadpool = NVJITLINK_ERROR_THREADPOOL => "threadpool",
40 UnrecognizedInput = NVJITLINK_ERROR_UNRECOGNIZED_INPUT => "unrecognized input",
42 Finalize = NVJITLINK_ERROR_FINALIZE => "finalize",
44 NullInput = NVJITLINK_ERROR_NULL_INPUT => "null input",
46 IncompatibleOptions = NVJITLINK_ERROR_INCOMPATIBLE_OPTIONS => "incompatible options",
48 IncorrectInputType = NVJITLINK_ERROR_INCORRECT_INPUT_TYPE => "incorrect input type",
50 ArchMismatch = NVJITLINK_ERROR_ARCH_MISMATCH => "arch mismatch",
52 OutdatedLibrary = NVJITLINK_ERROR_OUTDATED_LIBRARY => "outdated library",
54 MissingFatbin = NVJITLINK_ERROR_MISSING_FATBIN => "missing fatbin",
56 UnrecognizedArch = NVJITLINK_ERROR_UNRECOGNIZED_ARCH => "unrecognized arch",
58 UnsupportedArch = NVJITLINK_ERROR_UNSUPPORTED_ARCH => "unsupported arch",
60 LtoNotEnabled = NVJITLINK_ERROR_LTO_NOT_ENABLED => "lto not enabled",
62 }
63}
64
65#[derive(Debug, Clone, Copy)]
67#[repr(u32)]
68#[non_exhaustive]
69pub enum InputType {
70 Cubin = sys::nvJitLinkInputType::NVJITLINK_INPUT_CUBIN.0,
72 Ptx = sys::nvJitLinkInputType::NVJITLINK_INPUT_PTX.0,
74 LtoIr = sys::nvJitLinkInputType::NVJITLINK_INPUT_LTOIR.0,
76 Fatbin = sys::nvJitLinkInputType::NVJITLINK_INPUT_FATBIN.0,
78 Object = sys::nvJitLinkInputType::NVJITLINK_INPUT_OBJECT.0,
80 Library = sys::nvJitLinkInputType::NVJITLINK_INPUT_LIBRARY.0,
82 Index = sys::nvJitLinkInputType::NVJITLINK_INPUT_INDEX.0,
84 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum OutputKind {
106 Cubin,
108 Ptx,
110 LtoIr,
113}
114
115#[derive(Debug, Clone)]
118pub struct LinkOptions {
119 pub architecture: GpuArchitecture,
121 pub lto: bool,
123 pub output: OutputKind,
125 pub line_info: bool,
127 pub raw_options: Vec<String>,
129}
130
131impl LinkOptions {
132 #[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#[derive(Debug)]
147pub struct LinkedArtifact {
148 pub kind: OutputKind,
150 bytes: Vec<u8>,
151 pub info_log: String,
154}
155
156impl LinkedArtifact {
157 #[must_use]
159 pub fn as_bytes(&self) -> &[u8] {
160 &self.bytes
161 }
162
163 #[must_use]
165 pub fn into_bytes(self) -> Vec<u8> {
166 self.bytes
167 }
168}
169
170#[derive(Debug)]
172pub struct Linker {
173 handle: sys::nvJitLinkHandle,
174 output: OutputKind,
175}
176
177#[derive(Debug)]
181pub struct RawLinker {
182 pub handle: sys::nvJitLinkHandle,
184 pub output: OutputKind,
186}
187
188impl Linker {
189 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 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 #[must_use]
243 pub fn as_raw(&self) -> sys::nvJitLinkHandle {
244 self.handle
245 }
246
247 #[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 #[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 pub fn add_data(&mut self, kind: InputType, bytes: &[u8], name: &str) -> Result<()> {
286 let name = CString::new(name)?;
287 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 pub fn add_file(&mut self, kind: InputType, file: &str) -> Result<()> {
306 let file = CString::new(file)?;
307 self.check(unsafe { sys::__nvJitLinkAddFile_13_4(self.handle, kind.raw(), file.as_ptr()) })
309 }
310
311 pub fn complete(self) -> Result<LinkedArtifact> {
318 self.check(unsafe { sys::__nvJitLinkComplete_13_4(self.handle) })?;
320 let mut size = 0;
321 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 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 #[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 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 let status = unsafe { sys::__nvJitLinkDestroy_13_4(&raw mut self.handle) };
410 if status != sys::nvJitLinkResult::NVJITLINK_SUCCESS {
411 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});